-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgris.py
178 lines (140 loc) · 6.11 KB
/
gris.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
"""PC est magique Flask App - Admin Pages Models"""
from __future__ import annotations
import datetime
import typing
from dateutil import relativedelta
import sqlalchemy as sa
from app import db
from app.enums import PermissionType, PermissionScope
from app.utils.columns import (
column,
many_to_many,
many_to_one,
my_enum,
Column,
Relationship,
)
Model = typing.cast(type[type], db.Model) # type checking hack
Enum = my_enum # type checking hack
# Association tables
class _PCeen_Role_AT(Model):
__tablename__ = "_pceen_role_at"
_pceen_id: Column[int] = column(sa.ForeignKey("pceen.id"), primary_key=True)
_role_id: Column[int] = column(sa.ForeignKey("role.id"), primary_key=True)
class _Role_Permission_AT(Model):
__tablename__ = "_role_permission_at"
_role_id: Column[int] = column(sa.ForeignKey("role.id"), primary_key=True)
_permission_id: Column[int] = column(sa.ForeignKey("permission.id"), primary_key=True)
class Role(Model):
"""A role a PCeen can have."""
id: Column[int] = column(sa.Integer(), primary_key=True)
name: Column[str] = column(sa.String(64), nullable=False)
index: Column[int] = column(sa.Integer(), nullable=False, default=1000)
color: Column[str] = column(sa.String(6), nullable=True)
pceens: Relationship[list[models.PCeen]] = many_to_many("PCeen.roles", secondary=_PCeen_Role_AT)
permissions: Relationship[list[Permission]] = many_to_many("Permission.roles", secondary=_Role_Permission_AT)
def __repr__(self) -> str:
"""Returns repr(self)."""
return f"<Role #{self.id} ({self.name})>"
def __str__(self) -> str:
"""Human-readible description of the role."""
return self.name
@property
def is_dark_colored(self) -> bool:
"""Whether the role color is dark-themed.
Adapted from https://stackoverflow.com/a/58270890.
"""
if not self.color:
return False
try:
red = int(self.color[:2], 16)
green = int(self.color[2:4], 16)
blue = int(self.color[4:], 16)
except ValueError:
return False
hsp_2 = (0.299 * red ** 2) + (0.587 * green ** 2) + (0.114 * blue ** 2)
return hsp_2 < 19500
class Permission(Model):
"""A permission a role can have."""
id: Column[int] = column(sa.Integer(), primary_key=True)
type: Column[PermissionType] = column(my_enum(PermissionType), nullable=False)
scope: Column[PermissionScope] = column(my_enum(PermissionScope), nullable=False)
ref_id: Column[int] = column(sa.Integer(), nullable=True)
roles: Relationship[list[Role]] = many_to_many("Role.permissions", secondary=_Role_Permission_AT)
def __repr__(self) -> str:
"""Returns repr(self)."""
try:
ref = self.ref or "<all>"
except ValueError:
ref = f"[#{self.ref_id}]"
return f"<Permission #{self.id} ({self.type.name} / " f"{self.scope.name}:{ref})>"
@property
def ref(self) -> Model | None:
"""Database entry this permission refer to, or ``None`` if global.
Raises :exc:`ValueError` if this permission refer to non-existing
item.
"""
if not self.scope.allow_elem or not self.ref_id:
return None
item = self.scope.query(models).get(self.ref_id)
if not item:
raise ValueError(f"Permission {self.id} refer to non-existing {self.scope}")
return item
def __str__(self) -> str:
"""A human-readible description of this permission."""
if not self.scope.allow_elem:
return f"{self.type.name} / {self.scope.name}"
if self.ref_id is None:
return f"{self.type.name} / every {self.scope.name}"
try:
return f'{self.type.name} / {self.scope.name} "{self.ref}"'
except ValueError:
return f"{self.type.name} / [OLD {self.scope.name} #{self.ref_id}]"
def grants_for(self, type: PermissionType, scope: PermissionScope, elem: Model = None) -> bool:
"""Check whether this permission grants given type and scope.
Args:
type: The permission type (.read, .write...).
scope: The permission scope (.pceen, .album...).
elem: The database entry to check the permission for, if
applicable.
Returns:
If the permission is granted.
"""
return (
self.scope == scope
and ((self.type == type) or (self.type == PermissionType.all))
and ((self.ref_id is None) or (self.ref == elem))
)
@classmethod
def get_or_create(cls, type_: PermissionType, scope: PermissionScope, ref_id: int | None = None) -> Permission:
perm = cls.query.filter_by(scope=scope, type=type_, ref_id=ref_id).first()
if not perm:
perm = cls(scope=scope, type=type_, ref_id=ref_id)
db.session.add(perm)
db.session.commit
return perm
class Ban(Model):
"""A ban of a PCeen from accessing the Internet."""
id: Column[int] = column(sa.Integer(), primary_key=True)
_pceen_id: Column[int] = column(sa.ForeignKey("pceen.id"), nullable=False)
pceen: Relationship[models.PCeen] = many_to_one("PCeen.bans")
start: Column[datetime.datetime] = column(sa.DateTime(), nullable=False)
end: Column[datetime.datetime | None] = column(sa.DateTime(), nullable=True)
reason: Column[str] = column(sa.String(32), nullable=False)
message: Column[str | None] = column(sa.String(2000), nullable=True)
def __repr__(self) -> str:
"""Returns repr(self)."""
return f"<Ban #{self.id} of {self.pceen} (-> {self.end})>"
@property
def duration(self) -> relativedelta.relativedelta | None:
"""Relative delta ``end - start``, or ``None`` if no end."""
if self.end:
return relativedelta.relativedelta(self.end, self.start)
else:
return None
@property
def is_active(self) -> bool:
"""Whether the ban is currently active."""
now = datetime.datetime.utcnow()
return (self.start <= now) and ((not self.end) or now < self.end)
from app import models