Blame view

app/auth/models.py 1.65 KB
42c07429   hitier   Default role valu...
1
2
3
from pprint import pprint

from flask_login import UserMixin, current_user
a5a365e8   hitier   Move User model t...
4
5
from app.models import db

7b74daf6   hitier   New User role man...
6
7
8
9
#
# Roles
#

42c07429   hitier   Default role valu...
10
11
ADMIN = 50
PROJECT = 40
7b74daf6   hitier   New User role man...
12
13
14
15
16
17
SERVICE = 30
AGENT = 10
PUBLIC = 0

_roleToName = {
    ADMIN: 'ADMIN',
42c07429   hitier   Default role valu...
18
    PROJECT: 'PROJECT',
7b74daf6   hitier   New User role man...
19
20
21
22
23
24
    SERVICE: 'SERVICE',
    AGENT: 'AGENT',
    PUBLIC: 'PUBLIC',
}
_nameToRole = {
    'ADMIN': ADMIN,
42c07429   hitier   Default role valu...
25
    'PROJECT': PROJECT,
7b74daf6   hitier   New User role man...
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
    'SERVICE': SERVICE,
    'AGENT': AGENT,
    'PUBLIC': PUBLIC,
}


def _checkRole(role):
    if isinstance(role, int):
        rv = role
    elif str(role) == role:
        role = role.upper()
        if role not in _nameToRole:
            raise ValueError("Unknown role: %r" % role)
        rv = _nameToRole[role]
    else:
        raise TypeError("Role not an integer or a valid string: %r" % role)
    return rv

a5a365e8   hitier   Move User model t...
44
45
46
47
48
49
50

class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)  # primary keys are required by SQLAlchemy
    email = db.Column(db.String(100), unique=True)
    name = db.Column(db.String(100))
    login = db.Column(db.String(100), unique=True)
    password = db.Column(db.String(100))
42c07429   hitier   Default role valu...
51
    role = db.Column(db.Integer, default=0)
a5a365e8   hitier   Move User model t...
52
53
54
55

    def __repr__(self):
        return "i: {}, n: {}, e: {}, l: {}".format(self.id, self.name, self.email, self.login)

42c07429   hitier   Default role valu...
56
57
58
59
60
61
    # Set role at construction time
    def __init__(self, **kwargs):
        super(User, self).__init__(**kwargs)
        self.set_role(kwargs['role'])

    def set_role(self, role):
7b74daf6   hitier   New User role man...
62
63
        self.role = _checkRole(role)

42c07429   hitier   Default role valu...
64
65
66
67
68
    def has_role(self, role):
        role = _checkRole(role)
        return self.role == role

    def has_role_or_higher(self, role):
7b74daf6   hitier   New User role man...
69
        role = _checkRole(role)
42c07429   hitier   Default role valu...
70
        return self.role and (self.role >= role)