shakecities/accounts.py

94 lines
2.5 KiB
Python
Raw Normal View History

2023-11-08 17:55:49 +11:00
import os
import dotenv
from passlib.hash import argon2
import json
2023-11-08 19:02:24 +11:00
import db
2023-11-08 17:55:49 +11:00
dotenv.load_dotenv()
local = os.getenv('LOCAL')
def hash_password(password):
return argon2.using(rounds=16).hash(password)
2023-11-08 19:02:24 +11:00
def convert_db_users(db_entry):
return {
'id': db_entry[0],
'email': db_entry[1],
'domain': db_entry[2],
'password': db_entry[3],
'tokens': db_entry[4].split(',')
}
2023-11-08 17:55:49 +11:00
# Verify a password against a hashed password
def verify_password(password, hashed_password):
return argon2.verify(password, hashed_password)
def generate_cookie():
token = os.urandom(24).hex()
# Verify token doesn't already exist
2023-11-08 19:06:08 +11:00
while db.search_users_token(token) != []:
token = os.urandom(24).hex()
2023-11-08 17:55:49 +11:00
return token
# Create a new user
def create_user(email, domain, password):
2023-11-08 19:18:16 +11:00
if len(email) < 4 or len(domain) < 4 or len(password) < 4:
return {'success': False, 'message': 'Invalid email, domain, or password'}
2023-11-08 17:55:49 +11:00
# Hash password
hashed_password = hash_password(password)
# Create user
user = {
'email': email,
'domain': domain,
'password': hashed_password
}
# Create a cookie
token = generate_cookie()
user['tokens'] = [token]
2023-11-08 19:02:24 +11:00
# Check if user exists
if db.search_users(email) != []:
return {'success': False, 'message': 'User already exists'}
2023-11-08 17:55:49 +11:00
2023-11-08 19:02:24 +11:00
db.add_user(email, domain, hashed_password, token)
2023-11-08 17:55:49 +11:00
return {'success': True, 'message': 'User created', 'token': token}
def validate_token(token):
2023-11-08 19:02:24 +11:00
search = db.search_users_token(token)
if search == []:
return False
else:
return convert_db_users(search[0])
def logout(token):
# Remove token from user
user = validate_token(token)
if not user:
return {'success': False, 'message': 'Invalid token'}
user['tokens'].remove(token)
# Update user
db.update_tokens(user['id'], user['tokens'])
2023-11-08 20:06:47 +11:00
return {'success': True, 'message': 'Logged out'}
def login(email,password):
# Verify email
search = db.search_users(email)
if search == []:
return {'success': False, 'message': 'Invalid email'}
user = convert_db_users(search[0])
# Verify password
if not verify_password(password, user['password']):
return {'success': False, 'message': 'Invalid password'}
# Create a cookie
token = generate_cookie()
user['tokens'].append(token)
# Update user
db.update_tokens(user['id'], user['tokens'])
return {'success': True, 'message': 'Logged in', 'token': token}