auth.py 10KB

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