App-Netdisco

 view release on metacpan or  search on metacpan

lib/App/Netdisco/Web/AuthN.pm  view on Meta::CPAN

    else {
        # 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' });

        if ($api) {
            header('Content-Type' => 'application/json');

            # if there's a current valid token then reissue it and reset timer
            $user->update({
              token_from => time,
              ($provider->validate_api_token($user->token)
                ? () : (token => \'md5(random()::text)')),
            })->discard_changes();
            return to_json { api_key => $user->token };
        }

        redirect ((scalar URI::Based->new(param('return_url'))->path_query) || '/');
    }
    else {
        # invalidate session cookie
        session->destroy;

        schema('netdisco')->resultset('UserLog')->create({
          username => param('username'),
          userip => request->remote_address,
          event => (sprintf 'Login Failure (%s)', ($api ? 'API' : 'WebUI')),
          details => param('return_url'),
        });

        if ($api) {
            header('Content-Type' => 'application/json');
            status('unauthorized');
            return to_json { error => 'authentication failed' };
        }

        vars->{login_failed}++;
        forward uri_for('/login'),
          { login_failed => 1, return_url => param('return_url') },
          { method => 'GET' };
    }
};

# ugh, *puke*, but D::P::Swagger has no way to set this with swagger_path
# must be after the path is declared, above.
Dancer::Plugin::Swagger->instance->doc
  ->{paths}->{ (setting('url_base') ? setting('url_base')->with('/login')->path : '/login') }
  ->{post}->{security}->[0]->{BasicAuth} = [];

# we override the default login_handler, so logout has to be handled as well
swagger_path {
  description => 'Destroy user API Key and session cookie',
  tags => ['General'],
  path => (setting('url_base') ? setting('url_base')->with('/logout')->path : '/logout'),
  parameters => [],
  responses => { default => { examples => { 'application/json' => {} } } },
},
get '/logout' => sub {
    my $api = ((request->accept and request->accept =~ m/(?:json|javascript)/) ? true : false);

    # clear out API token
    my $user = schema('netdisco')->resultset('User')
      ->find({ username => session('logged_in_user')});
    $user->update({token => undef, token_from => undef})->discard_changes()
      if $user and $user->in_storage;

    # invalidate session cookie
    session->destroy;



( run in 0.785 second using v1.01-cache-2.11-cpan-13bb782fe5a )