2018-09-20 20:05:03 +00:00
|
|
|
from app.core import bcrypt
|
2018-05-06 19:42:21 +00:00
|
|
|
from flask import Blueprint
|
|
|
|
from .models import Account
|
|
|
|
|
|
|
|
accounts_bp = Blueprint('accounts', __name__)
|
|
|
|
|
|
|
|
|
|
|
|
def create_account(username, email, password):
|
|
|
|
"""
|
|
|
|
Tries to create account with given parameters. Raises error on failure
|
|
|
|
|
|
|
|
:param username: Desired username for Account
|
|
|
|
:param email: Desired email for Account
|
|
|
|
:param password: Desired password for Account
|
|
|
|
:type username: string
|
|
|
|
:type email: string
|
|
|
|
:type password: string
|
2018-05-08 14:45:09 +00:00
|
|
|
:returns: True if account is successfully created
|
|
|
|
:rtype: Boolean
|
|
|
|
:raises: ValueError if account already exists
|
2018-05-06 19:42:21 +00:00
|
|
|
"""
|
|
|
|
if not Account.exists_with_any_of(username=username, email=email):
|
|
|
|
pw_hash = bcrypt.generate_password_hash(password).decode('utf-8')
|
|
|
|
account = Account(username, pw_hash, email)
|
|
|
|
account.save()
|
|
|
|
return True
|
|
|
|
|
|
|
|
raise ValueError("Account with given parameters already exists")
|
|
|
|
|
|
|
|
|
2018-09-22 17:01:50 +00:00
|
|
|
def update_account_role(account_id, role_id):
|
|
|
|
"""
|
|
|
|
Tries to update account role
|
|
|
|
|
|
|
|
:param account_id: Target account id
|
|
|
|
:param role_id: New role role_id
|
|
|
|
:type account_id: int
|
|
|
|
:type role_id: int
|
|
|
|
:returns: True if role is updated successfully
|
|
|
|
:rtype: Boolean
|
|
|
|
"""
|
|
|
|
acc = Account.get(id=account_id)
|
|
|
|
acc.role_id = role_id
|
|
|
|
acc.save()
|
|
|
|
|
|
|
|
|
2018-05-06 19:42:21 +00:00
|
|
|
def create_token(username, password):
|
|
|
|
"""
|
|
|
|
Tries to create token for account with given parameters.
|
|
|
|
Raises error on failure
|
|
|
|
|
|
|
|
:param username: username of Account
|
|
|
|
:param password: password of Account
|
|
|
|
:type username: string
|
|
|
|
:type password: string
|
2018-05-08 14:45:09 +00:00
|
|
|
:returns: created token
|
|
|
|
:rtype: string
|
|
|
|
:raises: ValueError if credentials are invalid or account does not exist
|
2018-05-06 19:42:21 +00:00
|
|
|
"""
|
|
|
|
if not Account.exists(username=username):
|
|
|
|
raise ValueError("Invalid credentials")
|
|
|
|
|
|
|
|
account = Account.get(username=username)
|
|
|
|
if not bcrypt.check_password_hash(account.password, password):
|
|
|
|
raise ValueError("Invalid credentials")
|
|
|
|
|
|
|
|
return account.create_auth_token()
|
2018-05-07 15:17:19 +00:00
|
|
|
|
|
|
|
|
|
|
|
def validate_token(token):
|
|
|
|
"""
|
|
|
|
Validates token and returns associated account
|
|
|
|
|
|
|
|
:param token: auth token to validate
|
|
|
|
:type token: string
|
2018-05-08 14:45:09 +00:00
|
|
|
:returns: created token
|
|
|
|
:rtype: Account
|
2018-05-07 15:17:19 +00:00
|
|
|
"""
|
|
|
|
return Account.validate_token(token)
|