def login_idporten_mock():
    if request.method != 'POST':
        return render_template('bruker_login.html')

    ssn = request.form['ssn']
    password = request.form['password']
    if DEBUG_PASSWORD is None or password != DEBUG_PASSWORD:
        app.logger.error('Running in debug mode, incorrect DEBUG_PASSWORD or not set')
        abort(403)

    auth_user = authentication.login_idporten_user_by_private_id(ssn, {})
    login_user(auth_user, remember=True)

    # Force the user to fill in the profile if unregistered
    if not auth_user.is_registered():
        response = make_response(redirect("/profil"))
    else:
        # Check if the user wants to redirect to a specific page
        redirect_target = get_redirect_target_from_cookie(request)
        response = make_response(redirect(redirect_target or request.args.get('next') or '/'))
        invalidate_redirect_target_cookie(response)

    set_cookie(response, 'auth_token', make_auth_token(auth_user.user_id))

    return response
def login_adfs_mock():
    if request.method != 'POST':
        return render_template('admin_login.html', roles=authentication.adfs_roles())

    username = request.form['username']
    password = request.form['password']
    if DEBUG_PASSWORD is None or password != DEBUG_PASSWORD:
        app.logger.error('Running in debug mode, but DEBUG_PASSWORD is not set')
        abort(403)

    auth_user = authentication.login_adfs_user_by_private_id(username, {})

    roles = request.form.getlist('roles')
    user_roles = authentication.update_user_roles(auth_user.user_id, roles)
    auth_user.roles = user_roles

    login_user(auth_user, remember=True)
    # Check if the user wants to redirect to a specific page
    redirect_target = get_redirect_target_from_cookie(request)
    response = make_response(redirect(redirect_target or request.args.get('next') or '/'))
    invalidate_redirect_target_cookie(response)

    set_cookie(response, 'auth_token', make_auth_token(auth_user.user_id))

    # set authentication type cookie
    set_auth_type_cookie(response, "active_directory")

    return response
def logged_in_from_adfs():
    app.logger.info('User logged in via ADFS')
    SAMLResponse = request.values['SAMLResponse']

    try:
        res = ADFSResponse(SAMLResponse, app.adfs_settings["idp_cert_fingerprint"])

        res.decrypt(app.adfs_settings["sp_private_key"])
        valid = res.is_valid()

        if not valid:
            app.logger.error('Invalid response from ADFS')
            abort(404)

        def to_unicode(in_str):
            return in_str.encode("utf-8")

        name_id = to_unicode(res.name_id)
        ident = get_attribute_or_404(res, "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsaccountname")
        name = to_unicode(get_attribute_or_404(res, "http://schemas.xmlsoap.org/claims/CommonName"))
        email = to_unicode(
            get_attribute_or_404(res, "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress"))

        app.logger.info('Logging in: name_id=%s name=%s ident=%s email=%s', name_id, name, ident, email)
        data = {"misc": {"name": name,
                         "email": email,
                         "ident": ident}}

        claims = adfs_helper.parse_claims(res._document)
        app.logger.info('Claims in SAML response: %s', claims)

        roles = adfs_helper.extract_roles(claims)
        app.logger.info('Requested roles parsed from claims: %s', roles)

        auth_user = authentication.login_adfs_user_by_private_id(ident, data)
        user_roles = authentication.update_user_roles(auth_user.user_id, roles)
        auth_user.roles = user_roles
        app.logger.info('User roles after update: %s', user_roles)

        login_user(auth_user, remember=True)
        # Check if the user wants to redirect to a specific page
        redirect_target = get_redirect_target_from_cookie(request)
        response = make_response(redirect(redirect_target or request.args.get('next') or '/'))
        invalidate_redirect_target_cookie(response)

        set_cookie(response, 'auth_token', make_auth_token(auth_user.user_id))

        # set authentication type cookie
        set_auth_type_cookie(response, "active_directory")

        return response
    except Exception as e:
        app.logger.error('Logging failed: %s', e)
        abort(404, 'Ugyldig innlogging.')
def logged_in():
    # IDPorten redirects to this URL if all ok with login
    app.logger.info("User logged in via ID-porten: request.values=%s",
                    request.values)
    SAMLResponse = request.values['SAMLResponse']

    res = IdpResponse(
        SAMLResponse,
        "TODO: remove signature parameter"
    )

    # Decrypt response from IDPorten with our private key, and make sure that the response is valid
    # (it was encrypted with same key)
    valid = res.is_valid(app.idporten_settings["idp_cert_file"], app.idporten_settings["private_key_file"])
    if valid:
        national_id_number = res.get_decrypted_assertion_attribute_value("uid")[0]
        idporten_parameters = {
            "session_index": res.get_session_index(),
            "name_id": res.name_id
        }

        auth_user = authentication.login_idporten_user_by_private_id(national_id_number,
                                                                     idporten_parameters)
        login_user(auth_user, remember=True)

        # Force the user to fill in the profile if unregistered
        if not auth_user.is_registered():
            app.logger.info("Logged in: %s Uregistrert bruker (%s)",
                            datetime.now().isoformat(),
                            national_id_number[:6])
            response = make_response(redirect("/profile"))
        else:
            app.logger.info("Logged in: %s %s %s (%s)",
                            datetime.now().isoformat(),
                            auth_user.first_name,
                            auth_user.last_name,
                            national_id_number[:6])

            # Check if the user wants to redirect to a specific page
            redirect_target = get_redirect_target_from_cookie(request)
            response = make_response(redirect(redirect_target or request.args.get('next') or '/'))
            invalidate_redirect_target_cookie(response)

        set_cookie(response, 'auth_token', make_auth_token(auth_user.user_id))
        return response
    else:
        abort(404, 'Ugyldig innlogging.')