Introduction
In Odoo, user authentication by default checks username and password against the res.users model. However, in some business cases, you may want to apply custom validation rules before allowing a user to log in.
For example:
Block login if the user is linked to an archived Employee.
Block login if the Employee has a custom field login_status = 'disabled'.
This article will show you how to customize the login process in Odoo 16/17 to enforce this logic.
Override route '/web/login'
Create file main.py in folder controller of module and override Home controller
controller/main.py:
# -*- coding: utf-8 -*-
import odoo
import odoo.modules.registry
from odoo.tools.translate import _
from odoo.exceptions import AccessError
from odoo.addons.web.controllers.home import Home, SIGN_UP_REQUEST_PARAMS
from odoo.addons.web.controllers.utils import ensure_db, is_user_internal
from odoo import http
from odoo.http import request
from odoo.exceptions import AccessDenied
from .. import defs
import os
import logging
_logger = logging.getLogger(__name__)
BASE_PATH = os.path.dirname(os.path.dirname(__file__))
class AdminHome(Home):
@http.route('/web/login', type='http', auth="none", csrf=False)
def web_login(self, redirect=None, **kw):
ensure_db()
if request.httprequest.method == 'GET' and redirect and request.session.uid:
return request.redirect(redirect)
# so it is correct if overloaded with auth="public"
if not request.uid:
request.update_env(user=odoo.SUPERUSER_ID)
if request.httprequest.method == 'POST':
try:
uid = request.session.authenticate(request.db, request.params['login'], request.params['password'])
user = request.env['res.users'].with_context(active_test=False).sudo().browse(uid)
employee = request.env['hr.employee'].sudo().search([('user_id', '=', user.id)], limit=1)
if employee and (
(employee.active and employee.login_status == 'disable')
or (not employee.active)
):
request.session.logout()
raise AccessDenied(_("User Blocked: Your account is disabled."))
return request.redirect(self._login_redirect(uid, redirect=redirect))
except odoo.exceptions.AccessDenied as e:
response = request.render('web.login', {
'error': str(e),
'redirect': redirect,
})
else:
response = request.render('web.login', {
'redirect': redirect,
})
response.headers['X-Frame-Options'] = 'SAMEORIGIN'
response.headers['Content-Security-Policy'] = "frame-ancestors 'self'"
return response
Reply