core/orm/user.py

59 lines
2.1 KiB
Python
Raw Normal View History

from typing import List
2021-08-19 15:33:39 +00:00
from sqlalchemy import Column, Integer, String, ForeignKey, Boolean, DateTime, JSON as JSONType
2021-08-17 09:14:26 +00:00
from sqlalchemy.orm import relationship
from orm import Permission
2021-08-05 16:49:08 +00:00
from orm.base import Base, local_session
from orm.notification import UserNotification
2021-08-19 15:33:39 +00:00
class UserRating(Base):
__tablename__ = 'user_rating'
createdBy: int = Column(Integer, ForeignKey("user.id"), primary_key = True)
value: int = Column(Integer, nullable=False)
2021-08-17 09:14:26 +00:00
class UserRole(Base):
__tablename__ = 'user_role'
id: int = Column(Integer, primary_key = True)
2021-08-19 15:33:39 +00:00
user_id: int = Column(Integer, ForeignKey("user.id"))
role_id str = Column(String, ForeignKey("role.name"))
2021-08-17 09:14:26 +00:00
class User(Base):
2021-08-05 16:49:08 +00:00
__tablename__ = 'user'
email: str = Column(String, unique=True, nullable=False, comment="Email")
username: str = Column(String, nullable=False, comment="Login")
2021-08-05 16:49:08 +00:00
password: str = Column(String, nullable=True, comment="Password")
bio: str = Column(String, nullable=True, comment="Bio")
userpic: str = Column(String, nullable=True, comment="Userpic")
viewname: str = Column(String, nullable=True, comment="Display name")
rating: int = Column(Integer, nullable=True, comment="Rating")
slug: str = Column(String, unique=True, nullable=True, comment="Slug")
muted: bool = Column(Boolean, default=False)
emailConfirmed: bool = Column(Boolean, default=False)
createdAt: DateTime = Column(DateTime, nullable=False, comment="Created at")
wasOnlineAt: DateTime = Column(DateTime, nullable=False, comment="Was online at")
2021-08-19 15:33:39 +00:00
links: JSONType = Column(JSONType, nullable=True, comment="Links")
oauth: str = Column(String, nullable=True)
2021-08-19 15:33:39 +00:00
notifications = relationship(lambda: UserNotification)
ratings = relationship(lambda: UserRating)
roles = relationship(lambda: UserRole)
2021-08-17 09:14:26 +00:00
2021-08-05 16:49:08 +00:00
@classmethod
def get_permission(cls, user_id):
2021-08-17 09:14:26 +00:00
scope = {}
2021-08-05 16:49:08 +00:00
with local_session() as session:
2021-08-17 09:14:26 +00:00
user = session.query(User).filter(User.id == user_id).first()
for role in user.roles:
for p in role.permissions:
2021-08-18 16:53:55 +00:00
if not p.resource_id in scope:
scope[p.resource_id] = set()
scope[p.resource_id].add(p.operation_id)
2021-08-17 09:14:26 +00:00
return scope
if __name__ == '__main__':
2021-08-05 16:49:08 +00:00
print(User.get_permission(user_id=1))