Event-CRUD-Flask-python3-API/services/UserService.py

61 lines
1.8 KiB
Python
Raw Permalink Normal View History

2024-01-07 11:28:49 +00:00
from flask_bcrypt import Bcrypt
2024-01-09 09:01:39 +00:00
from models import db, User, UserEventAssociation
2024-01-07 11:28:49 +00:00
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()
2024-01-07 14:21:35 +00:00
return new_user.to_dict()
2024-01-07 11:28:49 +00:00
@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):
2024-01-09 09:17:01 +00:00
user = User.query.filter_by(id=user_id).first()
if user:
return user.to_dict()
return
2024-01-07 11:28:49 +00:00
@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
2024-01-09 09:01:39 +00:00
@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]
2024-01-09 09:22:53 +00:00
@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