lemur/lemur/users/models.py

100 lines
2.8 KiB
Python
Raw Normal View History

2015-06-22 22:47:27 +02:00
"""
.. module: lemur.users.models
:platform: unix
:synopsis: This module contains all of the models need to create a user within
lemur
:copyright: (c) 2018 by Netflix Inc., see AUTHORS for more
2015-06-22 22:47:27 +02:00
:license: Apache, see LICENSE for more details.
.. moduleauthor:: Kevin Glisson <kglisson@netflix.com>
"""
from sqlalchemy.orm import relationship
from sqlalchemy import Integer, String, Column, Boolean
2015-06-22 22:47:27 +02:00
from sqlalchemy.event import listen
from sqlalchemy_utils.types.arrow import ArrowType
2015-06-22 22:47:27 +02:00
from lemur.database import db
from lemur.models import roles_users
from lemur.extensions import bcrypt
def hash_password(mapper, connect, target):
"""
Helper function that is a listener and hashes passwords before
insertion into the database.
:param mapper:
:param connect:
:param target:
"""
target.hash_password()
class User(db.Model):
2019-05-16 16:57:02 +02:00
__tablename__ = "users"
2015-06-22 22:47:27 +02:00
id = Column(Integer, primary_key=True)
password = Column(String(128))
active = Column(Boolean())
confirmed_at = Column(ArrowType())
2015-06-22 22:47:27 +02:00
username = Column(String(255), nullable=False, unique=True)
email = Column(String(128), unique=True)
profile_picture = Column(String(255))
2019-05-16 16:57:02 +02:00
roles = relationship(
"Role",
secondary=roles_users,
passive_deletes=True,
backref=db.backref("user"),
lazy="dynamic",
)
certificates = relationship(
"Certificate", backref=db.backref("user"), lazy="dynamic"
)
pending_certificates = relationship(
"PendingCertificate", backref=db.backref("user"), lazy="dynamic"
)
authorities = relationship("Authority", backref=db.backref("user"), lazy="dynamic")
keys = relationship("ApiKey", backref=db.backref("user"), lazy="dynamic")
logs = relationship("Log", backref=db.backref("user"), lazy="dynamic")
sensitive_fields = ("password",)
2015-06-22 22:47:27 +02:00
def check_password(self, password):
"""
Hash a given password and check it against the stored value
to determine it's validity.
:param password:
:return:
"""
if self.password:
return bcrypt.check_password_hash(self.password, password)
2015-06-22 22:47:27 +02:00
def hash_password(self):
"""
Generate the secure hash for the password.
:return:
"""
if self.password:
2019-05-16 16:57:02 +02:00
self.password = bcrypt.generate_password_hash(self.password).decode("utf-8")
2015-06-22 22:47:27 +02:00
@property
def is_admin(self):
"""
Determine if the current user has the 'admin' role associated
with it.
:return:
"""
for role in self.roles:
2019-05-16 16:57:02 +02:00
if role.name == "admin":
2015-06-22 22:47:27 +02:00
return True
def __repr__(self):
return "User(username={username})".format(username=self.username)
2015-06-22 22:47:27 +02:00
2019-05-16 16:57:02 +02:00
listen(User, "before_insert", hash_password)