~fnux/meta.sr.ht

ref: e929d461b76fb7b17963c864192a975562bf23b6 meta.sr.ht/metasrht/auth/builtin.py -rw-r--r-- 1.1 KiB
e929d461Timothée Floure Make password reset logic more generic 9 months ago
                                                                                
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
39
import bcrypt

from srht.database import db
from srht.validation import Validation

from metasrht.auth.base import AuthMethod, get_user
from metasrht.types.user import User


class BuiltinAuthMethod(AuthMethod):
    def user_valid(self, valid: Validation, username: str, password: str) \
            -> bool:
        username = get_user(username)

        valid.expect(username is not None, "Username or password incorrect")

        if valid.ok:
            valid.expect(username.password, "Username or password incorrect")

        if valid.ok:
            valid.expect(check_password(password, username.password),
                         "Username or password incorrect")

        return valid.ok

    def prepare_user(self, username: str) -> User:
        return get_user(username)


def check_password(password: str, hash: str) -> bool:
    return bcrypt.checkpw(password.encode(), hash.encode())


def hash_password(password: str) -> str:
    return bcrypt.hashpw(password.encode(), salt=bcrypt.gensalt()).decode()

def set_user_password(self, user: User, password: str) -> None:
    user.password = hash_password(password)
    db.session.commit()