Commit 57f8e9b6 authored by Daniele Venzano's avatar Daniele Venzano

LDAP with SASL authentication and change authentication system to use cookies and a login page

Merge from Quang-Nhat Hoang-Xuan private tree
parent 31799d3f
# Copyright (c) 2016, Quang-Nhat Hoang-Xuan
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""LDAP authentication module."""
import logging
import ldap
import ldap.sasl
except ImportError:
ldap = None
import zoe_api.auth.base
import zoe_api.exceptions
from zoe_lib.config import get_conf
log = logging.getLogger(__name__)
class LDAPSASLAuthenticator(zoe_api.auth.base.BaseAuthenticator):
"""A simple LDAP authenticator."""
def __init__(self):
self.connection = ldap.initialize(get_conf().ldap_server_uri)
self.base_dn = get_conf().ldap_base_dn
self.connection.protocol_version = ldap.VERSION3
self.sasl_auth = ldap.sasl.sasl({}, 'GSSAPI')
def auth(self, username, password):
"""Authenticate the user or raise an exception."""
search_filter = "uid=" + username
uid = None
role = 'guest'
self.connection.sasl_interactive_bind_s('', self.sasl_auth)
result = self.connection.search_s(self.base_dn, ldap.SCOPE_SUBTREE, search_filter)
if len(result) == 0:
raise zoe_api.exceptions.ZoeAuthException('Unknown user or wrong password.')
user_dict = result[0][1]
uid = username
gid_numbers = [int(x) for x in user_dict['gidNumber']]
if get_conf().ldap_admin_gid in gid_numbers:
role = 'admin'
elif get_conf().ldap_user_gid in gid_numbers:
role = 'user'
elif get_conf().ldap_guest_gid in gid_numbers:
role = 'guest'
log.warning('User {} has an unknown group ID ({}), using guest role'.format(username, result[0][1]['gidNumber']))
role = 'guest'
except ldap.LDAPError as ex:
if ex.args[0]['desc'] == 'Invalid credentials':
raise zoe_api.exceptions.ZoeAuthException('Unknown user or wrong password.')
log.exception("LDAP exception")
zoe_api.exceptions.ZoeAuthException('LDAP error.')
return uid, role
......@@ -19,7 +19,7 @@ from random import randint
import json
from zoe_api.api_endpoint import APIEndpoint # pylint: disable=unused-import
from zoe_api.web.utils import get_auth, catch_exceptions
from zoe_api.web.utils import get_auth_login, get_auth, catch_exceptions
from zoe_api.web.custom_request_handler import ZoeRequestHandler
......@@ -36,6 +36,31 @@ class RootWeb(ZoeRequestHandler):
class LoginWeb(ZoeRequestHandler):
"""The login web page."""
def initialize(self, **kwargs):
"""Initializes the request handler."""
self.api_endpoint = kwargs['api_endpoint'] # type: APIEndpoint
def get(self):
"""Login page."""
def post(self):
"""Try to authenticate."""
username = self.get_argument("username", "")
password = self.get_argument("password", "")
uid, role = get_auth_login(username, password)
if not self.get_secure_cookie('zoe'):
cookie_val = uid + '.' + role
self.set_secure_cookie('zoe', cookie_val)
self.redirect(self.get_argument("next", u"/user"))
class HomeWeb(ZoeRequestHandler):
"""Handler class"""
def initialize(self, **kwargs):
<div id="main-container">
<div id="main">
<img alt="zoe dummy login page" src="{{ static_url("img/logo.png") }}">
<div id="login-form">
<form action="/login" method="post" id="login_form">
<label for="username">Username</label>
<input autocapitalize="off" autocorrect="off" class="text-input" id="username" name="username" tabindex="1" type="text" value="">
<label for="password">Password</label>
<input class="text-input" id="password" name="password" tabindex="2" type="password" value="">
<span class="errormessage">{{errormessage}}</span>
<div id="form_btn">
<input id="signin-btn" class="btn btn-blue" type="submit" value="Sign In" tabindex="3">
......@@ -15,13 +15,13 @@
"""Functions needed by the Zoe web interface."""
import base64
import logging
from zoe_lib.config import get_conf
from zoe_api.auth.base import BaseAuthenticator # pylint: disable=unused-import
from zoe_api.auth.ldap import LDAPAuthenticator
from zoe_api.auth.ldapsasl import LDAPSASLAuthenticator
from zoe_api.auth.file import PlainTextAuthenticator
import zoe_api.exceptions
from zoe_api.web.custom_request_handler import ZoeRequestHandler
......@@ -54,26 +54,18 @@ def catch_exceptions(func):
def missing_auth(handler: ZoeRequestHandler):
"""Sends a 401 response that enables basic auth"""
handler.set_status(401, 'Could not verify your access level for that URL. You have to login with proper credentials.')
handler.set_header('WWW-Authenticate', 'Basic realm="Login Required"')
"""Redirect to login page."""
handler.redirect(handler.get_argument('next', u'/login'))
def get_auth(handler: ZoeRequestHandler):
"""Try to authenticate a request."""
auth_header = handler.request.headers.get('Authorization')
if auth_header is None or not auth_header.startswith('Basic '):
raise zoe_api.exceptions.ZoeAuthException
auth_decoded = base64.decodebytes(bytes(auth_header[6:], 'ascii')).decode('utf-8')
username, password = auth_decoded.split(':', 2)
def get_auth_login(username, password):
"""Authenticate username and password against the configured user store."""
if get_conf().auth_type == 'text':
authenticator = PlainTextAuthenticator() # type: BaseAuthenticator
elif get_conf().auth_type == 'ldap':
authenticator = LDAPAuthenticator()
authenticator = LDAPAuthenticator() # type: BaseAuthenticator
elif get_conf().auth_type == 'ldapsasl':
authenticator = LDAPSASLAuthenticator() # type: BaseAuthenticator
raise zoe_api.exceptions.ZoeException('Configuration error, unknown authentication method: {}'.format(get_conf().auth_type))
uid, role = authenticator.auth(username, password)
......@@ -83,6 +75,18 @@ def get_auth(handler: ZoeRequestHandler):
return uid, role
def get_auth(handler: ZoeRequestHandler):
"""Try to authenticate a request."""
if handler.get_secure_cookie('zoe'):
cookie_val = str(handler.get_secure_cookie('zoe'))
uid, role = cookie_val[2:-1].split('.')'Authentication done using cookie')
return uid, role
handler.redirect(handler.get_argument('next', u'/login'))
def error_page(handler: ZoeRequestHandler, error_message: str, status: int):
"""Generate an error page."""
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment