Exemple #1
0
def parse_authorization_header(header):
    """
    Parses the HTTP Auth Header to a JWT Token
    Args:
        header: Authorization header of the HTTP Request
    Examples:
        request.headers['Authorization'] or something same
    Returns:
        Valid JWT token
    """
    if not header:
        return None
    value = wsgi_to_bytes(header)
    try:
        auth_type, auth_info = value.split(None, 1)
        auth_type = auth_type.lower()
    except ValueError:
        # Fallback for old versions
        auth_type = b"bearer"
        auth_info = value

    if auth_type == b"basic":
        try:
            username, password = base64.b64decode(auth_info).split(b":", 1)

            with current_app.app_context():
                username = to_unicode(username, "utf-8")
                password = to_unicode(password, "utf-8")

                user_manager: UserManager = UserManager(
                    current_app.database_manager)
                auth_module = AuthModule(
                    SystemSettingsReader(current_app.database_manager))

                try:
                    user_instance = auth_module.login(user_manager, username,
                                                      password)
                except Exception as e:
                    return None
                if user_instance:
                    tg = TokenGenerator(current_app.database_manager)
                    return tg.generate_token(payload={
                        'user': {
                            'public_id': user_instance.get_public_id()
                        }
                    })
                else:
                    return None
        except Exception:
            return None

    if auth_type == b"bearer":
        try:
            tv = TokenValidator()
            decoded_token = tv.decode_token(auth_info)
            tv.validate_token(decoded_token)
            return auth_info
        except Exception:
            return None
    return None
Exemple #2
0
def get_provider_config_form(provider_class: str, request_user: User):
    auth_module = AuthModule(system_settings_reader)
    try:
        provider_class_config = auth_module.get_provider(
            provider_class).get_config().PROVIDER_CONFIG_FORM
    except StopIteration:
        return abort(404, 'Provider not found')
    return make_response(provider_class_config)
Exemple #3
0
def get_provider_config(provider_class: str, request_user: UserModel):
    auth_module = AuthModule(
        system_settings_reader.get_all_values_from_section(
            'auth', default=AuthModule.__DEFAULT_SETTINGS__))
    try:
        provider_class_config = auth_module.get_provider(
            provider_class).get_config()
    except StopIteration:
        return abort(404, 'Provider not found')
    return make_response(provider_class_config)
Exemple #4
0
 def __init__(self, database_manager: DatabaseManagerMongo = None):
     self.key_holder = KeyHolder()
     self.header = {'alg': 'RS512'}
     self.database_manager = database_manager or DatabaseManagerMongo(
         **SystemConfigReader().get_all_values_from_section('Database'))
     self.auth_module = AuthModule(
         SystemSettingsReader(self.database_manager))
Exemple #5
0
def post_login():
    user_manager: UserManager = UserManager(current_app.database_manager)
    group_manager: GroupManager = GroupManager(
        current_app.database_manager, right_manager=RightManager(rights))
    security_manager: SecurityManager = SecurityManager(
        current_app.database_manager)
    login_data = request.json
    if not request.json:
        return abort(400, 'No valid JSON data was provided')

    request_user_name = login_data['user_name']
    request_password = login_data['password']

    auth_module = AuthModule(
        system_settings_reader.get_all_values_from_section(
            'auth', default=AuthModule.__DEFAULT_SETTINGS__),
        user_manager=user_manager,
        group_manager=group_manager,
        security_manager=security_manager)
    user_instance = None
    try:
        user_instance = auth_module.login(request_user_name, request_password)
    except (AuthenticationProviderNotExistsError,
            AuthenticationProviderNotActivated) as err:
        return abort(503, err.message)
    except Exception as e:
        return abort(401)
    finally:
        # If login success generate user instance with token
        if user_instance:
            tg = TokenGenerator()
            token: bytes = tg.generate_token(
                payload={'user': {
                    'public_id': user_instance.get_public_id()
                }})
            token_issued_at = int(datetime.now().timestamp())
            token_expire = int(tg.get_expire_time().timestamp())

            login_response = LoginResponse(user_instance, token,
                                           token_issued_at, token_expire)

            return login_response.make_response()

        # Login not success
        else:
            return abort(401, 'Could not login')
Exemple #6
0
 def __init__(self, database_manager: DatabaseManagerMongo = None):
     self.key_holder = KeyHolder(database_manager)
     self.header = {'alg': 'RS512'}
     self.database_manager = database_manager
     self.auth_module = AuthModule(
         SystemSettingsReader(
             self.database_manager).get_all_values_from_section(
                 'auth', default=AuthModule.__DEFAULT_SETTINGS__))
Exemple #7
0
def get_installed_providers(request_user: User):
    provider_names: List[dict] = []
    auth_module = AuthModule(system_settings_reader)
    for provider in auth_module.providers:
        provider_names.append({
            'class_name': provider.get_name(),
            'external': provider.EXTERNAL_PROVIDER
        })
    return make_response(provider_names)
Exemple #8
0
def get_installed_providers(request_user: UserModel):
    provider_names: List[dict] = []
    auth_module = AuthModule(
        system_settings_reader.get_all_values_from_section(
            'auth', default=AuthModule.__DEFAULT_SETTINGS__))
    for provider in auth_module.providers:
        provider_names.append({
            'class_name': provider.get_name(),
            'external': provider.EXTERNAL_PROVIDER
        })
    return make_response(provider_names)
def post_login():
    login_data = request.json
    if not request.json:
        return abort(400, 'No valid JSON data was provided')

    request_user_name = login_data['user_name']
    request_password = login_data['password']

    auth_module = AuthModule(system_settings_reader)
    user_instance = None
    try:
        user_instance = auth_module.login(user_manager, request_user_name,
                                          request_password)
    except (AuthenticationProviderNotExistsError,
            AuthenticationProviderNotActivated) as err:
        return abort(503, err.message)
    except Exception as e:
        return abort(401)
    finally:
        # If login success generate user instance with token
        if user_instance:
            tg = TokenGenerator()
            token: bytes = tg.generate_token(
                payload={'user': {
                    'public_id': user_instance.get_public_id()
                }})
            token_issued_at = int(datetime.now().timestamp())
            token_expire = int(tg.get_expire_time().timestamp())

            login_response = LoginResponse(user_instance, token,
                                           token_issued_at, token_expire)

            return login_response.make_response()

        # Login not success
        else:
            return abort(401, 'Could not login')
Exemple #10
0
def get_auth_settings(request_user: User):
    auth_module = AuthModule(system_settings_reader)
    return make_response(auth_module.settings)
Exemple #11
0
def get_auth_settings():
    auth_settings = system_settings_reader.get_all_values_from_section(
        'auth', default=AuthModule.__DEFAULT_SETTINGS__)
    auth_module = AuthModule(auth_settings)
    return make_response(auth_module.settings)