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.

155 lines
6.3 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 openerp import _, http, registry, SUPERUSER_ID
  8. from openerp.api import Environment
  9. from openerp.http import Response, request
  10. from openerp.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. return http.local_redirect(
  46. '/auth_totp/login',
  47. query={
  48. 'mfa_login_token': user.mfa_login_token,
  49. 'redirect': request.params.get('redirect'),
  50. },
  51. keep_hash=True,
  52. )
  53. @http.route('/auth_totp/login', type='http', auth='none', methods=['GET'])
  54. def mfa_login_get(self, *args, **kwargs):
  55. return request.render('auth_totp.mfa_login', qcontext=request.params)
  56. @http.route('/auth_totp/login', type='http', auth='none', methods=['POST'])
  57. def mfa_login_post(self, *args, **kwargs):
  58. """Process MFA login attempt
  59. Overview:
  60. * Try to find a user based on the MFA login token. If this doesn't
  61. work, redirect to the password login page with an error message
  62. * Validate the confirmation code provided by the user. If it's not
  63. valid, redirect to the previous login step with an error message
  64. * Generate a long-term MFA login token for the user and log the
  65. user in using the token
  66. * Build a trusted device cookie and add it to the response if the
  67. trusted device option was checked
  68. * Redirect to the provided URL or to '/web' if one was not given
  69. """
  70. # sudo() is required because there is no request.env.uid (likely since
  71. # there is no user logged in at the start of the request)
  72. user_model_sudo = request.env['res.users'].sudo()
  73. device_model_sudo = user_model_sudo.env['res.users.device']
  74. config_model_sudo = user_model_sudo.env['ir.config_parameter']
  75. token = request.params.get('mfa_login_token')
  76. try:
  77. user = user_model_sudo.user_from_mfa_login_token(token)
  78. except (MfaTokenInvalidError, MfaTokenExpiredError) as exception:
  79. return http.local_redirect(
  80. '/web/login',
  81. query={
  82. 'redirect': request.params.get('redirect'),
  83. 'error': exception.message,
  84. },
  85. keep_hash=True,
  86. )
  87. confirmation_code = request.params.get('confirmation_code')
  88. if not user.validate_mfa_confirmation_code(confirmation_code):
  89. return http.local_redirect(
  90. '/auth_totp/login',
  91. query={
  92. 'redirect': request.params.get('redirect'),
  93. 'error': _(
  94. 'Your confirmation code is not correct. Please try'
  95. ' again.'
  96. ),
  97. 'mfa_login_token': token,
  98. },
  99. keep_hash=True,
  100. )
  101. # These context managers trigger a safe commit, which persists the
  102. # changes right away and is needed for the auth call
  103. with Environment.manage():
  104. with registry(request.db).cursor() as temp_cr:
  105. temp_env = Environment(temp_cr, SUPERUSER_ID, request.context)
  106. temp_user = temp_env['res.users'].browse(user.id)
  107. temp_user.generate_mfa_login_token(60 * 24 * 30)
  108. token = temp_user.mfa_login_token
  109. request.session.authenticate(request.db, user.login, token, user.id)
  110. redirect = request.params.get('redirect')
  111. if not redirect:
  112. redirect = '/web'
  113. response = Response(http.redirect_with_hash(redirect))
  114. if request.params.get('remember_device'):
  115. device = device_model_sudo.create({'user_id': user.id})
  116. secret = config_model_sudo.get_param('database.secret')
  117. device_cookie = JsonSecureCookie({'device_id': device.id}, secret)
  118. cookie_lifetime = timedelta(days=30)
  119. cookie_exp = datetime.utcnow() + cookie_lifetime
  120. device_cookie = device_cookie.serialize(cookie_exp)
  121. cookie_key = 'trusted_devices_%d' % user.id
  122. sec_config = config_model_sudo.get_param('auth_totp.secure_cookie')
  123. security_flag = sec_config != '0'
  124. response.set_cookie(
  125. cookie_key,
  126. device_cookie,
  127. max_age=cookie_lifetime.total_seconds(),
  128. expires=cookie_exp,
  129. httponly=True,
  130. secure=security_flag,
  131. )
  132. return response