API - users refactoring

This commit is contained in:
Sam 2022-02-16 18:07:05 +01:00
parent 1b4a477544
commit fc43fcd6bf
12 changed files with 124 additions and 10 deletions

View File

@ -8,7 +8,7 @@ from flask import Flask
from freezegun import freeze_time
from fittrackee.users.models import User, UserSportPreference
from fittrackee.users.utils_token import get_user_token
from fittrackee.users.utils.token import get_user_token
from fittrackee.workouts.models import Sport, Workout
from ..api_test_case import ApiTestCaseMixin

View File

@ -5,12 +5,12 @@ from flask import Flask
from fittrackee.users.exceptions import UserNotFoundException
from fittrackee.users.models import User
from fittrackee.users.utils import (
from fittrackee.users.utils.admin import set_admin_rights
from fittrackee.users.utils.controls import (
check_passwords,
check_username,
is_valid_email,
register_controls,
set_admin_rights,
)
from ..utils import random_string
@ -163,7 +163,7 @@ class TestIsUsernameValid:
class TestRegisterControls:
module_path = 'fittrackee.users.utils.'
module_path = 'fittrackee.users.utils.controls.'
valid_username = random_string()
valid_email = f'{random_string()}@example.com'
valid_password = random_string()

View File

@ -27,8 +27,8 @@ from fittrackee.workouts.models import Sport
from .decorators import authenticate
from .models import User, UserSportPreference
from .utils import check_passwords, register_controls
from .utils_token import decode_user_token
from .utils.controls import check_passwords, register_controls
from .utils.token import decode_user_token
auth_blueprint = Blueprint('auth', __name__)

View File

@ -5,7 +5,7 @@ from flask import request
from fittrackee.responses import HttpResponse
from .utils import verify_user
from .utils.controls import verify_user
def verify_auth_user(

View File

@ -11,7 +11,7 @@ from sqlalchemy.sql.expression import select
from fittrackee import bcrypt, db
from fittrackee.workouts.models import Workout
from .utils_token import decode_user_token, get_user_token
from .utils.token import decode_user_token, get_user_token
BaseModel: DeclarativeMeta = db.Model

View File

@ -21,7 +21,7 @@ from fittrackee.workouts.models import Record, Workout, WorkoutSegment
from .decorators import authenticate, authenticate_as_admin
from .exceptions import UserNotFoundException
from .models import User, UserSportPreference
from .utils import set_admin_rights
from .utils.admin import set_admin_rights
users_blueprint = Blueprint('users', __name__)

View File

View File

@ -0,0 +1,12 @@
from fittrackee import db
from ..exceptions import UserNotFoundException
from ..models import User
def set_admin_rights(username: str) -> None:
user = User.query.filter_by(username=username).first()
if not user:
raise UserNotFoundException()
user.admin = True
db.session.commit()

View File

@ -0,0 +1,88 @@
import re
from typing import Optional, Tuple
from flask import Request
from fittrackee.responses import (
ForbiddenErrorResponse,
HttpResponse,
UnauthorizedErrorResponse,
)
from ..models import User
def is_valid_email(email: str) -> bool:
"""
Return if email format is valid
"""
mail_pattern = r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)"
return re.match(mail_pattern, email) is not None
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
"""
ret = ''
if password_conf != password:
ret = 'password: password and password confirmation do not match\n'
if len(password) < 8:
ret += 'password: 8 characters required\n'
return ret
def check_username(username: str) -> str:
"""
Return if username is valid
"""
ret = ''
if not 2 < len(username) < 13:
ret += 'username: 3 to 12 characters required\n'
if not re.match(r'^[a-zA-Z0-9_]+$', username):
ret += (
'username: only alphanumeric characters and the '
'underscore character "_" allowed\n'
)
return ret
def register_controls(
username: str, email: str, password: str, password_conf: str
) -> str:
"""
Verify if username, email and passwords are valid
If not, it returns not empty string
"""
ret = check_username(username)
if not is_valid_email(email):
ret += 'email: valid email must be provided\n'
ret += check_passwords(password, password_conf)
return ret
def verify_user(
current_request: Request, verify_admin: bool
) -> Tuple[Optional[HttpResponse], Optional[User]]:
"""
Return authenticated user, if the provided token is valid and user has
admin rights if 'verify_admin' is True
"""
default_message = 'provide a valid auth token'
auth_header = current_request.headers.get('Authorization')
if not auth_header:
return UnauthorizedErrorResponse(default_message), None
auth_token = auth_header.split(' ')[1]
resp = User.decode_auth_token(auth_token)
if isinstance(resp, str):
return UnauthorizedErrorResponse(resp), None
user = User.query.filter_by(id=resp).first()
if not user:
return UnauthorizedErrorResponse(default_message), None
if verify_admin and not user.admin:
return ForbiddenErrorResponse(), None
return None, user

View File

@ -0,0 +1,14 @@
from typing import Optional
from fittrackee.responses import ForbiddenErrorResponse, HttpResponse
def can_view_workout(
auth_user_id: int, workout_user_id: int
) -> Optional[HttpResponse]:
"""
Return error response if user has no right to view workout
"""
if auth_user_id != workout_user_id:
return ForbiddenErrorResponse()
return None

View File

@ -30,7 +30,6 @@ from fittrackee.responses import (
)
from fittrackee.users.decorators import authenticate
from fittrackee.users.models import User
from fittrackee.users.utils import can_view_workout
from .models import Workout
from .utils.convert import convert_in_duration
@ -40,6 +39,7 @@ from .utils.gpx import (
get_chart_data,
)
from .utils.short_id import decode_short_id
from .utils.visibility import can_view_workout
from .utils.workouts import (
WorkoutException,
create_workout,