2018-01-01 11:10:39 +01:00
|
|
|
import re
|
2020-07-11 19:35:20 +02:00
|
|
|
from datetime import timedelta
|
2018-01-14 20:49:35 +01:00
|
|
|
from functools import wraps
|
2021-01-02 19:28:03 +01:00
|
|
|
from typing import Any, Callable, Optional, Tuple, Union
|
2017-12-25 17:45:28 +01:00
|
|
|
|
2020-07-11 19:35:20 +02:00
|
|
|
import humanize
|
2021-01-01 16:39:25 +01:00
|
|
|
from fittrackee.responses import (
|
|
|
|
ForbiddenErrorResponse,
|
2021-01-02 19:28:03 +01:00
|
|
|
HttpResponse,
|
2021-01-01 16:39:25 +01:00
|
|
|
InvalidPayloadErrorResponse,
|
|
|
|
PayloadTooLargeErrorResponse,
|
|
|
|
UnauthorizedErrorResponse,
|
|
|
|
)
|
2021-01-02 19:28:03 +01:00
|
|
|
from flask import Request, current_app, request
|
2017-12-25 17:45:28 +01:00
|
|
|
|
|
|
|
from .models import User
|
|
|
|
|
|
|
|
|
2021-01-02 19:28:03 +01:00
|
|
|
def is_admin(user_id: int) -> bool:
|
|
|
|
"""
|
|
|
|
Return if user has admin rights
|
|
|
|
"""
|
2018-05-09 16:50:30 +02:00
|
|
|
user = User.query.filter_by(id=user_id).first()
|
|
|
|
return user.admin
|
|
|
|
|
|
|
|
|
2021-01-02 19:28:03 +01:00
|
|
|
def is_valid_email(email: str) -> bool:
|
|
|
|
"""
|
|
|
|
Return if email format is valid
|
|
|
|
"""
|
2018-05-09 16:50:30 +02:00
|
|
|
mail_pattern = r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)"
|
|
|
|
return re.match(mail_pattern, email) is not None
|
|
|
|
|
|
|
|
|
2021-01-02 19:28:03 +01:00
|
|
|
def check_passwords(password: str, password_conf: str) -> str:
|
|
|
|
"""
|
|
|
|
Verify if password and password confirmation are the same and have
|
|
|
|
more than 8 characters
|
|
|
|
|
|
|
|
If not, it returns not empty string
|
|
|
|
"""
|
2020-05-17 16:42:44 +02:00
|
|
|
ret = ''
|
|
|
|
if password_conf != password:
|
|
|
|
ret = 'Password and password confirmation don\'t match.\n'
|
|
|
|
if len(password) < 8:
|
|
|
|
ret += 'Password: 8 characters required.\n'
|
|
|
|
return ret
|
|
|
|
|
|
|
|
|
2021-01-02 19:28:03 +01:00
|
|
|
def register_controls(
|
|
|
|
username: str, email: str, password: str, password_conf: str
|
|
|
|
) -> str:
|
|
|
|
"""
|
|
|
|
Verify if user name, email and passwords are valid
|
|
|
|
|
|
|
|
If not, it returns not empty string
|
|
|
|
"""
|
2018-05-09 17:00:22 +02:00
|
|
|
ret = ''
|
|
|
|
if not 2 < len(username) < 13:
|
|
|
|
ret += 'Username: 3 to 12 characters required.\n'
|
|
|
|
if not is_valid_email(email):
|
|
|
|
ret += 'Valid email must be provided.\n'
|
2020-05-17 16:42:44 +02:00
|
|
|
ret += check_passwords(password, password_conf)
|
2018-05-09 17:00:22 +02:00
|
|
|
return ret
|
|
|
|
|
|
|
|
|
2021-01-02 19:28:03 +01:00
|
|
|
def verify_extension_and_size(
|
|
|
|
file_type: str, req: Request
|
|
|
|
) -> Optional[HttpResponse]:
|
|
|
|
"""
|
|
|
|
Return error Response if file is invalid
|
|
|
|
"""
|
2018-05-01 17:51:38 +02:00
|
|
|
if 'file' not in req.files:
|
2021-01-01 16:39:25 +01:00
|
|
|
return InvalidPayloadErrorResponse('No file part.', 'fail')
|
2018-05-01 17:51:38 +02:00
|
|
|
|
|
|
|
file = req.files['file']
|
|
|
|
if file.filename == '':
|
2021-01-01 16:39:25 +01:00
|
|
|
return InvalidPayloadErrorResponse('No selected file.', 'fail')
|
2018-05-01 17:51:38 +02:00
|
|
|
|
2018-05-01 17:58:51 +02:00
|
|
|
allowed_extensions = (
|
2021-01-10 11:16:43 +01:00
|
|
|
'WORKOUT_ALLOWED_EXTENSIONS'
|
|
|
|
if file_type == 'workout'
|
2018-05-01 17:58:51 +02:00
|
|
|
else 'PICTURE_ALLOWED_EXTENSIONS'
|
|
|
|
)
|
|
|
|
|
2019-08-31 14:11:00 +02:00
|
|
|
file_extension = (
|
|
|
|
file.filename.rsplit('.', 1)[1].lower()
|
|
|
|
if '.' in file.filename
|
|
|
|
else None
|
|
|
|
)
|
2019-11-13 18:40:01 +01:00
|
|
|
max_file_size = current_app.config['max_single_file_size']
|
2019-08-31 14:11:00 +02:00
|
|
|
|
2019-08-28 13:25:39 +02:00
|
|
|
if not (
|
2019-08-31 14:11:00 +02:00
|
|
|
file_extension
|
2021-01-02 19:28:03 +01:00
|
|
|
and file_extension in current_app.config[allowed_extensions]
|
2019-08-28 13:25:39 +02:00
|
|
|
):
|
2021-01-01 16:39:25 +01:00
|
|
|
return InvalidPayloadErrorResponse(
|
|
|
|
'File extension not allowed.', 'fail'
|
|
|
|
)
|
|
|
|
|
|
|
|
if file_extension != 'zip' and req.content_length > max_file_size:
|
|
|
|
return PayloadTooLargeErrorResponse(
|
|
|
|
'Error during picture update, file size exceeds '
|
|
|
|
f'{display_readable_file_size(max_file_size)}.'
|
|
|
|
)
|
2018-05-01 17:51:38 +02:00
|
|
|
|
2021-01-01 16:39:25 +01:00
|
|
|
return None
|
2018-05-01 17:51:38 +02:00
|
|
|
|
|
|
|
|
2021-01-02 19:28:03 +01:00
|
|
|
def verify_user(
|
|
|
|
current_request: Request, verify_admin: bool
|
|
|
|
) -> Tuple[Optional[HttpResponse], Optional[int]]:
|
|
|
|
"""
|
|
|
|
Return user id, if the provided token is valid and if user has admin
|
|
|
|
rights if 'verify_admin' is True
|
|
|
|
"""
|
2021-01-01 16:39:25 +01:00
|
|
|
default_message = 'Provide a valid auth token.'
|
2018-05-09 17:00:22 +02:00
|
|
|
auth_header = current_request.headers.get('Authorization')
|
|
|
|
if not auth_header:
|
2021-01-01 16:39:25 +01:00
|
|
|
return UnauthorizedErrorResponse(default_message), None
|
|
|
|
auth_token = auth_header.split(' ')[1]
|
2018-05-09 17:00:22 +02:00
|
|
|
resp = User.decode_auth_token(auth_token)
|
|
|
|
if isinstance(resp, str):
|
2021-01-01 16:39:25 +01:00
|
|
|
return UnauthorizedErrorResponse(resp), None
|
2018-05-09 17:00:22 +02:00
|
|
|
user = User.query.filter_by(id=resp).first()
|
|
|
|
if not user:
|
2021-01-01 16:39:25 +01:00
|
|
|
return UnauthorizedErrorResponse(default_message), None
|
2018-05-09 17:00:22 +02:00
|
|
|
if verify_admin and not is_admin(resp):
|
2021-01-01 16:39:25 +01:00
|
|
|
return ForbiddenErrorResponse(), None
|
|
|
|
return None, resp
|
2018-05-09 17:00:22 +02:00
|
|
|
|
|
|
|
|
2021-01-02 19:28:03 +01:00
|
|
|
def authenticate(f: Callable) -> Callable:
|
2017-12-25 17:45:28 +01:00
|
|
|
@wraps(f)
|
2021-01-02 19:28:03 +01:00
|
|
|
def decorated_function(
|
|
|
|
*args: Any, **kwargs: Any
|
|
|
|
) -> Union[Callable, HttpResponse]:
|
2018-05-09 17:00:22 +02:00
|
|
|
verify_admin = False
|
2021-01-01 16:39:25 +01:00
|
|
|
response_object, resp = verify_user(request, verify_admin)
|
2018-05-09 17:00:22 +02:00
|
|
|
if response_object:
|
2021-01-01 16:39:25 +01:00
|
|
|
return response_object
|
2017-12-25 17:45:28 +01:00
|
|
|
return f(resp, *args, **kwargs)
|
2018-05-01 17:51:38 +02:00
|
|
|
|
2017-12-25 17:45:28 +01:00
|
|
|
return decorated_function
|
|
|
|
|
|
|
|
|
2021-01-02 19:28:03 +01:00
|
|
|
def authenticate_as_admin(f: Callable) -> Callable:
|
2018-05-09 16:50:30 +02:00
|
|
|
@wraps(f)
|
2021-01-02 19:28:03 +01:00
|
|
|
def decorated_function(
|
|
|
|
*args: Any, **kwargs: Any
|
|
|
|
) -> Union[Callable, HttpResponse]:
|
2018-05-09 17:00:22 +02:00
|
|
|
verify_admin = True
|
2021-01-01 16:39:25 +01:00
|
|
|
response_object, resp = verify_user(request, verify_admin)
|
2018-05-09 17:00:22 +02:00
|
|
|
if response_object:
|
2021-01-01 16:39:25 +01:00
|
|
|
return response_object
|
2018-05-09 16:50:30 +02:00
|
|
|
return f(resp, *args, **kwargs)
|
2018-01-01 11:10:39 +01:00
|
|
|
|
2018-05-09 16:50:30 +02:00
|
|
|
return decorated_function
|
2018-06-15 10:50:37 +02:00
|
|
|
|
|
|
|
|
2021-01-10 11:16:43 +01:00
|
|
|
def can_view_workout(
|
|
|
|
auth_user_id: int, workout_user_id: int
|
2021-01-02 19:28:03 +01:00
|
|
|
) -> Optional[HttpResponse]:
|
|
|
|
"""
|
2021-01-10 11:16:43 +01:00
|
|
|
Return error response if user has no right to view workout
|
2021-01-02 19:28:03 +01:00
|
|
|
"""
|
2021-01-10 11:16:43 +01:00
|
|
|
if auth_user_id != workout_user_id:
|
2021-01-01 16:39:25 +01:00
|
|
|
return ForbiddenErrorResponse()
|
|
|
|
return None
|
2019-08-31 14:11:00 +02:00
|
|
|
|
|
|
|
|
2021-01-02 19:28:03 +01:00
|
|
|
def display_readable_file_size(size_in_bytes: Union[float, int]) -> str:
|
|
|
|
"""
|
|
|
|
Return readable file size from size in bytes
|
|
|
|
"""
|
2019-08-31 14:11:00 +02:00
|
|
|
if size_in_bytes == 0:
|
|
|
|
return '0 bytes'
|
|
|
|
if size_in_bytes == 1:
|
|
|
|
return '1 byte'
|
|
|
|
for unit in [' bytes', 'KB', 'MB', 'GB', 'TB']:
|
|
|
|
if abs(size_in_bytes) < 1024.0:
|
2021-01-02 19:28:03 +01:00
|
|
|
return f'{size_in_bytes:3.1f}{unit}'
|
2019-08-31 14:11:00 +02:00
|
|
|
size_in_bytes /= 1024.0
|
2021-01-02 19:28:03 +01:00
|
|
|
return f'{size_in_bytes} bytes'
|
2020-07-11 19:35:20 +02:00
|
|
|
|
|
|
|
|
2021-01-02 19:28:03 +01:00
|
|
|
def get_readable_duration(duration: int, locale: Optional[str] = 'en') -> str:
|
|
|
|
"""
|
|
|
|
Return readable and localized duration from duration in seconds
|
|
|
|
"""
|
2020-07-15 10:10:54 +02:00
|
|
|
if locale is not None and locale != 'en':
|
2020-07-11 19:35:20 +02:00
|
|
|
_t = humanize.i18n.activate(locale) # noqa
|
|
|
|
readable_duration = humanize.naturaldelta(timedelta(seconds=duration))
|
2020-07-15 10:10:54 +02:00
|
|
|
if locale is not None and locale != 'en':
|
2020-07-11 19:35:20 +02:00
|
|
|
humanize.i18n.deactivate()
|
|
|
|
return readable_duration
|