App-Netdisco
view release on metacpan or search on metacpan
lib/App/Netdisco/Web/AuthN.pm view on Meta::CPAN
sub _api_unauthorized {
my $error = shift;
status 401;
content_type 'application/json';
return halt(to_json { error => $error, return_url => param('return_url') });
}
# Dancer will create a session if it sees its own cookie. For the API and also
# various auto login options we need to bootstrap the session instead. If no
# auth data passed, then the hook simply returns, no session is set, and the
# user is redirected to login page.
hook 'before' => sub {
my $theme_by_name = qr{\A\Q@{[ uri_for('/theme/')->path ]}\E[A-Za-z0-9_-]+\.css\z};
# return if request is for endpoints not requiring a session
return if (
request->path eq uri_for('/login')->path
or request->path eq uri_for('/logout')->path
or request->path eq uri_for('/swagger.json')->path
or request->path eq uri_for('/theme.css')->path
or request->path =~ $theme_by_name
or index(request->path, uri_for('/swagger-ui')->path) == 0
or (setting('health_path') and request->path eq uri_for(setting('health_path'))->path)
or (setting('metrics_path') and request->path eq uri_for(setting('metrics_path'))->path)
);
# Dancer will issue a cookie to the client which could be returned and
# cause API calls to succeed without passing token. Kill the session.
session->destroy if request_is_api;
# ...otherwise, we can short circuit if Dancer reads its cookie OK
return if session('logged_in_user');
my $delegated = _get_delegated_authn_user();
# this ordering allows override of delegated authN if given creds
# protect against delegated authN config but no valid user
if ((not $delegated) and
(setting('trust_x_remote_user') or setting('trust_remote_user'))) {
session->destroy;
request->path_info('/');
}
# API calls must conform strictly to path and header requirements
elsif (request_is_api and request->header('Authorization')) {
# from the internals of Dancer::Plugin::Auth::Extensible
my $provider = Dancer::Plugin::Auth::Extensible::auth_provider('users');
my $token = request->header('Authorization');
my $user = $provider->validate_api_token($token)
or return _api_unauthorized('invalid or expired token');
session(logged_in_user => $user->username);
session(logged_in_user_realm => 'users');
}
elsif ($delegated) {
session(logged_in_user => $delegated->username);
session(logged_in_user_realm => 'users');
}
else {
# An API request with no credentials is answered here. The handler for
# '/' tells the API apart by the Accept header alone, so a client that
# sent none got the login page as HTML, with a 200 and a JSON
# Content-Type, and took that for success.
return _api_unauthorized('not authorized') if request_is_api;
# user has no AuthN - force to handler for '/'
request->path_info('/');
}
};
# override default login_handler so we can log access in the database
swagger_path {
description => 'Obtain an API Key',
tags => ['General'],
path => (setting('url_base') ? setting('url_base')->with('/login')->path : '/login'),
parameters => [],
responses => { default => { examples => {
'application/json' => { api_key => 'cc9d5c02d8898e5728b7d7a0339c0785' } } },
},
},
post '/login' => sub {
my $api = ((request->accept and request->accept =~ m/(?:json|javascript)/) ? true : false);
# from the internals of Dancer::Plugin::Auth::Extensible
my $provider = Dancer::Plugin::Auth::Extensible::auth_provider('users');
# get authN data from BasicAuth header used by API, put into params
my $authheader = request->header('Authorization');
if (defined $authheader and $authheader =~ /^Basic (.*)$/i) {
my ($u, $p) = split(m/:/, (MIME::Base64::decode($1) || ":"));
params->{username} = $u;
params->{password} = $p;
}
# validate authN
my ($success, $realm) = authenticate_user(param('username'),param('password'));
# or try to get user from somewhere else
my $delegated = _get_delegated_authn_user();
if (($success and not
# protect against delegated authN config but no valid user (then must ignore params)
(not $delegated and (setting('trust_x_remote_user') or setting('trust_remote_user'))))
or $delegated) {
# this ordering allows override of delegated user if given creds
my $user = ($success ? $provider->get_user_details(param('username'))
: $delegated);
session logged_in_user => $user->username;
session logged_in_fullname => ($user->fullname || '');
session logged_in_user_realm => ($realm || 'users');
schema('netdisco')->resultset('UserLog')->create({
username => session('logged_in_user'),
userip => request->remote_address,
event => (sprintf 'Login (%s)', ($api ? 'API' : 'WebUI')),
details => param('return_url'),
});
$user->update({ last_on => \'LOCALTIMESTAMP' });
( run in 0.796 second using v1.01-cache-2.11-cpan-3f962061493 )