# Copyright 2015-2021 SUSE LLC
# SPDX-License-Identifier: GPL-2.0-or-later

package OpenQA::WebAPI::Auth::Fake;
use Mojo::Base -base, -signatures;
use Time::Seconds;

use constant KEY => $ENV{OPENQA_FAKE_AUTH_KEY} // '1234567890ABCDEF';
use constant SECRET => $ENV{OPENQA_FAKE_AUTH_SECRET} // '1234567890ABCDEF';
use constant EXPIRATION => $ENV{OPENQA_FAKE_AUTH_EXPIRATION_S} // ONE_DAY;

sub auth_logout ($self) { return }

sub auth_login ($self) {
    my $headers = $self->req->headers;

    my %users;
    $users{Demo} = {fullname => 'Demo User', email => 'demo@user.org', admin => 1, operator => 1, key => KEY};
    $users{nobody}
      = {fullname => 'Nobody', email => 'nobody@example.com', admin => 0, operator => 0, key => '1111111111111111'};
    $users{otherdeveloper} = {
        fullname => 'Other developer',
        email => 'dev@example.com',
        admin => 1,
        operator => 1,
        key => '2222222222222222'
    };

    my $user = $self->req->param('user') || 'Demo';
    my $userinfo = $users{$user} || die 'No such user';
    $userinfo->{username} = $user;

    $user = $self->schema->resultset('Users')->create_user(
        $userinfo->{username},
        email => $userinfo->{email},
        nickname => $userinfo->{username},
        fullname => $userinfo->{fullname},
        is_admin => $userinfo->{admin},
        is_operator => $userinfo->{operator});

    my $key = $user->api_keys->find_or_create({key => $userinfo->{key}, secret => SECRET});
    # expire in a day after login
    $key->update({t_expiration => DateTime->from_epoch(epoch => time + EXPIRATION)});
    $self->session->{user} = $userinfo->{username};
    return (error => 0);
}

1;
