-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathskala_api.py
More file actions
3304 lines (2567 loc) · 117 KB
/
Copy pathskala_api.py
File metadata and controls
3304 lines (2567 loc) · 117 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (C) 2023 David Mossakowski
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
from copy import deepcopy
import json
import os
import io
import glob
import random
import uuid
import time
from datetime import datetime, date, timedelta
import competitionsEngine
import csv
from functools import wraps
from dataclasses import dataclass
from flask import Flask, redirect, url_for, session, request, render_template, send_file, send_from_directory, jsonify, Response, \
stream_with_context, copy_current_request_context, g
import logging
from logging_config import attach_request_logging
from flask import Blueprint
import activities_db as activities_db
import skala_db
from io import BytesIO
from flask import send_file
from collections import defaultdict
#import Activity
#from flask_openapi3 import APIBlueprint, OpenAPI, Tag
#book_tag = Tag(name="book", description="Some Book")
#comp_tag = Tag(name="competition", description="""
# Some competition
# with multiple lines
# #header also
# """)
# Third party libraries
from flask import Flask, redirect, request, url_for
from flask_login import (
LoginManager,
current_user,
login_required,
login_user,
logout_user,
)
from oauthlib.oauth2 import WebApplicationClient
import requests
from pydantic import BaseModel
# Email login service (shared with server)
from src.email_login import EmailLoginService
from src.email_sender import EmailSender
from src.User import User
import jwt
# Google auth (optional)
try:
from google.oauth2 import id_token as google_id_token # type: ignore
from google.auth.transport import requests as google_requests # type: ignore
GOOGLE_AUTH_AVAILABLE = True
except Exception:
GOOGLE_AUTH_AVAILABLE = False
from authlib.integrations.flask_client import OAuth
from authlib.integrations.flask_client import OAuthError
languages = {}
grades = ['?', '1', '2', '3', '4a', '4b', '4c', '5a','5a+', '5b', '5b+', '5c','5c+', '6a', '6a+', '6b', '6b+', '6c', '6c+', '7a', '7a+', '7b', '7b+', '7c', '7c+', '8a', '8a+', '8b', '8b+', '8c', '8c+', '9a', '9a+', '9b', '9b+', '9c']
DATA_DIRECTORY = os.getenv('DATA_DIRECTORY')
if DATA_DIRECTORY is None:
DATA_DIRECTORY = os.getcwd()
COMPETITIONS_DB = DATA_DIRECTORY + "/db/competitions.sqlite"
# ID, date, name, location
COMPETITIONS_TABLE = "competitions"
# ID, name, club, m/f, list of climbs
CLIMBERS_TABLE = "climbers"
FSGT_APP_ID = os.getenv('FSGT_APP_ID')
FSGT_APP_SECRET = os.getenv('FSGT_APP_SECRET')
GOOGLE_DISCOVERY_URL = (
"https://accounts.google.com/.well-known/openid-configuration"
)
#skala_api_app = APIBlueprint('skala_api', __name__, url_prefix='/api1', doc_ui=True, abp_tags= [book_tag, comp_tag])
skala_api_app = Blueprint('skala_api', __name__, url_prefix='/api1')
attach_request_logging(
skala_api_app,
app_name='api',
allowed_path_substrings=['/api1']
)
skala_api_app.debug = True
skala_api_app.secret_key = 'development'
oauth = OAuth(skala_api_app)
genres = {"test": "1"}
authenticated = False
# Initialize email login service (captcha None for API)
_email_sender = EmailSender(reference_data=competitionsEngine.reference_data)
email_login_service_api = EmailLoginService(competitionsEngine, _email_sender, bcrypt=None, simple_captcha=None) # bcrypt later bound
try:
# Attempt to import bcrypt instance from server if available
from server import bcrypt as _bcrypt_instance # type: ignore
email_login_service_api.bcrypt = _bcrypt_instance
except Exception:
pass
# Third party libraries
from flask import Flask, redirect, request, url_for
from flask_login import (
LoginManager,
current_user,
login_required,
login_user,
logout_user,
)
from oauthlib.oauth2 import WebApplicationClient
import requests
# Internal imports
# Flask app setup
skala_api_app.secret_key = os.environ.get("SECRET_KEY") or os.urandom(24)
UPLOAD_FOLDER = os.path.join(DATA_DIRECTORY,'uploads')
ALLOWED_EXTENSIONS = set(['txt', 'png', 'jpg', 'jpeg', 'gif'])
# skala_api_app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
#from flask_openapi3 import Info, Tag
#from flask_openapi3 import OpenAPI
#info = Info(title="book API", version="1.0.0")
#book_tag = Tag(name="book", description="Some Book")
class Activity1(BaseModel):
activity_name: str
gym_id: str
date: datetime
# User session management setup
# https://flask-login.readthedocs.io/en/latest
@skala_api_app.before_request
def x(*args, **kwargs):
#logging.debug('api before request '+str(session.get('language'))+ ' accepted languages='+str(request.accept_languages))
if not session.get('language'):
#kk = competitionsEngine.supported_languages.keys()
language = request.accept_languages.best_match(competitionsEngine.supported_languages.keys())
if language is None:
language = 'fr_FR'
session['language'] = language
recreate_session_from_jwt()
#logging.debug ("api setting language to session language="+str(session['language']))
set_language(session['language'])
@skala_api_app.route('/api/language/<language>')
def set_language(language=None):
if language is None:
language = 'fr_FR'
session['language'] = language
#logging.debug('api setting language requested to '+str(language))
langpack = competitionsEngine.reference_data['languages'].get(language)
if langpack is None:
if language.startswith('pl'):
langpack = competitionsEngine.reference_data['languages']['pl_PL']
elif language.startswith('en'):
langpack = competitionsEngine.reference_data['languages']['en_US']
elif language.startswith('fr'):
langpack = competitionsEngine.reference_data['languages']['fr_FR']
else:
langpack = competitionsEngine.reference_data['languages']['fr_FR']
logging.warning('api setting language not found '+str(language))
competitionsEngine.reference_data['current_language'] = langpack
return language
@skala_api_app.route('/language')
def get_translations():
language = session.get('language')
if language is None:
language = 'fr_FR'
langpack = competitionsEngine.reference_data['languages'].get(language)
return langpack
@skala_api_app.route('/language')
def get_language():
if not session.get('language'):
return json.dumps({'language': 'fr_FR'})
else:
return json.dumps({'language': session['language']})
@skala_api_app.route('/langpack')
def get_default_langpack():
if not session.get('language'):
return json.dumps(competitionsEngine.reference_data['languages']['fr_FR'])
else:
return json.dumps(competitionsEngine.reference_data['languages'][session.get('language')])
@skala_api_app.route('/langpack/<language>')
def get_langpack(language=None):
if not session.get('language'):
return json.dumps(competitionsEngine.reference_data['languages']['fr_FR'])
else:
set_language(language)
return json.dumps(competitionsEngine.reference_data['languages'][session.get('language')])
def is_logged_in():
if session is not None and session.get('expires_at') is not None:
return True
else:
session["wants_url"] = request.url
return False
# ---------------- JWT SUPPORT -----------------
JWT_SECRET = os.getenv('JWT_SECRET', os.getenv('SECRET_KEY', 'dev-secret'))
JWT_ALG = 'HS256'
JWT_EXP_SECONDS = 60 * 60 * 24 * 356 * 100 # 100 years
def create_jwt(
email: str,
user_id: str | None = None,
*,
name: str | None = None,
authsource: str | None = None,
expires_at: int | None = None,
picture: str | None = None,
):
now = int(time.time())
payload = {
'sub': email,
'uid': user_id,
'iat': now,
'exp': now + JWT_EXP_SECONDS,
}
# Prefer explicit parameters, fallback to session values
if name or session.get('name'):
payload['name'] = name if name is not None else session.get('name')
if authsource or session.get('authsource'):
payload['authsource'] = authsource if authsource is not None else session.get('authsource')
if expires_at or session.get('expires_at'):
payload['expires_at'] = expires_at if expires_at is not None else session.get('expires_at')
if picture is not None:
payload['picture'] = picture
elif session.get('picture') is not None:
payload['picture'] = session.get('picture')
return jwt.encode(payload, JWT_SECRET, algorithm=JWT_ALG)
def decode_jwt(token: str):
try:
return jwt.decode(token, JWT_SECRET, algorithms=[JWT_ALG])
except jwt.ExpiredSignatureError:
return {'error': 'token_expired'}
except Exception:
return {'error': 'invalid_token'}
def jwt_required(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
auth_header = request.headers.get('Authorization', '')
token = auth_header[7:].strip() if auth_header.startswith('Bearer ') else None
if not token:
return jsonify({'error': 'missing_token'}), 401
decoded = decode_jwt(token)
if 'error' in decoded:
return jsonify({'error': decoded['error']}), 401
request.jwt_email = decoded.get('sub') # type: ignore
return fn(*args, **kwargs)
return wrapper
def session_or_jwt_required(fn):
"""Allow either JWT (Authorization: Bearer) or existing session email."""
@wraps(fn)
def wrapper(*args, **kwargs):
recreate_session_from_jwt
if not session.get('email'):
return jsonify({'error': 'unauthorized'}), 401
return fn(*args, **kwargs)
return wrapper
def recreate_session_from_jwt():
email = None
expires_at = None
picture = None
auth_header = request.headers.get('Authorization', '')
if auth_header.startswith('Bearer '):
decoded = decode_jwt(auth_header[7:].strip())
if isinstance(decoded, dict) and 'error' not in decoded:
email = decoded.get('sub')
expires_at = decoded.get('exp')
picture = decoded.get('picture')
session['email'] = email # ensure session email set
session['expires_at'] = expires_at # type: ignore
session['picture'] = picture # type: ignore
if not email:
cookie_token = request.cookies.get('skala3ma_jwt')
if cookie_token:
decoded = decode_jwt(cookie_token)
if isinstance(decoded, dict) and 'error' not in decoded:
email = decoded.get('sub')
expires_at = decoded.get('exp')
picture = decoded.get('picture')
session['email'] = email # ensure session email set
session['expires_at'] = expires_at # type: ignore
session['picture'] = picture # type: ignore
def admin_required(fn):
"""Admin decorator for API endpoints - returns JSON error"""
@wraps(fn)
def wrapper(*args, **kwargs):
email = session.get('email') if session else None
if email:
user = competitionsEngine.get_user_by_email(email)
if User.is_admin(user):
return fn(*args, **kwargs)
return jsonify({'error': 'admin_required'}), 403
return wrapper
def admin_required_ui(fn):
"""Admin decorator for UI routes - redirects to login page"""
@wraps(fn)
def decorated_function(*args, **kwargs):
if session != None:
email = session.get('email')
if email:
user = competitionsEngine.get_user_by_email(email)
if User.is_admin(user):
return fn(*args, **kwargs)
from flask import request, redirect, url_for
session["wants_url"] = request.url
return redirect(url_for("app_ui.fsgtlogin"))
return decorated_function
#@skala_api_app.get('/apitest', tags=[book_tag, comp_tag])
def testapi():
return {"code": 0, "message": "ok"}
@skala_api_app.post('/auth/login')
def api_email_login():
"""Email/password login returning JSON.
Body form or JSON: {"email":"...","password":"..."}
"""
data = request.get_json(silent=True) or request.form
email = data.get('email') if data else None
password = data.get('password') if data else None
# Ensure bcrypt available
if email_login_service_api.bcrypt is None:
from flask_bcrypt import Bcrypt
email_login_service_api.bcrypt = Bcrypt()
result = email_login_service_api.login_with_password(email, password, apply_session=True)
if result.get('success'):
user = result.get('user') or {}
user_obj = competitionsEngine.get_user_by_email(user.get('email')) if user else None
token = create_jwt(user.get('email'), user_obj.get('id') if user_obj else None)
result['token'] = token
status = 200 if result.get('success') else 401
return jsonify(result), status
@skala_api_app.post('/auth/google/login')
def api_google_login():
"""Exchange Google ID token for local JWT.
Input JSON: {"id_token": "<google id token>"}
"""
if not GOOGLE_AUTH_AVAILABLE:
return jsonify({'success': False, 'error': 'google_auth_not_available'}), 501
data = request.get_json(silent=True) or {}
id_token_str = data.get('id_token')
if not id_token_str:
return jsonify({'success': False, 'error': 'missing_id_token'}), 400
client_id = os.getenv('GOOGLE_WEB_CLIENT_ID') or os.getenv('GOOGLE_CLIENT_ID')
try:
info = google_id_token.verify_oauth2_token(id_token_str, google_requests.Request(), client_id)
if info.get('iss') not in ('accounts.google.com', 'https://accounts.google.com'):
return jsonify({'success': False, 'error': 'invalid_issuer'}), 401
if not info.get('email'):
return jsonify({'success': False, 'error': 'no_email'}), 400
if info.get('email_verified') is False:
return jsonify({'success': False, 'error': 'email_not_verified'}), 401
except Exception as e:
logging.warning(f"Google token verification failed: {e}")
return jsonify({'success': False, 'error': 'invalid_token'}), 401
email = info['email'].lower()
sub = info.get('sub')
firstname = info.get('given_name')
lastname = info.get('family_name')
picture = info.get('picture')
user = competitionsEngine.get_user_by_email(email)
created = False
if not user:
# Minimal user record; adapt fields based on competitionsEngine expectations
user = {
'email': email,
'firstname': firstname,
'lastname': lastname,
'is_confirmed': True,
'auth_provider': 'google',
'google_sub': sub,
'gpictureurl': picture,
'permissions': {'general': []}
}
try:
competitionsEngine.upsert_user(user)
created = True
except Exception as e:
logging.error(f"Failed to create google user {email}: {e}")
return jsonify({'success': False, 'error': 'user_creation_failed'}), 500
else:
# Update picture / names if changed
updated = False
if picture and picture != user.get('gpictureurl'):
user['gpictureurl'] = picture; updated = True
if firstname and firstname != user.get('firstname'):
user['firstname'] = firstname; updated = True
if lastname and lastname != user.get('lastname'):
user['lastname'] = lastname; updated = True
if not user.get('is_confirmed'):
user['is_confirmed'] = True; updated = True
if updated:
try:
competitionsEngine.upsert_user(user)
except Exception as e:
logging.warning(f"Failed to update google user {email}: {e}")
# Issue JWT
db_user = competitionsEngine.get_user_by_email(email) or user
token = create_jwt(email, db_user.get('id'))
return jsonify({
'success': True,
'token': token,
'created': created,
'user': {
'email': db_user.get('email'),
'firstname': db_user.get('firstname'),
'lastname': db_user.get('lastname'),
'picture': db_user.get('gpictureurl') or db_user.get('fpictureurl') or picture
}
})
@skala_api_app.post('/auth/logout')
def api_logout():
"""Clear server-side session (logout). Always returns success."""
try:
# Remove typical auth keys but fall back to full clear.
for k in list(session.keys()):
session.pop(k, None)
session.clear()
except Exception:
pass
return jsonify({'success': True})
# ---------------- Additional Email Auth API Endpoints -----------------
def _extract_json_or_form():
return request.get_json(silent=True) or request.form or {}
@skala_api_app.post('/auth/register')
def api_email_register():
"""Initiate registration (or resend confirmation / password reset) via email.
Input JSON/Form: {"email": "user@example.com"}
Always returns 200 to avoid user enumeration besides obvious validation errors.
"""
data = _extract_json_or_form()
email = (data.get('email') or '').strip().lower()
if not email or '@' not in email:
return jsonify({
'success': False,
'error_key': 'invalid_email',
'error': 'Invalid email'
}), 400
# Reuse service.register logic by crafting a form-like object
service_result = email_login_service_api.register({'email': email})
ctx = service_result.get('context', {})
message = ctx.get('error') # service uses 'error' key for human message
# Heuristics for success (email dispatched)
dispatched_messages = {
'Please_check_your_email_for_confirmation_link',
'Link_to_reset_password_sent_to_email'
}
success = False
if message:
# Compare against translation keys if available
for key in dispatched_messages:
if key in message:
success = True
break
return jsonify({
'success': success,
'stage': 'register',
'email': email,
'message': message,
}), 200 if success else 400
@skala_api_app.post('/auth/password/reset/request')
def api_request_password_reset():
"""Request password reset link (works even if user unconfirmed - resends confirm)."""
data = _extract_json_or_form()
email = (data.get('email') or '').strip().lower()
if not email or '@' not in email:
return jsonify({'success': False, 'error_key': 'invalid_email', 'error': 'Invalid email'}), 400
user = competitionsEngine.get_user_by_email(email)
# Always respond success (prevent enumeration) but trigger appropriate email
if user is None:
pass # pretend to send
elif user.get('is_confirmed') is False:
# resend confirmation
email_login_service_api._send_registration_email(email)
else:
# confirmed -> send reset password email
token = email_login_service_api._generate_token(email)
confirm_url = url_for('confirm_email', type='reset_password', token=token, _external=True)
email_login_service_api.email_sender.send_password_reset_email(email, confirm_url)
return jsonify({
'success': True,
'stage': 'password_reset_request',
'message': 'If the email exists a message has been sent.'
})
@skala_api_app.get('/auth/confirm/<type>/<token>')
def api_confirm_email(type, token):
"""Confirm registration or reset password token. Returns JSON indicating next step."""
service_result = email_login_service_api.confirm_email(type, token)
ctx = service_result.get('context', {})
template = service_result.get('template')
if template == 'change_password.html':
# Session now holds email granting ability to set password
email = session.get('email')
return jsonify({
'success': True,
'stage': 'confirm',
'require_password_change': True,
'email': email,
'message': 'Token valid. Please set password.'
})
error_msg = ctx.get('error') or 'Invalid or expired token'
return jsonify({
'success': False,
'stage': 'confirm',
'error': error_msg
}), 400
@skala_api_app.post('/auth/password/change')
def api_change_password():
"""Change password after confirmation (requires session email set by confirm)."""
data = _extract_json_or_form()
password = data.get('password')
password2 = data.get('password2') or data.get('password_confirm')
# Ensure bcrypt available
if email_login_service_api.bcrypt is None:
from flask_bcrypt import Bcrypt
email_login_service_api.bcrypt = Bcrypt()
service_result = email_login_service_api.change_password(password, password2)
template = service_result.get('template')
ctx = service_result.get('context', {})
if template == 'competitionLogin.html':
return jsonify({
'success': True,
'stage': 'change_password',
'message': ctx.get('error'), # service uses error slot for info message
})
return jsonify({
'success': False,
'stage': 'change_password',
'error': ctx.get('error') or 'Unable to change password'
}), 400
@skala_api_app.get('/auth/status')
def api_auth_status():
"""Return authentication status (session or JWT)."""
# Check JWT first
auth_header = request.headers.get('Authorization', '')
status_source = None
user_email = None
if auth_header.startswith('Bearer '):
decoded = decode_jwt(auth_header[7:])
if 'error' not in decoded:
user_email = decoded.get('sub')
status_source = 'jwt'
# Fallback to session
if not user_email and session.get('email'):
user_email = session.get('email')
status_source = 'session'
if not user_email:
return jsonify({'authenticated': False}), 200
user = competitionsEngine.get_user_by_email(user_email) or {}
return jsonify({
'authenticated': True,
'source': status_source,
'user': {
'email': user.get('email'),
'firstname': user.get('firstname'),
'lastname': user.get('lastname'),
'club': user.get('club'),
'is_admin': User.is_admin(user),
}
})
#---------------- Activities API -----------------
# returns all activities for all users
@skala_api_app.get('/activities')
def get_activities():
allActivities = activities_db.get_activities_all_anonymous()
activities = {}
activities['activities'] = allActivities
avg_stats = []
user_stats = []
all_activities_stats = calculate_activities_stats(allActivities)
# Create a dictionary for all_activities_stats for quick lookups
all_activities_dict = {date: count for date, count in zip(all_activities_stats['dates'], all_activities_stats['routes_done'])}
activities['stats'] = {}
activities['stats']['routes_done'] = user_stats
activities['stats']['routes_avg'] = avg_stats
return activities
@skala_api_app.get('/myactivities')
@session_or_jwt_required
def get_useractivities():
user = competitionsEngine.get_user_by_email(session['email'])
activitiesA = activities_db.get_activities(user.get('id'))
allActivities = activities_db.get_activities_all_anonymous()
activities = {}
activities['activities'] = activitiesA
avg_stats = []
user_stats = []
user_activities_stats = calculate_activities_stats(activitiesA)
all_activities_stats = calculate_activities_stats(allActivities)
combined_dates = sorted(set(user_activities_stats['dates'] + all_activities_stats['dates']), reverse=False)
# Limit the combined_dates list to only the last 26 items
combined_dates = combined_dates[-25:]
# Create a dictionary for all_activities_stats for quick lookups
all_activities_dict = {date: count for date, count in zip(all_activities_stats['dates'], all_activities_stats['routes_done'])}
# Loop through user_activities_stats and check if the date exists in all_activities_stats
for date in combined_dates:
if date in all_activities_dict:
avg_stats.append(all_activities_dict[date])
else:
avg_stats.append(0)
if date in user_activities_stats['dates']:
user_stats.append(user_activities_stats['routes_done'][user_activities_stats['dates'].index(date)])
else:
user_stats.append(0)
activities['stats'] = {}
activities['stats']['dates'] = combined_dates
activities['stats']['routes_done'] = user_stats
activities['stats']['routes_avg'] = avg_stats
return activities
#calculates number of routes done per day
def calculate_activities_stats_per_day(activities):
# Get today's date
today = datetime.today().date()
stats = {}
# Create a dictionary with dates 30 days back from today as keys and 0 as initial values
routes_done = {(today - timedelta(days=i)).strftime('%Y-%m-%d'): 0 for i in range(160, -1, -1)}
for activity in activities:
if activity.get('date') is None:
continue
# Parse the 'date' into a date object
activity_date = activity['date']
# If the activity date is in the routes_done dictionary, add the number of routes
if activity_date in routes_done:
routes_done[activity_date] += len(activity['attempts'])
# Convert the dictionary to a list of values
routes_done_list = list(routes_done.values())
stats['dates'] = list(routes_done.keys())
stats['routes_done'] = routes_done_list
return stats
# calculates number of activities per day
def calculate_activities_stats(activities):
# Initialize a dictionary to store the count of routes done per week
weekly_stats = defaultdict(int)
for activity in activities:
# Parse the date of the activity
activity_date = datetime.strptime(activity['date'], '%Y-%m-%d')
# Find the Monday of the week for the activity date
start_of_week = activity_date - timedelta(days=activity_date.weekday())
if activity.get('attempts') is None:
logging.warning('activity has no attempts '+str(activity))
# Increment the count of routes done for that week
weekly_stats[start_of_week] += len(activity.get('attempts', []))
# Convert the weekly_stats dictionary to a sorted list of tuples
sorted_weekly_stats = sorted(weekly_stats.items())
# Initialize the result dictionary with dates and routes_done lists
result = {'dates': [], 'routes_done': []}
# Populate the result dictionary
for week_start, count in sorted_weekly_stats:
result['dates'].append(week_start.strftime('%Y-%m-%d'))
result['routes_done'].append(count)
return result
@skala_api_app.get('/activities/all')
def get_activities_all():
activities = activities_db.get_activities_all_anonymous()
#return json.dumps(activities)
return activities
@skala_api_app.post('/activity')
@session_or_jwt_required
def journey_add():
user = competitionsEngine.get_user_by_email(session['email'])
data = request.get_json()
#data = request.get_data()
# get the data from the body of the request
date = data.get('date')
gym_id = data.get('gym_id')
name = data.get('activity_name')
comp = {}
gym = competitionsEngine.get_gym(gym_id)
routesid = gym.get('routesid')
#a = Activity1(**data)
activity_id = activities_db.add_activity(user, gym, routesid, name, date)
activity = activities_db.get_activity(activity_id)
# journey_id = user.get('journey_id')
#journeys = activities_db.get_activities(user.get('id'))
return activity.to_dict()
@skala_api_app.delete('/activity/<activity_id>')
@session_or_jwt_required
def delete_activity(activity_id):
user = competitionsEngine.get_user_by_email(session['email'])
activity = activities_db.get_activity(activity_id)
if (activity is None):
return {"error":"activity not found"}
#a = Activity1(**data)
activities_db.delete_activity(activity_id)
# journey_id = user.get('journey_id')
#journeys = activities_db.get_activities(user.get('id'))
return {}
@skala_api_app.get('/activity/<activity_id>')
@session_or_jwt_required
def get_activity(activity_id):
user = competitionsEngine.get_user_by_email(session['email'])
activity = activities_db.get_activity(activity_id)
if (activity is None):
return {"error":"activity not found"}
#a = Activity1(**data)
#activity = activities_db.get_activity(activity_id)
#activity = calculate_activity_stats(activity)
# journey_id = user.get('journey_id')
#journeys = activities_db.get_activities(user.get('id'))
return activity.to_dict()
#return json.dumps(activity)
# add an attempt to an activity
@skala_api_app.post('/activity/<activity_id>')
@session_or_jwt_required
def add_activity_route_attempt(activity_id):
user = competitionsEngine.get_user_by_email(session['email'])
data = request.get_json()
#data = request.get_data()
# get the data from the body of the request
gym_id = data.get('gym_id')
routes_id = data.get('routes_id')
routes = competitionsEngine.get_routes(routes_id)
route_id = data.get('route_id')
note = data.get('note')
route_finish_status = data.get('route_finish_status')
grade = data.get('grade')
user_grade = data.get('route-grade-user')
route_stars = data.get('route_stars')
route = competitionsEngine.get_route(routes_id, route_id)
activity = activities_db.add_activity_attempt(activity_id, route, route_finish_status, note, user_grade, (route_stars or 0))
# journey_id = user.get('journey_id')
#journeys = activities_db.get_activities(user.get('id'))
return activity
@skala_api_app.get('/activity/user/<user_id>')
@session_or_jwt_required
def get_activities_by_user(user_id):
user = competitionsEngine.get_user_by_email(session['email'])
# Fetch activities for provided user_id (authorization: allow only self unless admin)
if str(user.get('id')) != str(user_id):
# basic permission check: only allow self for now
return jsonify({'error': 'forbidden'}), 403
activities = activities_db.get_activities(user.get('id'))
if activities is None:
activities = []
return json.dumps(activities)
@skala_api_app.get('/activity/gym/<gym_id>/routes/<routes_id>')
def get_activities_by_gym_by_routes(gym_id, routes_id):
activities = activities_db.get_activities_by_gym_routes(gym_id, routes_id)
if (activities is None or len(activities) == 0):
return {"error":"activity not found"}
#a = Activity1(**data)
# journey_id = user.get('journey_id')
# calculate_activity_stats(activity)
#journeys = activities_db.get_activities(user.get('id'))
return json.dumps(activities)
@skala_api_app.delete('/activity/<activity_id>/route/<route_id>')
@session_or_jwt_required
def delete_activity_route(activity_id, route_id):
#user = competitionsEngine.get_user_by_email(session['email'])
activity = activities_db.get_activity(activity_id)
if (activity is None):
return {"error":"activity not found"}
#a = Activity1(**data)
activity = activities_db.delete_activity_route(activity_id, route_id)
# journey_id = user.get('journey_id')
#journeys = activities_db.get_activities(user.get('id'))
return activity
# Update whole activity (currently supports updating name only)
@skala_api_app.put('/activity/<activity_id>')
@session_or_jwt_required
def update_activity_meta(activity_id):
"""Update Activity level fields (e.g., name).
JSON body may include:
- name: new activity name/title
Returns updated Activity (lean representation if attempts present).
"""
data = request.get_json(silent=True) or {}
activity = activities_db.get_activity(activity_id)
if activity is None:
return jsonify({'error': 'activity_not_found'}), 404
# Allow name change
if 'name' in data:
new_name = (data.get('name') or '').strip()
if not new_name:
return jsonify({'error': 'invalid_name'}), 400
activity.name = new_name[:200] # basic length guard
# Persist (legacy flattened to preserve current storage format)
activities_db.update_activity(activity)
return jsonify(activity.to_dict())
# update a specific route attempt inside an activity using attempt_id (no creation on miss)
@skala_api_app.put('/activity/<activity_id>/attempt/<attempt_id>')
@session_or_jwt_required
def update_activity_route(activity_id, attempt_id):
"""Update a single existing RouteAttempt within an Activity by attempt_id.
Path: /activity/{activity_id}/attempt/{attempt_id}
JSON body fields accepted (all optional):
- status: one of VALID_STATUSES or a recognized synonym
- user_grade: user proposed grade (string)
- note: free-form note (string)
- attempt_time: ISO8601 timestamp (e.g. 2025-10-30T18:42:00Z)
Behavior changes vs previous version:
- Lookup is by RouteAttempt.attempt_id only (not route id)
- Will NOT create a new attempt if not found (returns 404)
- Still rehydrates legacy flattened 'routes' list into attempts once if needed
Returns updated Activity (lean form: distinct routes + attempts arrays).
"""
from src.RouteAttempt import VALID_STATUSES, STATUS_SYNONYMS, RouteAttempt # local import to avoid circular
data = request.get_json(silent=True) or {}
activity = activities_db.get_activity(activity_id)
if activity is None:
return jsonify({'error': 'activity_not_found'}), 404
# Attempt lookup by attempt_id
attempt = next((a for a in activity.attempts if a.attempt_id == attempt_id), None)
# Lazy rehydrate from legacy flattened list if attempts list empty and attempt not found