auth.py 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. # -*- coding: utf-8 -*-
  2. """
  3. Auth* related model.
  4. This is where the models used by the authentication stack are defined.
  5. It's perfectly fine to re-use this definition in the tracim application,
  6. though.
  7. """
  8. import os
  9. import time
  10. import uuid
  11. from datetime import datetime
  12. from hashlib import sha256
  13. from typing import TYPE_CHECKING
  14. from sqlalchemy import Column
  15. from sqlalchemy import ForeignKey
  16. from sqlalchemy import Sequence
  17. from sqlalchemy import Table
  18. from sqlalchemy.ext.hybrid import hybrid_property
  19. from sqlalchemy.orm import relation
  20. from sqlalchemy.orm import relationship
  21. from sqlalchemy.orm import synonym
  22. from sqlalchemy.types import Boolean
  23. from sqlalchemy.types import DateTime
  24. from sqlalchemy.types import Integer
  25. from sqlalchemy.types import Unicode
  26. from tracim_backend.lib.utils.translation import fake_translator as l_
  27. from tracim_backend.models.meta import DeclarativeBase
  28. from tracim_backend.models.meta import metadata
  29. if TYPE_CHECKING:
  30. from tracim_backend.models.data import Workspace
  31. from tracim_backend.models.data import UserRoleInWorkspace
  32. __all__ = ['User', 'Group', 'Permission']
  33. # This is the association table for the many-to-many relationship between
  34. # groups and permissions.
  35. group_permission_table = Table('group_permission', metadata,
  36. Column('group_id', Integer, ForeignKey('groups.group_id',
  37. onupdate="CASCADE", ondelete="CASCADE"), primary_key=True),
  38. Column('permission_id', Integer, ForeignKey('permissions.permission_id',
  39. onupdate="CASCADE", ondelete="CASCADE"), primary_key=True)
  40. )
  41. # This is the association table for the many-to-many relationship between
  42. # groups and members - this is, the memberships.
  43. user_group_table = Table('user_group', metadata,
  44. Column('user_id', Integer, ForeignKey('users.user_id',
  45. onupdate="CASCADE", ondelete="CASCADE"), primary_key=True),
  46. Column('group_id', Integer, ForeignKey('groups.group_id',
  47. onupdate="CASCADE", ondelete="CASCADE"), primary_key=True)
  48. )
  49. class Group(DeclarativeBase):
  50. TIM_NOBODY = 0
  51. TIM_USER = 1
  52. TIM_MANAGER = 2
  53. TIM_ADMIN = 3
  54. TIM_NOBODY_GROUPNAME = 'nobody'
  55. TIM_USER_GROUPNAME = 'users'
  56. TIM_MANAGER_GROUPNAME = 'managers'
  57. TIM_ADMIN_GROUPNAME = 'administrators'
  58. __tablename__ = 'groups'
  59. group_id = Column(Integer, Sequence('seq__groups__group_id'), autoincrement=True, primary_key=True)
  60. group_name = Column(Unicode(16), unique=True, nullable=False)
  61. display_name = Column(Unicode(255))
  62. created = Column(DateTime, default=datetime.utcnow)
  63. users = relationship('User', secondary=user_group_table, backref='groups')
  64. def __repr__(self):
  65. return '<Group: name=%s>' % repr(self.group_name)
  66. def __unicode__(self):
  67. return self.group_name
  68. @classmethod
  69. def by_group_name(cls, group_name, dbsession):
  70. """Return the user object whose email address is ``email``."""
  71. return dbsession.query(cls).filter_by(group_name=group_name).first()
  72. class Profile(object):
  73. """This model is the "max" group associated to a given user."""
  74. _NAME = [
  75. Group.TIM_NOBODY_GROUPNAME,
  76. Group.TIM_USER_GROUPNAME,
  77. Group.TIM_MANAGER_GROUPNAME,
  78. Group.TIM_ADMIN_GROUPNAME,
  79. ]
  80. _IDS = [
  81. Group.TIM_NOBODY,
  82. Group.TIM_USER,
  83. Group.TIM_MANAGER,
  84. Group.TIM_ADMIN,
  85. ]
  86. # TODO - G.M - 18-04-2018 [Cleanup] Drop this
  87. # _LABEL = [l_('Nobody'),
  88. # l_('Users'),
  89. # l_('Global managers'),
  90. # l_('Administrators')]
  91. def __init__(self, profile_id):
  92. assert isinstance(profile_id, int)
  93. self.id = profile_id
  94. self.name = Profile._NAME[profile_id]
  95. # TODO - G.M - 18-04-2018 [Cleanup] Drop this
  96. # self.label = Profile._LABEL[profile_id]
  97. class User(DeclarativeBase):
  98. """
  99. User definition.
  100. This is the user definition used by :mod:`repoze.who`, which requires at
  101. least the ``email`` column.
  102. """
  103. __tablename__ = 'users'
  104. user_id = Column(Integer, Sequence('seq__users__user_id'), autoincrement=True, primary_key=True)
  105. email = Column(Unicode(255), unique=True, nullable=False)
  106. display_name = Column(Unicode(255))
  107. _password = Column('password', Unicode(128))
  108. created = Column(DateTime, default=datetime.utcnow)
  109. is_active = Column(Boolean, default=True, nullable=False)
  110. imported_from = Column(Unicode(32), nullable=True)
  111. timezone = Column(Unicode(255), nullable=False, server_default='')
  112. # TODO - G.M - 04-04-2018 - [auth] Check if this is already needed
  113. # with new auth system
  114. auth_token = Column(Unicode(255))
  115. auth_token_created = Column(DateTime)
  116. @hybrid_property
  117. def email_address(self):
  118. return self.email
  119. def __repr__(self):
  120. return '<User: email=%s, display=%s>' % (
  121. repr(self.email), repr(self.display_name))
  122. def __unicode__(self):
  123. return self.display_name or self.email
  124. @property
  125. def permissions(self):
  126. """Return a set with all permissions granted to the user."""
  127. perms = set()
  128. for g in self.groups:
  129. perms = perms | set(g.permissions)
  130. return perms
  131. @property
  132. def profile(self) -> Profile:
  133. profile_id = 0
  134. if len(self.groups) > 0:
  135. profile_id = max(group.group_id for group in self.groups)
  136. return Profile(profile_id)
  137. # TODO - G-M - 20-04-2018 - [Calendar] Replace this in context model object
  138. # @property
  139. # def calendar_url(self) -> str:
  140. # # TODO - 20160531 - Bastien: Cyclic import if import in top of file
  141. # from tracim.lib.calendar import CalendarManager
  142. # calendar_manager = CalendarManager(None)
  143. #
  144. # return calendar_manager.get_user_calendar_url(self.user_id)
  145. @classmethod
  146. def by_email_address(cls, email, dbsession):
  147. """Return the user object whose email address is ``email``."""
  148. return dbsession.query(cls).filter_by(email=email).first()
  149. @classmethod
  150. def by_user_name(cls, username, dbsession):
  151. """Return the user object whose user name is ``username``."""
  152. return dbsession.query(cls).filter_by(email=username).first()
  153. @classmethod
  154. def _hash_password(cls, cleartext_password: str) -> str:
  155. salt = sha256()
  156. salt.update(os.urandom(60))
  157. salt = salt.hexdigest()
  158. hash = sha256()
  159. # Make sure password is a str because we cannot hash unicode objects
  160. hash.update((cleartext_password + salt).encode('utf-8'))
  161. hash = hash.hexdigest()
  162. ciphertext_password = salt + hash
  163. # Make sure the hashed password is a unicode object at the end of the
  164. # process because SQLAlchemy _wants_ unicode objects for Unicode cols
  165. # FIXME - D.A. - 2013-11-20 - The following line has been removed since using python3. Is this normal ?!
  166. # password = password.decode('utf-8')
  167. return ciphertext_password
  168. def _set_password(self, cleartext_password: str) -> None:
  169. """
  170. Set ciphertext password from cleartext password.
  171. Hash cleartext password on the fly,
  172. Store its ciphertext version,
  173. """
  174. self._password = self._hash_password(cleartext_password)
  175. def _get_password(self) -> str:
  176. """Return the hashed version of the password."""
  177. return self._password
  178. password = synonym('_password', descriptor=property(_get_password,
  179. _set_password))
  180. def validate_password(self, cleartext_password: str) -> bool:
  181. """
  182. Check the password against existing credentials.
  183. :param cleartext_password: the password that was provided by the user
  184. to try and authenticate. This is the clear text version that we
  185. will need to match against the hashed one in the database.
  186. :type cleartext_password: unicode object.
  187. :return: Whether the password is valid.
  188. :rtype: bool
  189. """
  190. result = False
  191. if self.password:
  192. hash = sha256()
  193. hash.update((cleartext_password + self.password[:64]).encode('utf-8'))
  194. result = self.password[64:] == hash.hexdigest()
  195. return result
  196. def get_display_name(self, remove_email_part: bool=False) -> str:
  197. """
  198. Get a name to display from corresponding member or email.
  199. :param remove_email_part: If True and display name based on email,
  200. remove @xxx.xxx part of email in returned value
  201. :return: display name based on user name or email.
  202. """
  203. if self.display_name:
  204. return self.display_name
  205. else:
  206. if remove_email_part:
  207. at_pos = self.email.index('@')
  208. return self.email[0:at_pos]
  209. return self.email
  210. def get_role(self, workspace: 'Workspace') -> int:
  211. for role in self.roles:
  212. if role.workspace == workspace:
  213. return role.role
  214. return UserRoleInWorkspace.NOT_APPLICABLE
  215. def get_active_roles(self) -> ['UserRoleInWorkspace']:
  216. """
  217. :return: list of roles of the user for all not-deleted workspaces
  218. """
  219. roles = []
  220. for role in self.roles:
  221. if not role.workspace.is_deleted:
  222. roles.append(role)
  223. return roles
  224. # TODO - G.M - 04-04-2018 - [auth] Check if this is already needed
  225. # with new auth system
  226. def ensure_auth_token(self, validity_seconds, session) -> None:
  227. """
  228. Create auth_token if None, regenerate auth_token if too much old.
  229. auth_token validity is set in
  230. :return:
  231. """
  232. if not self.auth_token or not self.auth_token_created:
  233. self.auth_token = str(uuid.uuid4())
  234. self.auth_token_created = datetime.utcnow()
  235. session.flush()
  236. return
  237. now_seconds = time.mktime(datetime.utcnow().timetuple())
  238. auth_token_seconds = time.mktime(self.auth_token_created.timetuple())
  239. difference = now_seconds - auth_token_seconds
  240. if difference > validity_seconds:
  241. self.auth_token = str(uuid.uuid4())
  242. self.auth_token_created = datetime.utcnow()
  243. session.flush()
  244. class Permission(DeclarativeBase):
  245. """
  246. Permission definition.
  247. Only the ``permission_name`` column is required.
  248. """
  249. __tablename__ = 'permissions'
  250. permission_id = Column(
  251. Integer,
  252. Sequence('seq__permissions__permission_id'),
  253. autoincrement=True,
  254. primary_key=True
  255. )
  256. permission_name = Column(Unicode(63), unique=True, nullable=False)
  257. description = Column(Unicode(255))
  258. groups = relation(Group, secondary=group_permission_table,
  259. backref='permissions')
  260. def __repr__(self):
  261. return '<Permission: name=%s>' % repr(self.permission_name)
  262. def __unicode__(self):
  263. return self.permission_name