auth.py 10KB

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