Event-CRUD-Flask-python3-API/services/UserService.py
2024-01-09 11:22:53 +02:00

61 lines
No EOL
1.8 KiB
Python

from flask_bcrypt import Bcrypt
from models import db, User, UserEventAssociation
bcrypt = Bcrypt()
class UserService:
@staticmethod
def create_user(data):
new_user = User(
name=data['username'],
email=data['email'],
location=data['location'],
password_hash=bcrypt.generate_password_hash(data['password']).decode('utf-8')
)
db.session.add(new_user)
db.session.commit()
return new_user.to_dict()
@staticmethod
def get_all_users():
users = User.query.all()
return [user.to_dict() for user in users]
@staticmethod
def get_user_by_email(email):
return User.query.filter_by(email=email).first()
@staticmethod
def get_user_by_id(user_id):
user = User.query.filter_by(id=user_id).first()
if user:
return user.to_dict()
return
@staticmethod
def verify_user(data):
user = UserService.get_user_by_email(data['email'])
if user and bcrypt.check_password_hash(user.password_hash, data['password']):
return user
return None
@staticmethod
def get_users_with_same_location_but_not_been_notifyed(location):
users = User.query.filter_by(location=location).all()
users = [user for user in users if not UserEventAssociation.query.filter_by(user_id=user.id).first()]
return [user.to_dict() for user in users]
@staticmethod
def update_user(user_id, data):
# update user
user = User.query.filter_by(id=user_id).first()
if user:
user.name = data['username']
user.email = data['email']
user.location = data['location']
db.session.commit()
return user.to_dict()
return None