~fnux/meta.sr.ht

ref: 1523a34288ef75828716b82551f545241e9eba7c meta.sr.ht/metasrht/auth/builtin.py -rw-r--r-- 992 bytes
1523a342Drew DeVault Add user profile information to admin page 8 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
import bcrypt
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()