File size: 1,986 Bytes
d72e3a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from Model.Database import Database
from Exceptions.UserExistsException import UserExistsException
from Exceptions.UserOrPasswordIncorrectException import UserOrPasswordIncorrectException
import bcrypt

class Service_User:

    def __init__(self):
        pass

    ### Signup user
    def signup_user(self, username, password):
        db = Database()

        if db.user_exists(username):
            db.close()
            raise UserExistsException("User already exists")

        try:
            hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())

            db.insert_user(username, str(hashed_password))
            db.close()
        except Exception as e:
            db.close()
            raise e
        
        return "Account created successfully"

    ### Login user
    def login_user(self, username, password):
        db = Database()
        user_info = db.select_user_by_name(username)
        
        if user_info is None:
            db.close()
            raise UserOrPasswordIncorrectException("User or Password incorrect.")

        try:
            hashed_password_from_db = user_info[2]

            if hashed_password_from_db.startswith("b'") and hashed_password_from_db.endswith("'"):
                hashed_password_from_db = hashed_password_from_db[2:-1].encode('utf-8')
            elif isinstance(hashed_password_from_db, str):
                hashed_password_from_db = hashed_password_from_db.encode('utf-8')

            password_match = bcrypt.checkpw(password.encode('utf-8'), hashed_password_from_db)

            db.close()
        except Exception as e:
            db.close()
            raise e
        
        if password_match == False:
            raise UserOrPasswordIncorrectException("User or Password incorrect.")
        
        return {
            'user_id': user_info[0],
            'user_name': user_info[1],
            'user_is_connected': True,
            'password_match': password_match
        }