Skip to content
This repository has been archived by the owner on Jan 20, 2024. It is now read-only.

Commit

Permalink
Add some auth/user management helpers
Browse files Browse the repository at this point in the history
  • Loading branch information
tdemin committed Jun 4, 2019
1 parent 3e2079c commit e56b91b
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 3 deletions.
36 changes: 36 additions & 0 deletions project_amber/helpers/auth.py
@@ -0,0 +1,36 @@
from hashlib import sha256
from base64 import b64encode

from bcrypt import hashpw, gensalt, checkpw

from project_amber.app import db
from project_amber.models.auth import User

def addUser(name: str, password: str) -> int:
"""
Creates a new user. Returns their ID on success.
"""
prehashed_pw = b64encode(sha256(password).digest())
hashed_pw = hashpw(prehashed_pw, gensalt())
user = User(name=name, password=hashed_pw)
db.session.add(user)
db.session.commit()
return user.id

def removeUser(uid: int) -> int:
"""
Removes a user given their ID. Returns their ID on success.
"""
user = db.session.query(User).filter_by(id=uid).one()
db.session.delete(user)
db.session.commit()
return uid

def verifyPassword(uid: int, password: str) -> bool:
"""
Verifies user's password with bcrypt's checkpw(). Returns `True`, if
the passwords match, and False otherwise.
"""
user = db.session.query(User).filter_by(id=uid).one()
prehashed_pw = b64encode(sha256(password).digest())
return checkpw(prehashed_pw, user.password)
10 changes: 7 additions & 3 deletions project_amber/models/auth.py
@@ -1,6 +1,10 @@
from project_amber.app import db

class User(db.Model):
"""
Holds the usual user details (username, password). The password is
hashed with bcrypt and a random salt.
"""
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(128), unique=True, nullable=False)
password = db.Column(db.String(256))
Expand All @@ -13,7 +17,7 @@ class Session(db.Model):
"""
token = db.Column(db.String(256), primary_key=True)
user = db.Column(db.Integer, db.ForeignKey("user.id"), nullable=False)
loginTime = db.Column(db.Integer, nullable=False)
login_time = db.Column(db.Integer, nullable=False)
def __repr__(self):
return "<Session token='%s' user='%d' loginTime='%d'>" % \
self.token, self.user, self.loginTime
return "<Session token='%s' user='%d' login_time='%d'>" % \
self.token, self.user, self.login_time

0 comments on commit e56b91b

Please sign in to comment.