예제 #1
0
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(120), unique=True)
    hashSalt = db.Column(db.Binary(120))
    hashpwd = db.Column(db.Binary(120))

    blogs = db.relationship('Blog', backref='owner')

    def __init__(self, username, hashSalt, hashpwd):
        self.username = username
        self.hashSalt = hashSalt
        self.hashpwd = hashpwd
예제 #2
0
class User(db.Model):
    __tablename__ = 'users'
    name = db.Column(db.String(100), primary_key=True)
    password = db.Column(db.Binary(32))
    salt = db.Column(db.Binary(32))

    def __init__(self, name, password):
        self.name = name
        self.salt = os.urandom(32)
        self.password = hashlib.pbkdf2_hmac('sha256', password.encode(), self.salt, 100000)

    def check_pass(self, password):
        return self.password == hashlib.pbkdf2_hmac('sha256', password.encode(), self.salt, 100000)
예제 #3
0
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(
        db.String(140),
        index=True,
        unique=True,
    )
    joined = db.Column(db.DateTime, )
    password_hash = db.Column(db.Binary(60), )
    u2f_credentials = db.relationship(
        'U2FCredentials',
        backref='user',
        lazy='dynamic',
    )

    def __init__(self, username, password, joined=None):
        self.username = username
        self.password_hash = bcrypt.hashpw(password.encode('utf-8'),
                                           bcrypt.gensalt())
        if joined is None:
            joined = datetime.now()
        self.joined = joined

    def __repr__(self):
        return '<User %r>' % (self.username)
예제 #4
0
class User(Base, UserMixin):

    __tablename__ = 'user'

    # Identification Data: email & password
    email = db.Column(db.String(128), nullable=False, unique=True)
    password = db.Column(db.Binary(128), nullable=False)

    budgets = db.relationship('Budget')

    expenses = db.relationship('Expense')

    # New instance instantiation procedure
    def __init__(self, email, password):

        self.email = email
        if password:
            self.set_password(password)
        else:
            self.password = None

    def set_password(self, password):
        self.password = bcrypt.generate_password_hash(password)

    def check_password(self, value):
        return bcrypt.check_password_hash(self.password, value)

    def __repr__(self):
        return '<User %r>' % (self.email)
예제 #5
0
class User(db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String(80), unique=True)
    email = db.Column(db.String(32), unique=True)
    password = db.Column(db.Binary(32), nullable=False)
    key = db.Column(db.String(32), nullable=False, unique=True)

    def __init__(self, username, password, email):
        self.key = randomStr(32)  # 32位随机字符 唯一标识用户
        self.username = str(username)
        self.email = email
        self.password = encrypt(password)

    # 登录函数 在数据库中验证
    @staticmethod
    def login(username, password):
        # 先查询用户名
        re = User.query.filter_by(username=username).first()
        # 没查到则查email
        if not re:
            re = User.query.filter_by(email=username).first()

        if re and re.isRight(password):
            session['username_key'] = re.key
            session['password'] = re.password
            session.permanent = True
            return True
        else:
            return False

    # 存入数据库
    def save(self):
        if self.validate():
            db.session.add(self)
            db.session.commit()
            return True
        else:
            return False

    # 验证用户输入是否正确
    def validate(self):
        return True

    def __repr__(self):
        return "Username: %s" % self.username

    # 参数password 明文或密文
    def isRight(self, password, isplain=True):
        if isplain:
            if decrypt(self.password) == password:
                return True
            else:
                return False
        else:
            if self.password == password:
                return True
            else:
                return False
예제 #6
0
파일: models.py 프로젝트: lqf96/cwng-bknd
class User(db.Model):
    # Table schema
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String(32), unique=True)
    email = db.Column(db.String(64), unique=True)
    password = db.Column(db.Binary(32))
    join_date = db.Column(db.DateTime(), default=datetime.now)
    active = db.Column(db.Boolean(), default=False)
예제 #7
0
class User(Base, UserMixin):
    """
    User model that represents the user of the application
    Current schema (specific to this model):
        email: str,
        password: hashed,
        budgets: entries in the budget table,
        expenses: entries in the expense table
    :param email: User's email
    :param password: User's password
    :type email: str
    :type password: str
    """
    __tablename__ = 'user'

    # Identification Data: email & password
    email = db.Column(db.String(128), nullable=False, unique=True)
    password = db.Column(db.Binary(128), nullable=False)

    budgets = db.relationship('Budget')

    expenses = db.relationship('Expense')

    # New instance instantiation procedure
    def __init__(self, email, password):

        self.email = email
        if password:
            self.set_password(password)
        else:
            self.password = None

    def set_password(self, password):
        """
        Set's a user's password to a hashed version of their desired password
        :param password: User's password
        :type password: str
        """
        self.password = bcrypt.generate_password_hash(password)

    def check_password(self, value):
        """Verify password against stored hashed password.

        :param str value: The password to verify.
        :return: True if the password matches the stored hashed password.
        :rtype: bool
        """
        return bcrypt.check_password_hash(self.password, value)

    def __repr__(self):
        """
        Creates a string representation of the User
        :return: User string representation
        :rtype: str
        """
        return '<User %r>' % (self.email)
예제 #8
0
class User(db.Model):
    '''
    Class that represents a user of the application

    The following attributes of a user are stored in this table:
        email address
        password (hashed using Bcrypt)
        authenticated flag (indicates if a user is logged in or not)
        date that the user registered on
    '''

    __tablename__ = 'users'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    email = db.Column(db.String, unique=True, nullable=False)
    hashed_password = db.Column(db.Binary(60), nullable=False)
    authenticated = db.Column(db.Boolean, default=False)
    created_on = db.Column(db.DateTime, nullable=True)
    role = db.Column(db.String, default='user')
    feature_requests = db.relationship('FeatureRequest')

    def __init__(self, email, plain_password, role='user'):
        self.email = email
        self.hashed_password = bcrypt.generate_password_hash(plain_password)
        self.authenticated = False
        self.created_on = datetime.now()
        self.role = role

    def set_password(self, plain_password):
        self.hashed_password = bcrypt.generate_password_hash(plain_password)

    def is_correct_password(self, plain_password):
        return bcrypt.check_password_hash(self.hashed_password, plain_password)

    @property
    def is_authenticated(self):
        '''Return True if the user is authenticated.'''
        return self.authenticated

    @property
    def is_active(self):
        '''Always True, as all users are active.'''
        return True

    @property
    def is_anonymous(self):
        '''Always False, as anonymous users aren't supported.'''
        return False

    def get_id(self):
        '''Return the id of a user to satisfy Flask-Login's requirements.'''
        return str(self.id)

    def __repr__(self):
        return '<User {}>'.format(self.email)
예제 #9
0
class User(db.Model):
    """ User model class. """
    id = db.Column(db.Integer(), primary_key=True, autoincrement=True)
    username = db.Column(db.String(32), unique=True)
    email = db.Column(db.String(64), unique=True)
    password = db.Column(db.Binary(32))
    join_date = db.Column(db.DateTime(), default=datetime.now)
    active = db.Column(db.Boolean(), default=False)
    avatar = db.Column(UploadedFileField())
    self_introduction = db.Column(db.Text(), unique=True)
    contribution = db.Column(db.Integer(), default=0)
    job = db.Column(db.String(64), unique=True)
예제 #10
0
class User(db.Model):
    __tablename__ = 'ithriv_user'
    id = db.Column(db.Integer, primary_key=True)
    eppn = db.Column(db.String, nullable=True)
    email = db.Column(db.String, nullable=False, unique=True)
    display_name = db.Column(db.String)
    _password = db.Column('password', db.Binary(60))
    role = db.Column(db.String(), default='User')
    email_verified = db.Column(db.Boolean, nullable=False, default=False)
    institution_id = db.Column('institution_id', db.Integer(), db.ForeignKey('institution.id'))
    institution = db.relationship('ThrivInstitution')
    institutional_role = db.Column(db.String)
    division = db.Column(db.String)

    @hybrid_property
    def password(self):
        return self._password

    @password.setter
    def password(self, plaintext):
        self._password = bcrypt.generate_password_hash(plaintext)

    def is_correct_password(self, plaintext):
        if not self._password:
            raise RestException(RestException.LOGIN_FAILURE);
        return bcrypt.check_password_hash(self._password, plaintext)

    def encode_auth_token(self):
        try:
            payload = {
                'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=2, minutes=0, seconds=0),
                'iat': datetime.datetime.utcnow(),
                'sub': self.id
            }
            return jwt.encode(
                payload,
                app.config.get('SECRET_KEY'),
                algorithm='HS256'
            )
        except Exception as e:
            return e

    @staticmethod
    def decode_auth_token(auth_token):
        try:
            payload = jwt.decode(auth_token, app.config.get('SECRET_KEY'), algorithms='HS256')
            return payload['sub']
        except jwt.ExpiredSignatureError:
            raise RestException(RestException.TOKEN_EXPIRED)
        except jwt.InvalidTokenError:
            raise RestException(RestException.TOKEN_INVALID)
예제 #11
0
class Users(db.Model):
    __tablename__ = 'users'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    email = db.Column(db.String, unique=True, nullable=False)
    _password = db.Column(db.Binary(60), nullable=False)
    authenticated = db.Column(db.Boolean, default=False)
    role = db.Column(db.String, default='user')

    def __init__(self, email, plaintext_password, role):
        self.email = email
        self.password = plaintext_password
        self.authenticated = False
        self.role = role

    @hybrid_property
    def password(self):
        return self._password

    @password.setter
    def set_password(self, plaintext_password):
        self._password = bcrypt.generate_password_hash(plaintext_password)

    @hybrid_method
    def is_correct_password(self, plaintext_password):
        return bcrypt.check_password_hash(self.password, plaintext_password)

    @property
    def is_authenticated(self):
        """Return True if the user is authenticated."""
        return self.authenticated

    @property
    def is_active(self):
        """Always True, as all users are active."""
        return True

    @property
    def is_anonymous(self):
        """Always False, as anonymous users aren't supported."""
        return False

    def get_id(self):
        """Return the email address to satisfy Flask-Login's requirements."""
        """Requires use of Python 3"""
        return str(self.id)

    def __repr__(self):
        return '<User {0}>'.format(self.name)
예제 #12
0
class UserModel(db.Model):
    __tablename__ = "user"

    id = db.Column(db.Integer, primary_key=True)
    first_name = db.Column(db.String(20), nullable=False)
    last_name = db.Column(db.String(30), nullable=False)
    country = db.Column(db.String(30), nullable=False)
    city = db.Column(db.String(30), nullable=False)
    _password = db.Column(db.Binary(60), nullable=False)
    email = db.Column(db.String(50), nullable=False, unique=True)
    validated = db.Column(db.Boolean, nullable=False, default=False)

    confirmation = db.relationship("ConfirmationModel",
                                   backref="user",
                                   lazy=True)

    def save_to_db(self):
        db.session.add(self)
        db.session.commit()

    def update_to_db(self):
        db.session.commit()

    def delete_from_db(self):
        db.session.delete(self)
        db.session.commit()

    @hybrid_property
    def password(self):
        return self._password

    @password.setter
    def set_password(self, plaintext_password):
        self._password = bcrypt.generate_password_hash(plaintext_password, 12)

    @hybrid_method
    def is_correct_password(self, plaintext_password):
        return bcrypt.check_password_hash(self.password, plaintext_password)

    @classmethod
    def get_user_by_email(cls, email):
        return cls.query.filter_by(email=email).first()

    @classmethod
    def get_user_by_id(cls, id):
        return cls.query.filter_by(id=id).first()
예제 #13
0
class User(Base):

    __tablename__ = 'users'

    username = db.Column(db.String(255), unique=True, nullable=False)
    email = db.Column(db.String(255), unique=True, nullable=False)
    full_name = db.Column(db.String(255), nullable=False)
    avatar = db.Column(db.String(255), nullable=True)
    confirmed = db.Column(db.Boolean, nullable=False, default=False)
    confirmed_on = db.Column(db.DateTime, nullable=True)
    superuser = db.Column(db.Boolean, nullable=False, default=False)
    last_login = db.Column(db.DateTime, nullable=True)
    _password = db.Column(db.Binary(128))
    issues = db.relationship('Issue', backref='user', lazy=True)

    @hybrid_property
    def password(self):
        return self._password

    @password.setter
    def _set_password(self, plaintext):
        self._password = bcrypt.generate_password_hash(plaintext)

    def is_correct_password(self, plaintext):
        return bcrypt.check_password_hash(self._password, plaintext)

    @property
    def show_avatar(self):
        return HTMLString(
            f'<img height="30" width="30" src="/{app.config["UPLOAD_FOLDER"]}/{self.avatar}">'
        )

    def is_authenticated(self):
        return True

    def is_active(self):
        return True

    def is_anonymous(self):
        return False

    def get_id(self):
        return str(self.id)

    def __repr__(self):
        return self.username
예제 #14
0
class User(db.Model):

    __tablename__ = 'users'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    email = db.Column(db.String, unique=True, nullable=False)
    hashed_password = db.Column(db.Binary(60), nullable=False)
    authenticated = db.Column(db.Boolean, default=False)
    registered_on = db.Column(db.DateTime, nullable=True)
    role = db.Column(db.String, default='user')

    def __init__(self, email, plaintext_password, role='user'):
        self.email = email
        self.hashed_password = bcrypt.generate_password_hash(plaintext_password)
        self.authenticated = False
        self.registered_on = datetime.now()
        self.role = role

    def set_password(self, plaintext_password):
        self.hashed_password = bcrypt.generate_password_hash(plaintext_password)

    def is_correct_password(self, plaintext_password):
        return bcrypt.check_password_hash(self.hashed_password, plaintext_password)

    @property
    def is_authenticated(self):
        """Return True if the user is authenticated."""
        return self.authenticated

    @property
    def is_active(self):
        """Always True, as all users are active."""
        return True

    @property
    def is_anonymous(self):
        """Always False, as anonymous users aren't supported."""
        return False

    def get_id(self):
        """Return the id of a user to satisfy Flask-Login's requirements."""
        return str(self.id)

    def __repr__(self):
        return '<User {}>'.format(self.email)
예제 #15
0
class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), index=True, unique=True)
    email = db.Column(db.String(120), index=True, unique=True)
    key = db.Column(db.Binary(32))
    password_hash = db.Column(db.String(128))
    projects = db.relationship('Project', backref='owner', lazy='dynamic')

    def __repr__(self):
        return '<User {}>'.format(self.username)

    def set_password(self, password):
        self.password_hash = generate_password_hash(password)

    def check_password(self, password):
        return check_password_hash(self.password_hash, password)

    def generate_key(self):
        self.key = Fernet.generate_key()
예제 #16
0
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True,autoincrement=True)
    email = db.Column(db.String(64), unique=True)
    _password = db.Column(db.Binary(60))
    character = db.relationship('Character',backref='user',uselist=False)
    role = db.Column(db.String(64))

    @property
    def is_active(self):
        return True

    @property
    def is_authenticated(self):
        return True

    @property
    def is_anonymous(self):
        return False

    def get_id(self):
        return self.id

    @hybrid_property
    def password(self):
        return self._password

    @password.setter
    def _set_password(self, plaintext):
        self._password = bcrypt.generate_password_hash(plaintext)

    def __init__(self, email='', password=''):
        self.email = email
        self.password = password
        self.role = 'user'

    def __repr__(self):
        return '<User #{} {}>'.format(self.id,self.email)
예제 #17
0
class User(db.Model, UserMixin):

    # tablename 'user' does not work in postgres
    __tablename__ = 'users'

    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, index=True)
    # use Binary for postgres
    password_hash = db.Column(db.Binary())
    todolist = db.relationship('ToDoList', lazy='dynamic')
    keepdolist = db.relationship('KeepDoList', lazy='dynamic')

    def set_password(self, plain_password):
        self.password_hash = bcrypt.generate_password_hash(plain_password)

    def verify_password(self, plain_password):
        return bcrypt.check_password_hash(self.password_hash, plain_password)

    @classmethod
    def find_by_username(cls, username):
        return cls.query.filter_by(username=username).first()

    @classmethod
    def find_by_id(cls, _id):
        return cls.query.filter_by(id=_id).first()

    # qurying todo and keepdo specific to user
    # return http 404 if nothing found
    def get_todo(self, _id):
        return self.todolist.filter_by(id=_id).first_or_404()

    def get_keepdo(self, _id):
        return self.keepdolist.filter_by(id=_id).first_or_404()

    def __repr__(self):
        return '<User {}>'.format(self.username)
예제 #18
0
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    user_name = db.Column(db.String(128), nullable=False)
    _password = db.Column(db.Binary(60))
    authenticated = db.Column(db.Boolean, default=False)

    def __init__(self, user_name, plaintext_password):
        self.user_name = user_name
        self.password = plaintext_password

    def is_active(self):
        return True

    def get_id(self):
        return self.id

    def is_authenticated(self):
        return self.authenticated

    def is_anonymous(self):
        return False

    @hybrid_property
    def password(self):
        return self._password

    @password.setter
    def password(self, plaintext):
        self._password = bcrypt.generate_password_hash(plaintext).decode(
            'utf-8')

    @hybrid_method
    def is_correct_password(self, plaintext_password):
        if bcrypt.check_password_hash(self.password, plaintext_password):
            return True
        return False
예제 #19
0
class User(db.Model):

    __tablename__ = 'users'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    email = db.Column(db.String, unique=True, nullable=False)
    _password = db.Column(db.Binary(60), nullable=False)
    authenticated = db.Column(db.Boolean, default=False)
    email_confirmation_sent_on = db.Column(db.DateTime, nullable=True)
    email_confirmed = db.Column(db.Boolean, nullable=True, default=False)
    email_confirmed_on = db.Column(db.DateTime, nullable=True)
    registered_on = db.Column(db.DateTime, nullable=True)
    last_logged_in = db.Column(db.DateTime, nullable=True)
    current_logged_in = db.Column(db.DateTime, nullable=True)
    role = db.Column(db.String, default='user')
    recipes = db.relationship('Recipe', backref='user', lazy='dynamic')

    def __init__(self,
                 email,
                 plaintext_password,
                 email_confirmation_sent_on=None,
                 role='user'):
        self.email = email
        self.password = plaintext_password
        self.authenticated = False
        self.email_confirmation_sent_on = datetime.now()
        self.email_confirmed = True
        self.email_confirmed_on = datetime.now()
        self.registered_on = datetime.now()
        self.last_logged_in = None
        self.current_logged_in = datetime.now()
        self.role = role

    @hybrid_property
    def password(self):
        return self._password

    @password.setter
    def set_password(self, plaintext_password):
        self._password = bcrypt.generate_password_hash(plaintext_password)

    @hybrid_method
    def is_correct_password(self, plaintext_password):
        return bcrypt.check_password_hash(self.password, plaintext_password)

    @property
    def is_authenticated(self):
        """Return True if the user is authenticated."""
        return self.authenticated

    @property
    def is_active(self):
        """Always True, as all users are active."""
        return True

    @property
    def is_anonymous(self):
        """Always False, as anonymous users aren't supported."""
        return False

    def get_id(self):
        """Return the email address to satisfy Flask-Login's requirements."""
        """Requires use of Python 3"""
        return str(self.id)

    def generate_auth_token(self, expires_in=3600):
        s = Serializer(app.config['SECRET_KEY'], expires_in=expires_in)
        return s.dumps({'id': self.id}).decode('utf-8')

    @staticmethod
    def verify_auth_token(token):
        s = Serializer(app.config['SECRET_KEY'])
        try:
            data = s.loads(token)
        except:
            return None
        return User.query.get(data['id'])

    def __repr__(self):
        return '<User {}>'.format(self.email)
예제 #20
0
class User(db.Model):

    __tablename__ = 'users'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    email = db.Column(db.String, unique=True, nullable=False)
    _password = db.Column(db.Binary(60), nullable=False)
    authenticated = db.Column(db.Boolean, default=False)
    email_confirmation_sent_on = db.Column(db.DateTime, nullable=True)
    email_confirmed = db.Column(db.Boolean, nullable=False)
    email_confirmed_on = db.Column(db.DateTime, nullable=True)
    registered_on = db.Column(db.DateTime, nullable=True)
    last_logged_in = db.Column(db.DateTime, nullable=True)
    current_logged_in = db.Column(db.DateTime, nullable=True)
    role = db.Column(db.String, default='user')
    recipes = db.relationship('Recipe', backref='user', lazy='dynamic')

    def __init__(self,
                 email,
                 plaintext_password,
                 email_confirmation_sent_on=None,
                 role='user'):
        self.email = email
        self.password = plaintext_password
        self.authenticated = False
        self.email_confirmation_sent_on = email_confirmation_sent_on
        self.email_confirmed = False
        self.email_confirmed_on = None
        self.registered_on = datetime.now()
        self.last_logged_in = None
        self.current_logged_in = datetime.now()
        self.role = role

    @hybrid_property
    def password(self):
        return self._password

    @password.setter
    def set_password(self, plaintext_password):
        self._password = bcrypt.generate_password_hash(plaintext_password)

    @hybrid_method
    def is_correct_password(self, plaintext_password):
        '''Return True if user is authenticated'''
        return bcrypt.check_password_hash(self.password, plaintext_password)

    @property
    def is_authenticated(self):
        '''Return True is user is authenticated'''
        return self.authenticated

    @property
    def is_active(self):
        '''Always True. All users are active'''
        return True

    @property
    def is_anonymous(self):
        '''Always False. Anonymous users are not supported'''
        return False

    def get_id(self):
        '''Return the email address to satisfy Flask-Login requirements'''
        '''Requires use of Python 3'''
        return str(self.id)

    def __repr__(self):
        return '<User {}>'.format(self.name)
예제 #21
0
class User(db.Model):
    # The user model is used to manage interaction with the StarDrive system, including sign-in and access levels. Users
    # can be Admins, people with autism and/or their guardians wishing to manage their care and participate in studies,
    # as well professionals in the field of autism research and care. Anyone who wishes to use the system will have a
    # user account. Please note that there is a separate participant model for tracking enrollment and participation in
    # studies.
    __tablename__ = 'stardrive_user'
    #    id = db.Column(db.Integer, primary_key=True)
    id = db.Column(db.Integer, primary_key=True, default=random_integer)
    last_updated = db.Column(db.DateTime(timezone=True), default=func.now())
    registration_date = db.Column(db.DateTime(timezone=True),
                                  default=func.now())
    last_login = db.Column(db.DateTime(timezone=True))
    email = db.Column(db.String, nullable=False, unique=True)
    role = db.Column(db.Enum(Role))
    participants = db.relationship(Participant, back_populates="user")
    participant_count = column_property(
        select([
            func.count(Participant.id)
        ]).where(Participant.user_id == id).correlate_except(Participant))
    email_verified = db.Column(db.Boolean, nullable=False, default=False)
    _password = db.Column('password', db.Binary(60))
    token = ''
    token_url = ''

    def related_to_participant(self, participant_id):
        for p in self.participants:
            if p.id == participant_id:
                return True
        return False

    def get_self_participant(self):
        if len(self.participants) > 0:
            for p in self.participants:
                if "self" in p.relationship.name:
                    return p

    def self_registration_complete(self):
        if self.get_self_participant() is not None:
            return self.get_self_participant().get_percent_complete() == 1

    @hybrid_property
    def password(self):
        return self._password

    @password.setter
    def password(self, plaintext):
        role_name = self.role_name()
        if self.password_meets_requirements(role_name, plaintext):
            self._password = bcrypt.generate_password_hash(plaintext)
        else:
            message = "Please enter a valid password. " + password_requirements[
                role_name]['instructions']
            raise RestException(RestException.INVALID_INPUT, details=message)

    def role_name(self):
        return self.role if isinstance(self.role, str) else self.role.name

    @classmethod
    def password_meets_requirements(cls, role_name, plaintext):
        reqs = password_requirements[role_name]
        regex = re.compile(reqs['regex'])

        if plaintext and isinstance(plaintext, str):
            match = regex.match(plaintext)
            return bool(match)
        else:
            return False

    def is_correct_password(self, plaintext):
        if not self._password:
            raise RestException(RestException.LOGIN_FAILURE)
        return bcrypt.check_password_hash(self._password, plaintext)

    def encode_auth_token(self):
        try:
            payload = {
                'exp':
                datetime.datetime.utcnow() +
                datetime.timedelta(hours=2, minutes=0, seconds=0),
                'iat':
                datetime.datetime.utcnow(),
                'sub':
                self.id
            }
            return jwt.encode(payload,
                              app.config.get('SECRET_KEY'),
                              algorithm='HS256')
        except Exception as e:
            return e

    @staticmethod
    def decode_auth_token(auth_token):
        try:
            payload = jwt.decode(auth_token,
                                 app.config.get('SECRET_KEY'),
                                 algorithms='HS256')
            return payload['sub']
        except jwt.ExpiredSignatureError:
            raise RestException(RestException.TOKEN_EXPIRED)
        except jwt.InvalidTokenError:
            raise RestException(RestException.TOKEN_INVALID)

    def get_contact(self):
        for p in self.participants:
            if p.contact:
                return {
                    'name': p.get_name(),
                    'relationship': p.relationship.name,
                    'contact': p.contact
                }

    def created_password(self):
        return self.password is not None

    def identity(self):
        if len(self.participants) > 0:
            return self.get_self_participant().relationship.name
        else:
            return 'Not set'

    def percent_self_registration_complete(self):
        if len(self.participants) > 0:
            return self.get_self_participant().get_percent_complete()
예제 #22
0
파일: user.py 프로젝트: danfunk/star-drive
class User(db.Model):
    # The user model is used to manage interaction with the StarDrive system, including sign-in and access levels. Users
    # can be Admins, people with autism and/or their guardians wishing to manage their care and participate in studies,
    # as well professionals in the field of autism research and care. Anyone who wishes to use the system will have a
    # user account. Please note that there is a separate participant model for tracking enrollment and participation in
    # studies.
    __tablename__ = 'stardrive_user'
    #    id = db.Column(db.Integer, primary_key=True)
    id = db.Column(db.Integer, primary_key=True, default=random_integer)
    last_updated = db.Column(db.DateTime(timezone=True), default=func.now())
    email = db.Column(db.String, nullable=False, unique=True)
    role = db.Column(db.Enum(Role))
    participants = db.relationship(Participant, back_populates="user")
    email_verified = db.Column(db.Boolean, nullable=False, default=False)
    _password = db.Column('password', db.Binary(60))
    token = ''

    def related_to_participant(self, participant_id):
        for p in self.participants:
            if p.id == participant_id:
                return True
        return False

    @hybrid_property
    def password(self):
        return self._password

    @password.setter
    def password(self, plaintext):
        self._password = bcrypt.generate_password_hash(plaintext)

    def is_correct_password(self, plaintext):
        if not self._password:
            raise RestException(RestException.LOGIN_FAILURE)
        return bcrypt.check_password_hash(self._password, plaintext)

    def encode_auth_token(self):
        try:
            payload = {
                'exp':
                datetime.datetime.utcnow() +
                datetime.timedelta(hours=2, minutes=0, seconds=0),
                'iat':
                datetime.datetime.utcnow(),
                'sub':
                self.id
            }
            return jwt.encode(payload,
                              app.config.get('SECRET_KEY'),
                              algorithm='HS256')
        except Exception as e:
            return e

    @staticmethod
    def decode_auth_token(auth_token):
        try:
            payload = jwt.decode(auth_token,
                                 app.config.get('SECRET_KEY'),
                                 algorithms='HS256')
            return payload['sub']
        except jwt.ExpiredSignatureError:
            raise RestException(RestException.TOKEN_EXPIRED)
        except jwt.InvalidTokenError:
            raise RestException(RestException.TOKEN_INVALID)

    def get_contact(self):
        for p in self.participants:
            if p.contact:
                return {
                    'name': p.get_name(),
                    'relationship': p.relationship.name,
                    'contact': p.contact
                }
예제 #23
0
class User(db.Model):
    __tablename__ = 'users'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String, unique=True, nullable=False)
    email = db.Column(db.String, unique=True, nullable=False)
    _password = db.Column(db.Binary(60), nullable=False)
    thumbnail = db.Column(db.String, default=None, nullable=True)
    description = db.Column(db.String, default=None, nullable=True)
    authenticated = db.Column(db.Boolean, default=False)
    email_confirmation_sent_on = db.Column(db.DateTime, nullable=True)
    email_confirmed = db.Column(db.Boolean, nullable=True, default=False)
    email_confirmed_on = db.Column(db.DateTime, nullable=True)
    registered_on = db.Column(db.DateTime, nullable=True)
    last_logged_in = db.Column(db.DateTime, nullable=True)
    current_logged_in = db.Column(db.DateTime, nullable=True)
    role = db.Column(db.String, default='user')
    articles = db.relationship('Article', backref='user', lazy='dynamic')
    videos = db.relationship('Video', backref='user', lazy='dynamic')

    def __init__(self, username, email, plaintext_password, email_confirmation_sent_on=None, role='user'):
        self.role = role
        self.username = username
        self.email = email
        self.password = plaintext_password
        self.authenticated = False
        self.email_confirmation_sent_on = email_confirmation_sent_on
        self.email_confirmed = False
        self.email_confirmed_on = None
        self.registered_on = datetime.now()
        self.last_logged_in = None
        self.current_logged_in = datetime.now()
        self.thumbnail = "user-default.png"
        if self.role == "admin":
            self.email_confirmed = True

    @hybrid_property
    def password(self):
        return self._password

    @password.setter
    def set_password(self, plaintext_password):
        self._password = bcrypt.generate_password_hash(plaintext_password)

    @hybrid_method
    def is_correct_password(self, plaintext_password):
        return bcrypt.check_password_hash(self.password, plaintext_password)

    @property
    def is_authenticated(self):
        """Return True if the user is authenticated."""
        return self.authenticated

    @property
    def is_active(self):
        """Always True, as all users are active."""
        return True

    @property
    def is_anonymous(self):
        """Always False, as anonymous users aren't supported."""
        return False

    def get_id(self):
        """Return the email address to satisfy Flask-Login's requirements."""
        """Requires use of Python 3"""
        return str(self.id)

    def set_thumbnail(self, thumbnail):
        self.thumbnail = thumbnail

    def set_description(self, description):
        self.description = description

    def __repr__(self):
        return '<User {0}>'.format(self.name)
예제 #24
0
class Session(db.Model):
    """ API session class. """
    token = db.Column(db.Binary(TOKEN_LEN), primary_key=True)
    user, user_id = foreign_key("User", backref_name="sessions")
예제 #25
0
class User(db.Model):
    __tablename__ = 'user'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String(USERNAME_MAX_LEN), unique=True)
    password_hash = db.Column(db.Binary(60), nullable=False)
    is_employee = db.Column(db.Boolean, nullable=False)
    active = db.Column(db.Boolean, nullable=False)
    banned = db.Column(db.Boolean, default=False)
    last_banning = db.Column(db.DateTime)

    _authenticated = False

    def get_id(self):
        return self.username

    def is_active(self):
        return self.active and self.banned != True

    def is_anonymous(self):
        return False

    def is_authenticated(self):
        return True

    def ban(self):
        self.banned = True
        self.last_banning = datetime.datetime.now()
        db.session.commit()

    def unban(self):
        self.banned = False
        db.session.commit()

    @property
    def client(self):
        if self.is_employee:
            return None
        return Client.query.filter_by(user_id=self.id).first()

    @property
    def employee(self):
        if self.is_employee:
            return Employee.query.filter_by(user_id=self.id).first()
        return None

    def employee_title(self):
        if self.is_employee:
            return Employee.query.filter_by(user_id=self.id).first().title
        return None

    @property
    def feedback_received(self):
        return Feedback.query.filter_by(to_user=self.id).all()

    @property
    def likes(self):
        return [fb for fb in self.feedback_received if fb.is_positive]

    @property
    def dislikes(self):
        return [fb for fb in self.feedback_received if not fb.is_positive]

    @property
    def feedback_left_since_banning(self):
        if self.last_banning is None:
            return Feedback.query.filter_by(from_user=self.id).limit(9).all()
        return Feedback.query.\
               filter(Feedback.from_user==self.id, Feedback.timestamp>self.last_banning).limit(9).all()

    @property
    def feedback_received_since_banning(self):
        if self.last_banning is None:
            return Feedback.query.filter_by(to_user=self.id).all()
        return Feedback.query.\
               filter(Feedback.to_user==self.id, Feedback.timestamp>self.last_banning).all()

    def __repr__(self):
        return '<User %r>' % (self.username)
예제 #26
0
class Users(UserMixin, db.Model):
    """
    Create an Employee table
    """

    # Ensures table will be named in plural and not in singular
    # as is the name of the model
    __tablename__ = 'user'

    user_id = db.Column(db.Integer, primary_key=True,autoincrement=True)
    # username = db.Column(db.String(60), index=True, unique=True)
    first_name = db.Column(db.String(60), index=True,nullable=False)
    last_name = db.Column(db.String(60), index=True)
    email_id = db.Column(db.String(60), index=True, unique=True,nullable=False)
    dob = db.Column(db.Date)
    phone = db.Column(db.Integer, unique=True)
    gender = db.Column(db.Binary(1))
    oauth_id = db.Column(db.String(256), unique = True)
    password_hash = db.Column(db.String(128),nullable=False)
    confirmation_status = db.Column(db.Boolean(1))
    x_auth_token = db.Column(db.String(256),unique=True,nullable=False)
    created_at = db.Column(db.TIMESTAMP,nullable=False);
    # department_id = db.Column(db.Integer, db.ForeignKey('departments.id'))
    # role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))
    # is_admin = db.Column(db.Boolean, default=False)

    @property
    def password(self):
        """
        Prevent pasword from being accessed
        """
        raise AttributeError('password is not a readable attribute.')

    @password.setter
    def password(self, password):
        """
        Set password to a hashed password
        """
        self.password_hash = generate_password_hash(password)

    def verify_password(self, password):
        """
        Check if hashed password matches actual password
        """
        return check_password_hash(self.password_hash, password)

    def __repr__(self):
        return '<User: {}>'.format(self.email_id)

    def encode_auth_token(self, user_id):
        """
        Generates the Auth Token
        :return: string
        """
        try:
            payload = {
                'exp': datetime.datetime.utcnow() + datetime.timedelta(days=100, seconds=0),
                'iat': datetime.datetime.utcnow(),
                'sub': user_id
            }
            return jwt.encode(
                payload,
                app.config.get('KEY'),
                algorithm='HS256'
            )
        except Exception as e:
            return e

    @staticmethod
    def decode_auth_token(auth_token):
        """
        Decodes the auth token
        :param auth_token:
        :return: integer|string
        """
        try:
            payload = jwt.decode(auth_token, app.config.get('SECRET_KEY'))
            return payload['sub']
        except jwt.ExpiredSignatureError:
            return 'Signature expired. Please log in again.'
        except jwt.InvalidTokenError:
            return 'Invalid token. Please log in again.'
예제 #27
0
class User(db.Model):
	__tablename__ = 'users'

	userID = db.Column(db.Integer, primary_key=True)
	id = db.Column(UUID(as_uuid=True), default=lambda: uuid.uuid4(), unique=True)
	username = db.Column(db.String(120), nullable=False, unique=True)
	email = db.Column(db.String)
	authenticated = db.Column(db.Boolean, default=False)
	is_admin = db.Column(db.Boolean, default=True)

	active = db.Column(db.Boolean, default=True)

	_password = db.Column(db.Binary(60), nullable=False)

	settings = db.relationship('UserSettings', backref='User', lazy=False)

	todolists = db.relationship('TodoList', backref='User', lazy=False)
	shoppinglists = db.relationship('ShoppinglistModel', backref='User', lazy=False)

	haushalt_id = db.Column(db.Integer, db.ForeignKey('haushalt.haushaltID'))

	def __init__(self, username, password):
		self.username = username
		self._password = self.hash_password(password).encode('utf-8')
		self.authenticated = False

	@classmethod
	def check_is_admin(cls, identity):
		user = User.find_by_id(identity)
		if not user:
			return {'message': 'No user found'}
		return user.is_admin

	@classmethod
	def change_is_admin(cls, user_id):
		user = User.find_by_id(user_id)
		if not user:
			return { 'message': 'User not found'}, 404
		elif not user.is_admin:
			return {'message': 'You have not the permission to change this'}, 403
		user.is_admin = not user.is_admin
		cls.save()
		return {'message': '{} is now an administrator'.format(user.username)}, 201

	@classmethod
	def change_active(cls, user_id):
		user = User.find_by_id(user_id)
		if not user:
			return { 'message': 'User not found'}, 404
		user.active = not user.active
		cls.save()
		return {'message': '{} changed to {}'.format(user.username, user.active)}, 201


	def hash_password(self, password):
		return bcrypt.hashpw(password, bcrypt.gensalt(12))


	def check_password(self, password, hashed_pw):
		return bcrypt.checkpw(password, hashed_pw)

	@classmethod
	def find_by_id(cls, id):
		return User.query.filter_by(id=(str2uuid(id))).first()

	@classmethod
	def find_by_username(cls, username):
		return User.query.filter_by(username=username).first()

	def save(self):
		db.session.add(self)
		db.session.commit()

	def json(self):
		return {
		'id': str(self.id),
		'username': self.username,
		'settings': [ setting.json() for settion in self.settings ]
		}