auth.py 11KB

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