user.py 2.08 KB
Newer Older
Vladislav Rykov's avatar
Vladislav Rykov 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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import psycopg2
import bcrypt


class UserDao:
    
    def __init__(self):
        pass

    # decorator implementation
    def with_psql(f):
        def _with_psql(*args, **kwargs):
            conn = psycopg2.connect('dbname=gateway')
            cur = conn.cursor()

            try:
                res = f(cur, *args, **kwargs)
            except (Exception, psycopg2.DatabaseError) as error:
                conn.rollback()
                res = (False, error)
            else:
                conn.commit()
            finally:
                cur.close()
                conn.close()
    
            return res
        return _with_psql

    @staticmethod
    @with_psql
    def create(cur, name, password):
        query = """
        INSERT INTO
            users
        VALUES
            (%s, %s)
        """
        cur.execute(query, (name, bcrypt.hashpw(password, bcrypt.gensalt())))
        return (True,)

    @staticmethod
    @with_psql 
    def delete(cur, name):
        query = """
        DELETE FROM
            users
        WHERE
            name = %s
        """
        cur.execute(query, (name,))
        return (True,)

    @staticmethod
    @with_psql
    def update_name(cur, old_name, new_name):
        query = """
        UPDATE users SET
            name = %s
        WHERE
            name = %s
        """
        cur.execute(query, (new_name,))
        return (True,)

    @staticmethod
    @with_psql
    def update_password(cur, name, password):
        query = """
        UPDATE users SET
            password = %s
        WHERE
            name = %s
        """
        cur.execute(query, (password, name))
        return (True,)

    @staticmethod
    @with_psql
    def get(cur, name, password):
        query = """
        SELECT * FROM
            users
        WHERE 
            name = %s
        """
        cur.execute(query, (name,))
        user = cur.fetchall()[0]
        
        if user[1].encode('utf-8') == bcrypt.hashpw(password, user[1].encode('utf-8')):
            return (True, user)
        else:
            return (False, 'Password or username do not match')