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
from bson.objectid import ObjectId
from .mongo import Model
from pymongo.errors import DuplicateKeyError
import hashlib
class User(Model):
@staticmethod
def dict_to_object(dictionary):
u = User(
first_name=dictionary["first_name"],
last_name=dictionary["last_name"],
email=dictionary["email"],
hashed_password=dictionary["hashed_password"]
)
u.__id = str(dictionary["_id"])
return u
def to_dict(self):
res = {}
if self.__id is not None:
res["_id"] = self.__id
if self.__first_name is not None:
res["first_name"] = self.__first_name
if self.__last_name is not None:
res["last_name"] = self.__last_name
if self.__email is not None:
res["email"] = self.__email
if self.__hashed_password is not None:
res["hashed_password"] = self.__hashed_password
return res
def __init__(self, first_name, last_name, email, hashed_password):
self.__id = None
self.__first_name = first_name
self.__last_name = last_name
self.__email = email
self.__hashed_password = hashed_password
@staticmethod
def get_collection():
return Model.get_db()["users"]
def get_id(self):
return self.__id
def store(self):
try:
add_document = User.get_collection().insert_one(self.to_dict())
self.__id = str(add_document.inserted_id)
except DuplicateKeyError:
print("Error occurred")
@staticmethod
def find_by_username(email):
u = User.get_collection().find_one({"email": email})
if u is not None:
return User.dict_to_object(u)
return u
@staticmethod
def find_by_id(object_id):
u = User.get_collection().find_one({"_id": ObjectId(object_id)})
if u is not None:
return User.dict_to_object(u)
return u
def compare_password(self, new_password):
new_hashed_password = hashlib.md5(new_password.encode()).hexdigest()
return self.__hashed_password == new_hashed_password