models.py
1.65 KB
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
from pprint import pprint
from flask_login import UserMixin, current_user
from app.models import db
#
# Roles
#
ADMIN = 50
PROJECT = 40
SERVICE = 30
AGENT = 10
PUBLIC = 0
_roleToName = {
ADMIN: 'ADMIN',
PROJECT: 'PROJECT',
SERVICE: 'SERVICE',
AGENT: 'AGENT',
PUBLIC: 'PUBLIC',
}
_nameToRole = {
'ADMIN': ADMIN,
'PROJECT': PROJECT,
'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
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))
role = db.Column(db.Integer, default=0)
def __repr__(self):
return "i: {}, n: {}, e: {}, l: {}".format(self.id, self.name, self.email, self.login)
# Set role at construction time
def __init__(self, **kwargs):
super(User, self).__init__(**kwargs)
self.set_role(kwargs['role'])
def set_role(self, role):
self.role = _checkRole(role)
def has_role(self, role):
role = _checkRole(role)
return self.role == role
def has_role_or_higher(self, role):
role = _checkRole(role)
return self.role and (self.role >= role)