auth.py 926 Bytes
Newer Older
Michal Pavlík's avatar
Michal Pavlík committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
from errors import WrongCredentials
from models import User
from config import PUBLIC_KEY, db
import bcrypt
import jwt


def basic_auth(username, password, required_scopes):
    user = User.query.filter_by(username=username).first()

    pswd = bytes(password, encoding='utf-8')
    is_pass_correct = bcrypt.checkpw(pswd, user.password)
    if not user or not is_pass_correct:
        raise WrongCredentials

    return {
        'sub': user.id,
        'username': user.username,
        'scope': 'read write'
    }



def oauth2(token):
    vals = jwt.decode(token, PUBLIC_KEY, algorithms='RS256')

    user = User.query.filter_by(uuid=vals['sub']).first()

    if not user:
        user = User(username=vals['name'], uuid=vals['sub'], password='external')
        db.session.add(user)
        db.session.commit()

    return {
        'sub': user.id,
        'username': user.username,
        'scope': vals['scope']
    }