You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

163 lines
6.5 KiB

  1. # -*- coding: utf-8 -*-
  2. # Copyright 2016-2017 LasLabs Inc.
  3. # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html).
  4. from datetime import datetime, timedelta
  5. import json
  6. from werkzeug.contrib.securecookie import SecureCookie
  7. from odoo import _, http, registry, SUPERUSER_ID
  8. from odoo.api import Environment
  9. from odoo.http import Response, request
  10. from odoo.addons.web.controllers.main import Home
  11. from ..exceptions import MfaTokenInvalidError, MfaTokenExpiredError
  12. class JsonSecureCookie(SecureCookie):
  13. serialization_method = json
  14. class AuthTotp(Home):
  15. @http.route()
  16. def web_login(self, *args, **kwargs):
  17. """Add MFA logic to the web_login action in Home
  18. Overview:
  19. * Call web_login in Home
  20. * Return the result of that call if the user has not logged in yet
  21. using a password, does not have MFA enabled, or has a valid
  22. trusted device cookie
  23. * If none of these is true, generate a new MFA login token for the
  24. user, log the user out, and redirect to the MFA login form
  25. """
  26. # sudo() is required because there may be no request.env.uid (likely
  27. # since there may be no user logged in at the start of the request)
  28. user_model_sudo = request.env['res.users'].sudo()
  29. config_model_sudo = user_model_sudo.env['ir.config_parameter']
  30. response = super(AuthTotp, self).web_login(*args, **kwargs)
  31. if not request.params.get('login_success'):
  32. return response
  33. user = user_model_sudo.browse(request.uid)
  34. if not user.mfa_enabled:
  35. return response
  36. cookie_key = 'trusted_devices_%d' % user.id
  37. device_cookie = request.httprequest.cookies.get(cookie_key)
  38. if device_cookie:
  39. secret = config_model_sudo.get_param('database.secret')
  40. device_cookie = JsonSecureCookie.unserialize(device_cookie, secret)
  41. if device_cookie.get('device_id') in user.trusted_device_ids.ids:
  42. return response
  43. user.generate_mfa_login_token()
  44. request.session.logout(keep_db=True)
  45. request.params['login_success'] = False
  46. return http.local_redirect(
  47. '/auth_totp/login',
  48. query={
  49. 'mfa_login_token': user.mfa_login_token,
  50. 'redirect': request.params.get('redirect'),
  51. },
  52. keep_hash=True,
  53. )
  54. @http.route(
  55. '/auth_totp/login',
  56. type='http',
  57. auth='public',
  58. methods=['GET'],
  59. website=True,
  60. )
  61. def mfa_login_get(self, *args, **kwargs):
  62. return request.render('auth_totp.mfa_login', qcontext=request.params)
  63. @http.route('/auth_totp/login', type='http', auth='none', methods=['POST'])
  64. def mfa_login_post(self, *args, **kwargs):
  65. """Process MFA login attempt
  66. Overview:
  67. * Try to find a user based on the MFA login token. If this doesn't
  68. work, redirect to the password login page with an error message
  69. * Validate the confirmation code provided by the user. If it's not
  70. valid, redirect to the previous login step with an error message
  71. * Generate a long-term MFA login token for the user and log the
  72. user in using the token
  73. * Build a trusted device cookie and add it to the response if the
  74. trusted device option was checked
  75. * Redirect to the provided URL or to '/web' if one was not given
  76. """
  77. # sudo() is required because there is no request.env.uid (likely since
  78. # there is no user logged in at the start of the request)
  79. user_model_sudo = request.env['res.users'].sudo()
  80. device_model_sudo = user_model_sudo.env['res.users.device']
  81. config_model_sudo = user_model_sudo.env['ir.config_parameter']
  82. token = request.params.get('mfa_login_token')
  83. try:
  84. user = user_model_sudo.user_from_mfa_login_token(token)
  85. except (MfaTokenInvalidError, MfaTokenExpiredError) as exception:
  86. return http.local_redirect(
  87. '/web/login',
  88. query={
  89. 'redirect': request.params.get('redirect'),
  90. 'error': exception.message,
  91. },
  92. keep_hash=True,
  93. )
  94. confirmation_code = request.params.get('confirmation_code')
  95. if not user.validate_mfa_confirmation_code(confirmation_code):
  96. return http.local_redirect(
  97. '/auth_totp/login',
  98. query={
  99. 'redirect': request.params.get('redirect'),
  100. 'error': _(
  101. 'Your confirmation code is not correct. Please try'
  102. ' again.'
  103. ),
  104. 'mfa_login_token': token,
  105. },
  106. keep_hash=True,
  107. )
  108. # These context managers trigger a safe commit, which persists the
  109. # changes right away and is needed for the auth call
  110. with Environment.manage():
  111. with registry(request.db).cursor() as temp_cr:
  112. temp_env = Environment(temp_cr, SUPERUSER_ID, request.context)
  113. temp_user = temp_env['res.users'].browse(user.id)
  114. temp_user.generate_mfa_login_token(60 * 24 * 30)
  115. token = temp_user.mfa_login_token
  116. request.session.authenticate(request.db, user.login, token, user.id)
  117. request.params['login_success'] = True
  118. redirect = request.params.get('redirect')
  119. if not redirect:
  120. redirect = '/web'
  121. response = Response(http.redirect_with_hash(redirect))
  122. if request.params.get('remember_device'):
  123. device = device_model_sudo.create({'user_id': user.id})
  124. secret = config_model_sudo.get_param('database.secret')
  125. device_cookie = JsonSecureCookie({'device_id': device.id}, secret)
  126. cookie_lifetime = timedelta(days=30)
  127. cookie_exp = datetime.utcnow() + cookie_lifetime
  128. device_cookie = device_cookie.serialize(cookie_exp)
  129. cookie_key = 'trusted_devices_%d' % user.id
  130. sec_config = config_model_sudo.get_param('auth_totp.secure_cookie')
  131. security_flag = sec_config != '0'
  132. response.set_cookie(
  133. cookie_key,
  134. device_cookie,
  135. max_age=cookie_lifetime.total_seconds(),
  136. expires=cookie_exp,
  137. httponly=True,
  138. secure=security_flag,
  139. )
  140. return response