auth.py 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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.lib.utils import lazy_ugettext as l_
  28. from tracim.model import DBSession
  29. from tracim.model import DeclarativeBase
  30. from tracim.model import metadata
  31. if TYPE_CHECKING:
  32. from tracim.model.data import Workspace
  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):
  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. @property
  127. def calendar_url(self) -> str:
  128. # TODO - 20160531 - Bastien: Cyclic import if import in top of file
  129. from tracim.lib.calendar import CalendarManager
  130. calendar_manager = CalendarManager(None)
  131. return calendar_manager.get_user_calendar_url(self.user_id)
  132. @classmethod
  133. def by_email_address(cls, email):
  134. """Return the user object whose email address is ``email``."""
  135. return DBSession.query(cls).filter_by(email=email).first()
  136. @classmethod
  137. def by_user_name(cls, username):
  138. """Return the user object whose user name is ``username``."""
  139. return DBSession.query(cls).filter_by(email=username).first()
  140. @classmethod
  141. def _hash_password(cls, cleartext_password: str) -> str:
  142. salt = sha256()
  143. salt.update(os.urandom(60))
  144. salt = salt.hexdigest()
  145. hash = sha256()
  146. # Make sure password is a str because we cannot hash unicode objects
  147. hash.update((cleartext_password + salt).encode('utf-8'))
  148. hash = hash.hexdigest()
  149. ciphertext_password = salt + hash
  150. # Make sure the hashed password is a unicode object at the end of the
  151. # process because SQLAlchemy _wants_ unicode objects for Unicode cols
  152. # FIXME - D.A. - 2013-11-20 - The following line has been removed since using python3. Is this normal ?!
  153. # password = password.decode('utf-8')
  154. return ciphertext_password
  155. def _set_password(self, cleartext_password: str) -> None:
  156. """
  157. Set ciphertext password from cleartext password.
  158. Hash cleartext password on the fly,
  159. Store its ciphertext version,
  160. """
  161. self._password = self._hash_password(cleartext_password)
  162. def _get_password(self) -> str:
  163. """Return the hashed version of the password."""
  164. return self._password
  165. password = synonym('_password', descriptor=property(_get_password,
  166. _set_password))
  167. def validate_password(self, cleartext_password: str) -> bool:
  168. """
  169. Check the password against existing credentials.
  170. :param cleartext_password: the password that was provided by the user
  171. to try and authenticate. This is the clear text version that we
  172. will need to match against the hashed one in the database.
  173. :type cleartext_password: unicode object.
  174. :return: Whether the password is valid.
  175. :rtype: bool
  176. """
  177. result = False
  178. if self.password:
  179. hash = sha256()
  180. hash.update((cleartext_password + self.password[:64]).encode('utf-8'))
  181. result = self.password[64:] == hash.hexdigest()
  182. return result
  183. def get_display_name(self, remove_email_part: bool=False) -> str:
  184. """
  185. Get a name to display from corresponding member or email.
  186. :param remove_email_part: If True and display name based on email,
  187. remove @xxx.xxx part of email in returned value
  188. :return: display name based on user name or email.
  189. """
  190. if self.display_name:
  191. return self.display_name
  192. else:
  193. if remove_email_part:
  194. at_pos = self.email.index('@')
  195. return self.email[0:at_pos]
  196. return self.email
  197. def get_role(self, workspace: 'Workspace') -> int:
  198. for role in self.roles:
  199. if role.workspace == workspace:
  200. return role.role
  201. from tracim.model.data import UserRoleInWorkspace
  202. return UserRoleInWorkspace.NOT_APPLICABLE
  203. def get_active_roles(self) -> ['UserRoleInWorkspace']:
  204. """
  205. :return: list of roles of the user for all not-deleted workspaces
  206. """
  207. roles = []
  208. for role in self.roles:
  209. if not role.workspace.is_deleted:
  210. roles.append(role)
  211. return roles
  212. def ensure_auth_token(self) -> None:
  213. """
  214. Create auth_token if None, regenerate auth_token if too much old.
  215. auth_token validity is set in
  216. :return:
  217. """
  218. from tracim.config.app_cfg import CFG
  219. validity_seconds = CFG.get_instance().USER_AUTH_TOKEN_VALIDITY
  220. if not self.auth_token or not self.auth_token_created:
  221. self.auth_token = str(uuid.uuid4())
  222. self.auth_token_created = datetime.utcnow()
  223. DBSession.flush()
  224. return
  225. now_seconds = time.mktime(datetime.utcnow().timetuple())
  226. auth_token_seconds = time.mktime(self.auth_token_created.timetuple())
  227. difference = now_seconds - auth_token_seconds
  228. if difference > validity_seconds:
  229. self.auth_token = str(uuid.uuid4())
  230. self.auth_token_created = datetime.utcnow()
  231. DBSession.flush()
  232. class Permission(DeclarativeBase):
  233. """
  234. Permission definition.
  235. Only the ``permission_name`` column is required.
  236. """
  237. __tablename__ = 'permissions'
  238. permission_id = Column(Integer, Sequence('seq__permissions__permission_id'), autoincrement=True, primary_key=True)
  239. permission_name = Column(Unicode(63), unique=True, nullable=False)
  240. description = Column(Unicode(255))
  241. groups = relation(Group, secondary=group_permission_table,
  242. backref='permissions')
  243. def __repr__(self):
  244. return '<Permission: name=%s>' % repr(self.permission_name)
  245. def __unicode__(self):
  246. return self.permission_name