2023-03-01 21:00:53 +01:00
|
|
|
import os
|
2020-05-10 17:08:18 +02:00
|
|
|
from datetime import datetime
|
2023-03-01 21:00:53 +01:00
|
|
|
from typing import Any, Dict, Optional, Union
|
2017-12-16 21:00:46 +01:00
|
|
|
|
|
|
|
import jwt
|
|
|
|
from flask import current_app
|
2018-06-05 18:16:53 +02:00
|
|
|
from sqlalchemy import func
|
2023-03-01 21:00:53 +01:00
|
|
|
from sqlalchemy.engine.base import Connection
|
|
|
|
from sqlalchemy.event import listens_for
|
2023-10-04 15:25:26 +02:00
|
|
|
from sqlalchemy.ext.declarative import DeclarativeMeta
|
2020-05-02 18:00:17 +02:00
|
|
|
from sqlalchemy.ext.hybrid import hybrid_property
|
2023-03-01 21:00:53 +01:00
|
|
|
from sqlalchemy.orm.mapper import Mapper
|
|
|
|
from sqlalchemy.orm.session import Session
|
2020-05-02 18:00:17 +02:00
|
|
|
from sqlalchemy.sql.expression import select
|
2018-06-05 18:16:53 +02:00
|
|
|
|
2023-03-01 21:00:53 +01:00
|
|
|
from fittrackee import appLog, bcrypt, db
|
|
|
|
from fittrackee.files import get_absolute_file_path
|
2021-01-20 16:47:00 +01:00
|
|
|
from fittrackee.workouts.models import Workout
|
|
|
|
|
2022-03-13 09:30:50 +01:00
|
|
|
from .exceptions import UserNotFoundException
|
|
|
|
from .roles import UserRole
|
2022-02-16 18:07:05 +01:00
|
|
|
from .utils.token import decode_user_token, get_user_token
|
2017-12-16 21:00:46 +01:00
|
|
|
|
2023-10-04 15:25:26 +02:00
|
|
|
BaseModel: DeclarativeMeta = db.Model
|
2017-12-16 21:00:46 +01:00
|
|
|
|
2023-10-04 15:25:26 +02:00
|
|
|
|
|
|
|
class User(BaseModel):
|
2021-01-02 19:28:03 +01:00
|
|
|
__tablename__ = 'users'
|
2023-10-04 15:25:26 +02:00
|
|
|
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
|
|
|
|
username = db.Column(db.String(255), unique=True, nullable=False)
|
|
|
|
email = db.Column(db.String(255), unique=True, nullable=False)
|
|
|
|
password = db.Column(db.String(255), nullable=False)
|
|
|
|
created_at = db.Column(db.DateTime, nullable=False)
|
|
|
|
admin = db.Column(db.Boolean, default=False, nullable=False)
|
|
|
|
first_name = db.Column(db.String(80), nullable=True)
|
|
|
|
last_name = db.Column(db.String(80), nullable=True)
|
|
|
|
birth_date = db.Column(db.DateTime, nullable=True)
|
|
|
|
location = db.Column(db.String(80), nullable=True)
|
|
|
|
bio = db.Column(db.String(200), nullable=True)
|
|
|
|
picture = db.Column(db.String(255), nullable=True)
|
|
|
|
timezone = db.Column(db.String(50), nullable=True)
|
|
|
|
date_format = db.Column(db.String(50), nullable=True)
|
2019-08-31 16:33:46 +02:00
|
|
|
# does the week start Monday?
|
2023-10-04 15:25:26 +02:00
|
|
|
weekm = db.Column(db.Boolean, default=False, nullable=False)
|
|
|
|
workouts = db.relationship(
|
2022-02-05 12:10:33 +01:00
|
|
|
'Workout',
|
|
|
|
lazy=True,
|
|
|
|
backref=db.backref('user', lazy='joined', single_parent=True),
|
2019-08-28 13:25:39 +02:00
|
|
|
)
|
2023-10-04 15:25:26 +02:00
|
|
|
records = db.relationship(
|
2022-02-05 12:10:33 +01:00
|
|
|
'Record',
|
|
|
|
lazy=True,
|
|
|
|
backref=db.backref('user', lazy='joined', single_parent=True),
|
2019-08-28 13:25:39 +02:00
|
|
|
)
|
2023-10-04 15:25:26 +02:00
|
|
|
language = db.Column(db.String(50), nullable=True)
|
|
|
|
imperial_units = db.Column(db.Boolean, default=False, nullable=False)
|
|
|
|
is_active = db.Column(db.Boolean, default=False, nullable=False)
|
|
|
|
email_to_confirm = db.Column(db.String(255), nullable=True)
|
|
|
|
confirmation_token = db.Column(db.String(255), nullable=True)
|
|
|
|
display_ascent = db.Column(db.Boolean, default=True, nullable=False)
|
|
|
|
accepted_policy_date = db.Column(db.DateTime, nullable=True)
|
|
|
|
start_elevation_at_zero = db.Column(
|
2023-03-15 05:54:20 +01:00
|
|
|
db.Boolean, default=True, nullable=False
|
|
|
|
)
|
2023-10-04 15:25:26 +02:00
|
|
|
use_raw_gpx_speed = db.Column(db.Boolean, default=False, nullable=False)
|
2023-12-16 21:18:09 +01:00
|
|
|
use_dark_mode = db.Column(db.Boolean, default=False, nullable=True)
|
2017-12-16 21:00:46 +01:00
|
|
|
|
2021-01-02 19:28:03 +01:00
|
|
|
def __repr__(self) -> str:
|
2018-05-23 17:30:22 +02:00
|
|
|
return f'<User {self.username!r}>'
|
2017-12-16 21:00:46 +01:00
|
|
|
|
|
|
|
def __init__(
|
2021-01-02 19:28:03 +01:00
|
|
|
self,
|
|
|
|
username: str,
|
|
|
|
email: str,
|
|
|
|
password: str,
|
2022-03-26 18:28:00 +01:00
|
|
|
created_at: Optional[datetime] = None,
|
2021-01-02 19:28:03 +01:00
|
|
|
) -> None:
|
2017-12-16 21:00:46 +01:00
|
|
|
self.username = username
|
|
|
|
self.email = email
|
|
|
|
self.password = bcrypt.generate_password_hash(
|
|
|
|
password, current_app.config.get('BCRYPT_LOG_ROUNDS')
|
|
|
|
).decode()
|
2022-03-26 18:28:00 +01:00
|
|
|
self.created_at = (
|
|
|
|
datetime.utcnow() if created_at is None else created_at
|
|
|
|
)
|
2017-12-16 21:00:46 +01:00
|
|
|
|
2017-12-17 12:07:25 +01:00
|
|
|
@staticmethod
|
2021-01-02 19:28:03 +01:00
|
|
|
def encode_auth_token(user_id: int) -> str:
|
2018-01-01 16:59:46 +01:00
|
|
|
"""
|
|
|
|
Generates the auth token
|
|
|
|
:param user_id: -
|
|
|
|
:return: JWToken
|
|
|
|
"""
|
2021-01-02 19:28:03 +01:00
|
|
|
return get_user_token(user_id)
|
2020-05-10 17:08:18 +02:00
|
|
|
|
|
|
|
@staticmethod
|
2021-01-02 19:28:03 +01:00
|
|
|
def encode_password_reset_token(user_id: int) -> str:
|
2020-05-10 17:08:18 +02:00
|
|
|
"""
|
|
|
|
Generates the auth token
|
|
|
|
:param user_id: -
|
|
|
|
:return: JWToken
|
|
|
|
"""
|
2021-01-02 19:28:03 +01:00
|
|
|
return get_user_token(user_id, password_reset=True)
|
2017-12-16 21:00:46 +01:00
|
|
|
|
|
|
|
@staticmethod
|
2021-01-02 19:28:03 +01:00
|
|
|
def decode_auth_token(auth_token: str) -> Union[int, str]:
|
2017-12-16 21:00:46 +01:00
|
|
|
"""
|
|
|
|
Decodes the auth token
|
|
|
|
:param auth_token: -
|
|
|
|
:return: integer|string
|
|
|
|
"""
|
|
|
|
try:
|
2022-09-14 15:15:03 +02:00
|
|
|
resp = decode_user_token(auth_token)
|
|
|
|
is_blacklisted = BlacklistedToken.check(auth_token)
|
|
|
|
if is_blacklisted:
|
|
|
|
return 'blacklisted token, please log in again'
|
|
|
|
return resp
|
2017-12-16 21:00:46 +01:00
|
|
|
except jwt.ExpiredSignatureError:
|
2021-11-01 09:44:10 +01:00
|
|
|
return 'signature expired, please log in again'
|
2017-12-16 21:00:46 +01:00
|
|
|
except jwt.InvalidTokenError:
|
2021-11-01 09:44:10 +01:00
|
|
|
return 'invalid token, please log in again'
|
2018-05-09 15:52:27 +02:00
|
|
|
|
2022-05-23 13:04:01 +02:00
|
|
|
def check_password(self, password: str) -> bool:
|
|
|
|
return bcrypt.check_password_hash(self.password, password)
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def generate_password_hash(new_password: str) -> str:
|
|
|
|
return bcrypt.generate_password_hash(
|
|
|
|
new_password, current_app.config.get('BCRYPT_LOG_ROUNDS')
|
|
|
|
).decode()
|
|
|
|
|
2022-05-27 13:28:26 +02:00
|
|
|
def get_user_id(self) -> int:
|
|
|
|
return self.id
|
|
|
|
|
2020-05-02 18:00:17 +02:00
|
|
|
@hybrid_property
|
2021-01-10 11:16:43 +01:00
|
|
|
def workouts_count(self) -> int:
|
|
|
|
return Workout.query.filter(Workout.user_id == self.id).count()
|
2020-05-02 18:00:17 +02:00
|
|
|
|
2021-01-10 11:16:43 +01:00
|
|
|
@workouts_count.expression # type: ignore
|
|
|
|
def workouts_count(self) -> int:
|
2020-05-02 18:00:17 +02:00
|
|
|
return (
|
2023-10-04 15:25:26 +02:00
|
|
|
select([func.count(Workout.id)])
|
2021-01-10 11:16:43 +01:00
|
|
|
.where(Workout.user_id == self.id)
|
|
|
|
.label('workouts_count')
|
2020-05-02 18:00:17 +02:00
|
|
|
)
|
|
|
|
|
2022-03-13 09:30:50 +01:00
|
|
|
def serialize(self, current_user: 'User') -> Dict:
|
|
|
|
role = (
|
|
|
|
UserRole.AUTH_USER
|
|
|
|
if current_user.id == self.id
|
|
|
|
else UserRole.ADMIN
|
|
|
|
if current_user.admin
|
|
|
|
else UserRole.USER
|
|
|
|
)
|
|
|
|
|
|
|
|
if role == UserRole.USER:
|
|
|
|
raise UserNotFoundException()
|
|
|
|
|
2018-06-07 22:44:52 +02:00
|
|
|
sports = []
|
2022-07-19 16:33:05 +02:00
|
|
|
total = (0, '0:00:00', 0)
|
2021-01-10 11:16:43 +01:00
|
|
|
if self.workouts_count > 0: # type: ignore
|
2019-08-28 13:25:39 +02:00
|
|
|
sports = (
|
2021-01-10 11:16:43 +01:00
|
|
|
db.session.query(Workout.sport_id)
|
|
|
|
.filter(Workout.user_id == self.id)
|
|
|
|
.group_by(Workout.sport_id)
|
|
|
|
.order_by(Workout.sport_id)
|
2019-08-28 13:25:39 +02:00
|
|
|
.all()
|
|
|
|
)
|
2019-09-23 14:43:56 +02:00
|
|
|
total = (
|
|
|
|
db.session.query(
|
2022-07-18 21:10:43 +02:00
|
|
|
func.sum(Workout.distance),
|
|
|
|
func.sum(Workout.duration),
|
|
|
|
func.sum(Workout.ascent),
|
2019-09-23 14:43:56 +02:00
|
|
|
)
|
2021-01-10 11:16:43 +01:00
|
|
|
.filter(Workout.user_id == self.id)
|
2019-09-23 14:43:56 +02:00
|
|
|
.first()
|
|
|
|
)
|
2022-03-13 09:30:50 +01:00
|
|
|
|
|
|
|
serialized_user = {
|
2018-05-09 15:52:27 +02:00
|
|
|
'admin': self.admin,
|
2022-03-13 09:30:50 +01:00
|
|
|
'bio': self.bio,
|
|
|
|
'birth_date': self.birth_date,
|
|
|
|
'created_at': self.created_at,
|
|
|
|
'email': self.email,
|
|
|
|
'email_to_confirm': self.email_to_confirm,
|
2018-05-09 15:52:27 +02:00
|
|
|
'first_name': self.first_name,
|
2022-03-19 22:02:06 +01:00
|
|
|
'is_active': self.is_active,
|
2018-05-09 15:52:27 +02:00
|
|
|
'last_name': self.last_name,
|
|
|
|
'location': self.location,
|
2018-06-05 18:16:53 +02:00
|
|
|
'nb_sports': len(sports),
|
2021-01-10 11:16:43 +01:00
|
|
|
'nb_workouts': self.workouts_count,
|
2022-03-13 09:30:50 +01:00
|
|
|
'picture': self.picture is not None,
|
2021-09-21 18:10:27 +02:00
|
|
|
'records': [record.serialize() for record in self.records],
|
2019-09-23 20:01:11 +02:00
|
|
|
'sports_list': [
|
|
|
|
sport for sportslist in sports for sport in sportslist
|
|
|
|
],
|
2022-07-19 16:33:05 +02:00
|
|
|
'total_ascent': float(total[2]) if total[2] else 0.0,
|
2021-01-02 19:28:03 +01:00
|
|
|
'total_distance': float(total[0]),
|
|
|
|
'total_duration': str(total[1]),
|
2022-03-13 09:30:50 +01:00
|
|
|
'username': self.username,
|
2018-05-09 15:52:27 +02:00
|
|
|
}
|
2022-03-13 09:30:50 +01:00
|
|
|
if role == UserRole.AUTH_USER:
|
2023-02-26 09:07:02 +01:00
|
|
|
accepted_privacy_policy = False
|
|
|
|
if self.accepted_policy_date:
|
|
|
|
accepted_privacy_policy = (
|
|
|
|
True
|
|
|
|
if current_app.config['privacy_policy_date'] is None
|
|
|
|
else current_app.config['privacy_policy_date']
|
|
|
|
< self.accepted_policy_date
|
|
|
|
)
|
2022-03-13 09:30:50 +01:00
|
|
|
serialized_user = {
|
|
|
|
**serialized_user,
|
|
|
|
**{
|
2023-02-26 09:07:02 +01:00
|
|
|
'accepted_privacy_policy': accepted_privacy_policy,
|
2022-10-25 23:27:05 +02:00
|
|
|
'date_format': self.date_format,
|
2022-07-23 08:09:45 +02:00
|
|
|
'display_ascent': self.display_ascent,
|
2022-03-13 09:30:50 +01:00
|
|
|
'imperial_units': self.imperial_units,
|
|
|
|
'language': self.language,
|
2023-03-14 05:51:05 +01:00
|
|
|
'start_elevation_at_zero': self.start_elevation_at_zero,
|
2022-03-13 09:30:50 +01:00
|
|
|
'timezone': self.timezone,
|
2023-12-16 21:18:09 +01:00
|
|
|
'use_dark_mode': self.use_dark_mode,
|
2023-05-15 06:40:03 +02:00
|
|
|
'use_raw_gpx_speed': self.use_raw_gpx_speed,
|
2022-03-13 09:30:50 +01:00
|
|
|
'weekm': self.weekm,
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
return serialized_user
|
2021-11-12 12:22:07 +01:00
|
|
|
|
|
|
|
|
2023-10-04 15:25:26 +02:00
|
|
|
class UserSportPreference(BaseModel):
|
2021-11-12 12:22:07 +01:00
|
|
|
__tablename__ = 'users_sports_preferences'
|
|
|
|
|
2023-10-04 15:25:26 +02:00
|
|
|
user_id = db.Column(
|
2021-11-12 12:22:07 +01:00
|
|
|
db.Integer,
|
|
|
|
db.ForeignKey('users.id'),
|
|
|
|
primary_key=True,
|
|
|
|
)
|
2023-10-04 15:25:26 +02:00
|
|
|
sport_id = db.Column(
|
2021-11-12 12:22:07 +01:00
|
|
|
db.Integer,
|
|
|
|
db.ForeignKey('sports.id'),
|
|
|
|
primary_key=True,
|
|
|
|
)
|
2023-10-04 15:25:26 +02:00
|
|
|
color = db.Column(db.String(50), nullable=True)
|
|
|
|
is_active = db.Column(db.Boolean, default=True, nullable=False)
|
|
|
|
stopped_speed_threshold = db.Column(db.Float, default=1.0, nullable=False)
|
2021-11-12 12:22:07 +01:00
|
|
|
|
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
user_id: int,
|
|
|
|
sport_id: int,
|
|
|
|
stopped_speed_threshold: float,
|
|
|
|
) -> None:
|
|
|
|
self.user_id = user_id
|
|
|
|
self.sport_id = sport_id
|
|
|
|
self.is_active = True
|
|
|
|
self.stopped_speed_threshold = stopped_speed_threshold
|
|
|
|
|
|
|
|
def serialize(self) -> Dict:
|
|
|
|
return {
|
|
|
|
'user_id': self.user_id,
|
|
|
|
'sport_id': self.sport_id,
|
|
|
|
'color': self.color,
|
|
|
|
'is_active': self.is_active,
|
|
|
|
'stopped_speed_threshold': self.stopped_speed_threshold,
|
|
|
|
}
|
2022-09-14 15:15:03 +02:00
|
|
|
|
|
|
|
|
2023-10-04 15:25:26 +02:00
|
|
|
class BlacklistedToken(BaseModel):
|
2022-09-14 15:15:03 +02:00
|
|
|
__tablename__ = 'blacklisted_tokens'
|
|
|
|
|
2023-10-04 15:25:26 +02:00
|
|
|
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
|
|
|
|
token = db.Column(db.String(500), unique=True, nullable=False)
|
|
|
|
expired_at = db.Column(db.Integer, nullable=False)
|
|
|
|
blacklisted_on = db.Column(db.DateTime, nullable=False)
|
2022-09-14 15:15:03 +02:00
|
|
|
|
2022-09-15 13:14:55 +02:00
|
|
|
def __init__(
|
|
|
|
self, token: str, blacklisted_on: Optional[datetime] = None
|
|
|
|
) -> None:
|
|
|
|
payload = jwt.decode(
|
|
|
|
token,
|
|
|
|
current_app.config['SECRET_KEY'],
|
|
|
|
algorithms=['HS256'],
|
|
|
|
)
|
2022-09-14 15:15:03 +02:00
|
|
|
self.token = token
|
2022-09-15 13:14:55 +02:00
|
|
|
self.expired_at = payload['exp']
|
|
|
|
self.blacklisted_on = (
|
|
|
|
blacklisted_on if blacklisted_on else datetime.utcnow()
|
|
|
|
)
|
2022-09-14 15:15:03 +02:00
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def check(cls, auth_token: str) -> bool:
|
|
|
|
return cls.query.filter_by(token=str(auth_token)).first() is not None
|
2023-03-01 12:16:32 +01:00
|
|
|
|
|
|
|
|
2023-10-04 15:25:26 +02:00
|
|
|
class UserDataExport(BaseModel):
|
2023-03-01 12:16:32 +01:00
|
|
|
__tablename__ = 'users_data_export'
|
|
|
|
|
2023-10-04 15:25:26 +02:00
|
|
|
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
|
|
|
|
user_id = db.Column(
|
2023-03-01 12:16:32 +01:00
|
|
|
db.Integer,
|
2023-03-01 21:00:53 +01:00
|
|
|
db.ForeignKey('users.id', ondelete='CASCADE'),
|
2023-03-01 12:16:32 +01:00
|
|
|
index=True,
|
|
|
|
unique=True,
|
|
|
|
)
|
2023-10-04 15:25:26 +02:00
|
|
|
created_at = db.Column(
|
2023-03-01 12:16:32 +01:00
|
|
|
db.DateTime, nullable=False, default=datetime.utcnow
|
|
|
|
)
|
2023-10-04 15:25:26 +02:00
|
|
|
updated_at = db.Column(
|
2023-03-01 12:16:32 +01:00
|
|
|
db.DateTime, nullable=True, onupdate=datetime.utcnow
|
|
|
|
)
|
2023-10-04 15:25:26 +02:00
|
|
|
completed = db.Column(db.Boolean, nullable=False, default=False)
|
|
|
|
file_name = db.Column(db.String(100), nullable=True)
|
|
|
|
file_size = db.Column(db.Integer, nullable=True)
|
2023-03-01 12:16:32 +01:00
|
|
|
|
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
user_id: int,
|
|
|
|
created_at: Optional[datetime] = None,
|
|
|
|
):
|
|
|
|
self.user_id = user_id
|
|
|
|
self.created_at = (
|
|
|
|
datetime.utcnow() if created_at is None else created_at
|
|
|
|
)
|
|
|
|
|
|
|
|
def serialize(self) -> Dict:
|
|
|
|
if self.completed:
|
|
|
|
status = "successful" if self.file_name else "errored"
|
|
|
|
else:
|
|
|
|
status = "in_progress"
|
|
|
|
return {
|
|
|
|
"created_at": self.created_at,
|
|
|
|
"status": status,
|
|
|
|
"file_name": self.file_name if status == "successful" else None,
|
|
|
|
"file_size": self.file_size if status == "successful" else None,
|
|
|
|
}
|
2023-03-01 21:00:53 +01:00
|
|
|
|
|
|
|
|
|
|
|
@listens_for(UserDataExport, 'after_delete')
|
|
|
|
def on_users_data_export_delete(
|
|
|
|
mapper: Mapper, connection: Connection, old_record: 'UserDataExport'
|
|
|
|
) -> None:
|
|
|
|
@listens_for(db.Session, 'after_flush', once=True)
|
|
|
|
def receive_after_flush(session: Session, context: Any) -> None:
|
|
|
|
if old_record.file_name:
|
|
|
|
try:
|
|
|
|
file_path = (
|
|
|
|
f"exports/{old_record.user_id}/{old_record.file_name}"
|
|
|
|
)
|
|
|
|
os.remove(get_absolute_file_path(file_path))
|
|
|
|
except OSError:
|
|
|
|
appLog.error('archive found when deleting export request')
|