-
Notifications
You must be signed in to change notification settings - Fork 5
/
user.py
executable file
·72 lines (62 loc) · 2.62 KB
/
user.py
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
#!/usr/bin/python3
""" holds class User"""
import models
from hashlib import md5
from models import BaseModel, Base
from os import getenv
from sqlalchemy.orm import relationship
from sqlalchemy import Column, String
class User(BaseModel, Base):
"""Representation of a user """
__tablename__ = 'users'
email = Column(String(128), nullable=False)
_password = Column("password", String(128), nullable=False)
first_name = Column(String(128), nullable=True)
last_name = Column(String(128), nullable=True)
if getenv("HBNB_TYPE_STORAGE") in ["db", "sl"]:
places = relationship("Place",
backref="user",
cascade="all, delete-orphan")
reviews = relationship("Review",
backref="user",
cascade="all, delete-orphan")
else:
@property
def places(self):
"""Return list of places associated with the current user"""
place_values = models.storage.all("Place").values()
return list(filter(lambda p: p.user_id == self.id,
place_values))
@property
def reviews(self):
"""Return list of reviews associated with the current user"""
review_values = models.storage.all("Review").values()
return list(filter(lambda r: r.user_id == self.id,
review_values))
@property
def password(self):
"""Getter for protected _password attribute."""
return self._password
@password.setter
def password(self, pwd):
"""Setter for protected _password attribute. Only called by
console or api to ensure the we do not re-hash hashed password"""
self._password = md5(pwd.encode()).hexdigest()
def __init__(self, *args, **kwargs):
"""initializes user"""
self.email = kwargs.pop("email", "")
# Order of setting password and _password is important
# to prevent re-hashing hashed password or overwriting
# previously set password.
self.password = kwargs.pop("password", "")
self._password = kwargs.pop("_password", self.password)
self.first_name = kwargs.pop("first_name", "")
self.last_name = kwargs.pop("last_name", "")
super().__init__(*args, **kwargs)
def to_dict(self, to_storage=False):
"""Return dictionary of all attributes of User. Do not
include `password` attribute unless `to_storage=True`."""
d = super().to_dict()
if to_storage:
d.update({"_password": self._password})
return d