<commit_before>#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2005-2009 University of Deusto
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
#
# This software consists of contributions made by many individuals, 
# listed below:
#
# Author: <NAME> <<EMAIL>>
# 
import voodoo.log as log
from voodoo.log import logged
import voodoo.LogLevel as LogLevel
import time

import weblab.login.LoginAuth as LoginAuth
import weblab.login.DelegatedLoginAuth as DelegatedLoginAuth
import weblab.login.database.DatabaseManager as DatabaseManager
import weblab.login.facade.LoginFacadeServer as LoginFacadeServer
import weblab.data.ServerType as ServerType
import weblab.exceptions.login.LoginExceptions as LoginExceptions
import weblab.exceptions.database.DatabaseExceptions as DbExceptions
import weblab.database.DatabaseSession as DbSession
import weblab.facade.RemoteFacadeContext as RemoteFacadeContext

LOGIN_FAILED_DELAY=5

class LoginServer(object):
    def __init__(self, coord_address, locator, cfg_manager, *args, **kwargs):
        super(LoginServer,self).__init__(*args, **kwargs)
        self._coord_address = coord_address
        self._db_manager    = DatabaseManager.LoginDatabaseManager(cfg_manager)
        self._locator       = locator

        self._facade_server = LoginFacadeServer.LoginRemoteFacadeServer( self, cfg_manager ) 
        self._facade_server.start()

        self._external_id_providers = {
                    "FACEBOOK" : DelegatedLoginAuth.Facebook(self._db_manager)
                }

    def stop(self):
        if hasattr(super(LoginServer, self), 'stop'):
            super(LoginServer, self).stop()
        self._facade_server.stop()

    @logged(LogLevel.Info, except_for='password')
    def login(self, username, password):
        """ do_login(username, password) -> SessionId 

        raises ( 
            LoginExceptions.UnableToCompleteOperationException, 
            LoginExceptions.InvalidCredentialsException 
        )
        """
        db_session_id = self._validate_local_user(username, password)
        return self._reserve_session(db_session_id)

    def _validate_local_user(self, username, password):
        db_session_id = self._db_manager.check_credentials(username, str(password))

        if isinstance(db_session_id, DbSession.InvalidDatabaseSessionId):
            log.log( LoginServer, log.LogLevel.Warning, "Invalid username: %s" % username )
            time.sleep(LOGIN_FAILED_DELAY)
            raise LoginExceptions.InvalidCredentialsException(
                        "Invalid username or password!"
                    )
        elif isinstance(db_session_id, DbSession.NotAuthenticatedSessionId):
            for user_auth in db_session_id.user_auths:
                login_auth = LoginAuth.LoginAuth.create(user_auth)
                if login_auth.authenticate(username, password):
                    log.log( LoginServer, log.LogLevel.Debug, "Username: %s with user_auth %s: SUCCESS" % (username, user_auth) )
                    break
                log.log( LoginServer, log.LogLevel.Warning, "Username: %s with user_auth %s: FAIL" % (username, user_auth) )
            else :
                raise LoginExceptions.InvalidCredentialsException(
                    "Invalid username or password!"
                )
        return db_session_id

    def _reserve_session(self, db_session_id):
        ups_server = self._locator.get_easy_server(ServerType.UserProcessing)
        session_id, server_route = ups_server.reserve_session(db_session_id)
        context = RemoteFacadeContext.get_context()
        context.route = server_route
        return session_id

    @logged(LogLevel.Info)
    def extensible_login(self, system, credentials):
        external_user_id = self._validate_remote_user(system, credentials)
        # It's a valid external user, book it if there is a user linked
        try:
            db_session_id = self._db_manager.check_external_credentials(external_user_id, system)
        except DbExceptions.DbUserNotFoundException:
            raise LoginExceptions.InvalidCredentialsException("%s User ID not found: %s" % (system, external_user_id))

        return self._reserve_session(db_session_id)

    def _validate_remote_user(self, system, credentials):
        system = system.upper()
        if not system in self._external_id_providers:
            raise LoginExceptions.LoginException("Invalid system!")

        external_user_id = self._external_id_providers[system].get_user_id(credentials)
        if external_user_id == "":
            raise LoginExceptions.InvalidCredentialsException(
                "Invalid username or password!"
            )
        return external_user_id


    @logged(LogLevel.Info, except_for="password")
    def grant_external_credentials(self, username, password, system, credentials):
        local_db_session_id  = self._validate_local_user(username, password)
        external_user_id = self._validate_remote_user(system, credentials)<commit_msg>[new_login_system]  * Adding login_not_linkable_users so users can't link accounts like "demo"<commit_after>#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2005-2009 University of Deusto
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
#
# This software consists of contributions made by many individuals, 
# listed below:
#
# Author: <NAME> <<EMAIL>>
# 
import voodoo.log as log
from voodoo.log import logged
import voodoo.LogLevel as LogLevel
import time

import weblab.login.LoginAuth as LoginAuth
import weblab.login.DelegatedLoginAuth as DelegatedLoginAuth
import weblab.login.database.DatabaseManager as DatabaseManager
import weblab.login.facade.LoginFacadeServer as LoginFacadeServer
import weblab.data.ServerType as ServerType
import weblab.exceptions.login.LoginExceptions as LoginExceptions
import weblab.exceptions.database.DatabaseExceptions as DbExceptions
import weblab.database.DatabaseSession as DbSession
import weblab.facade.RemoteFacadeContext as RemoteFacadeContext

LOGIN_FAILED_DELAY=5
NOT_LINKABLE_USERS = "login_not_linkable_users"

class LoginServer(object):
    def __init__(self, coord_address, locator, cfg_manager, *args, **kwargs):
        super(LoginServer,self).__init__(*args, **kwargs)
        self._coord_address = coord_address
        self._db_manager    = DatabaseManager.LoginDatabaseManager(cfg_manager)
        self._locator       = locator
        self._cfg_manager   = cfg_manager

        self._facade_server = LoginFacadeServer.LoginRemoteFacadeServer( self, cfg_manager ) 
        self._facade_server.start()

        self._external_id_providers = {
                    "FACEBOOK" : DelegatedLoginAuth.Facebook(self._db_manager)
                }

    def stop(self):
        if hasattr(super(LoginServer, self), 'stop'):
            super(LoginServer, self).stop()
        self._facade_server.stop()

    @logged(LogLevel.Info, except_for='password')
    def login(self, username, password):
        """ do_login(username, password) -> SessionId 

        raises ( 
            LoginExceptions.UnableToCompleteOperationException, 
            LoginExceptions.InvalidCredentialsException 
        )
        """
        db_session_id = self._validate_local_user(username, password)
        return self._reserve_session(db_session_id)

    def _validate_local_user(self, username, password):
        db_session_id = self._db_manager.check_credentials(username, str(password))

        if isinstance(db_session_id, DbSession.InvalidDatabaseSessionId):
            log.log( LoginServer, log.LogLevel.Warning, "Invalid username: %s" % username )
            time.sleep(LOGIN_FAILED_DELAY)
            raise LoginExceptions.InvalidCredentialsException(
                        "Invalid username or password!"
                    )
        elif isinstance(db_session_id, DbSession.NotAuthenticatedSessionId):
            for user_auth in db_session_id.user_auths:
                login_auth = LoginAuth.LoginAuth.create(user_auth)
                if login_auth.authenticate(username, password):
                    log.log( LoginServer, log.LogLevel.Debug, "Username: %s with user_auth %s: SUCCESS" % (username, user_auth) )
                    break
                log.log( LoginServer, log.LogLevel.Warning, "Username: %s with user_auth %s: FAIL" % (username, user_auth) )
            else :
                raise LoginExceptions.InvalidCredentialsException(
                    "Invalid username or password!"
                )
        return db_session_id

    def _reserve_session(self, db_session_id):
        ups_server = self._locator.get_easy_server(ServerType.UserProcessing)
        session_id, server_route = ups_server.reserve_session(db_session_id)
        context = RemoteFacadeContext.get_context()
        context.route = server_route
        return session_id

    @logged(LogLevel.Info)
    def extensible_login(self, system, credentials):
        external_user_id = self._validate_remote_user(system, credentials)
        # It's a valid external user, book it if there is a user linked
        try:
            db_session_id = self._db_manager.check_external_credentials(external_user_id, system)
        except DbExceptions.DbUserNotFoundException:
            raise LoginExceptions.InvalidCredentialsException("%s User ID not found: %s" % (system, external_user_id))

        return self._reserve_session(db_session_id)

    def _validate_remote_user(self, system, credentials):
        system = system.upper()
        if not system in self._external_id_providers:
            raise LoginExceptions.LoginException("Invalid system!")

        external_user_id = self._external_id_providers[system].get_user_id(credentials)
        if external_user_id == "":
            raise LoginExceptions.InvalidCredentialsException(
                "Invalid username or password!"
            )
        return external_user_id


    @logged(LogLevel.Info, except_for="password")
    def grant_external_credentials(self, username, password, system, credentials):
        not_linkable_users = self._cfg_manager.get_value(NOT_LINKABLE_USERS, [])
        for not_linkable_user in not_linkable_users:
            if username == not_linkable_user:
                raise LoginExceptions.LoginException("Username not linkable!")

        local_db_session_id  = self._validate_local_user(username, password)
        external_user_id = self._validate_remote_user(system, credentials)
{'fraction_non_alphanumeric': 0.07828211634244901, 'fraction_numerical': 0.0018795226012592802, 'mean_word_length': 3.2013422818791946, 'pattern_counts': {'":': 2, '<': 9, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5380842', 'n_tokens_mistral': 3001, 'n_tokens_neox': 2906, 'n_words': 641}