Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
84.76% covered (warning)
84.76%
89 / 105
33.33% covered (danger)
33.33%
1 / 3
CRAP
0.00% covered (danger)
0.00%
0 / 1
Index
84.76% covered (warning)
84.76%
89 / 105
33.33% covered (danger)
33.33%
1 / 3
19.15
0.00% covered (danger)
0.00%
0 / 1
 readResponse
95.00% covered (success)
95.00%
38 / 40
0.00% covered (danger)
0.00%
0 / 1
8
 testLogin
75.86% covered (warning)
75.86%
44 / 58
0.00% covered (danger)
0.00%
0 / 1
6.51
 getProviderList
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
4
1<?php
2
3/**
4 * @package Zmsstatistic
5 * @copyright BerlinOnline Stadtportal GmbH & Co. KG
6 **/
7
8namespace BO\Zmsstatistic;
9
10use BO\Slim\Render;
11use BO\Zmsclient\ModuleAccess;
12use BO\Zmsentities\Useraccount;
13use BO\Zmsentities\Workstation;
14use Psr\Http\Message\RequestInterface;
15use Psr\Http\Message\ResponseInterface;
16
17class Index extends BaseController
18{
19    protected bool $withAccess = false;
20
21    /**
22     * @SuppressWarnings(Param)
23     * @return \Psr\Http\Message\ResponseInterface
24     */
25    #[\Override]
26    public function readResponse(
27        RequestInterface $request,
28        ResponseInterface $response,
29        array $args
30    ): ResponseInterface {
31        try {
32            $workstation = \App::http()->readGetResult('/workstation/')->getEntity();
33        } catch (\Exception $workstationexception) {
34            $workstation = null;
35        }
36
37        $config = \App::http()->readGetResult('/config/', [], \App::CONFIG_SECURE_TOKEN)->getEntity();
38        /** @var \Psr\Http\Message\ServerRequestInterface $request */
39        $input = $request->getParsedBody();
40        $oidclogin = $request->getAttribute('validator')->getParameter('oidclogin')->isString()->getValue();
41        if ($request->getMethod() === 'POST') {
42            $loginData = $this->testLogin($input);
43            if ($loginData instanceof Workstation && $loginData->offsetExists('authkey')) {
44                \BO\Zmsclient\Auth::setKey($loginData->authkey);
45                return ModuleAccess::rejectWrongModuleAccess(ModuleAccess::MODULE_STATISTIC, $loginData, $response)
46                    ?? \BO\Slim\Render::redirect('workstationSelect', array(), array());
47            }
48
49            return Render::withHtml(
50                $response,
51                'page/index.twig',
52                array(
53                    'title' => 'Anmeldung gescheitert',
54                    'loginfailed' => true,
55                    'workstation' => null,
56                    'exception' => $loginData,
57                    'oidcproviderlist' => $this->getProviderList($config),
58                    'oidclogin' => $oidclogin,
59                    'showloginform' => (! $oidclogin)
60                )
61            );
62        } else {
63            if ($workstation instanceof Workstation && $workstation->hasId()) {
64                if ($wrongModuleResponse = ModuleAccess::rejectWrongModuleAccess(ModuleAccess::MODULE_STATISTIC, $workstation, $response)) {
65                    return $wrongModuleResponse;
66                }
67            }
68            return Render::withHtml(
69                $response,
70                'page/index.twig',
71                array(
72                    'title' => 'Anmeldung',
73                    'config' => $config,
74                    'workstation' => $workstation,
75                    'oidcproviderlist' => $this->getProviderList($config),
76                    'oidclogin' => $oidclogin,
77                    'showloginform' => (! $oidclogin)
78                )
79            );
80        }
81    }
82
83    /**
84     * @return mixed
85     */
86    #[\Override]
87    protected function testLogin(mixed $input): mixed
88    {
89        $userAccount = new Useraccount(array(
90            'id' => $input['loginName'],
91            'password' => $input['password'],
92            'departments' => array('id' => 0) // required in schema validation
93        ));
94        try {
95            /** @var mixed $workstation */
96            $workstation = \App::http()->readPostResult('/workstation/login/', $userAccount)->getEntity();
97
98            /** @var mixed $authkey */
99            $authkey = $workstation->authkey;
100            $sessionHash = hash('sha256', $authkey);
101            \App::$log->info('Login successful', [
102                'event' => 'auth_login_success',
103                'timestamp' => date('c'),
104                'username' => $userAccount->id,
105                'hashed_session_token' => $sessionHash,
106                'application' => 'zmsstatistic'
107            ]);
108
109            return $workstation;
110        } catch (\BO\Zmsclient\Exception $exception) {
111            $template = Helper\TwigExceptionHandler::getExceptionTemplate($exception);
112            if ('BO\Zmsentities\Exception\SchemaValidation' == $exception->template) {
113                $exceptionData = [
114                  'template' => 'exception/bo/zmsbackend/useraccount/exception/invalidcredentials.twig'
115                ];
116                $exceptionData['data']['password']['messages'] = [
117                    'Der Nutzername oder das Passwort wurden falsch eingegeben'
118                ];
119                \App::$log->info('Login failed - invalid credentials', [
120                    'event' => 'auth_login_failed',
121                    'timestamp' => date('c'),
122                    'username' => $userAccount->id,
123                    'error_type' => 'invalid_credentials',
124                    'application' => 'zmsstatistic'
125                ]);
126            } elseif ('BO\Zmsbackend\Useraccount\Exception\UserAlreadyLoggedIn' == $exception->template) {
127                \BO\Zmsclient\Auth::setKey($exception->data['authkey'], time() + \App::SESSION_DURATION);
128                \App::$log->info('User already logged in - reusing existing session', [
129                    'event' => 'auth_session_reuse',
130                    'timestamp' => date('c'),
131                    'username' => $userAccount->id,
132                    'hashed_session_token' => hash('sha256', $exception->data['authkey']),
133                    'application' => 'zmsstatistic'
134                ]);
135                throw $exception;
136            } elseif (
137                '' != $exception->template
138                && $this->exceptionTemplateExists($template)
139            ) {
140                $exceptionData = [
141                  'template' => $template,
142                  'data' => $exception->data
143                ];
144                \App::$log->info('Login failed - other error', [
145                    'event' => 'auth_login_failed',
146                    'timestamp' => date('c'),
147                    'username' => $userAccount->id,
148                    'error_type' => 'other',
149                    'error_message' => $exception->getMessage(),
150                    'application' => 'zmsstatistic'
151                ]);
152            } else {
153                throw $exception;
154            }
155        }
156        return $exceptionData;
157    }
158    protected function getProviderList(mixed $config): array
159    {
160        $allowedProviderList = explode(',', $config->getPreference('oidc', 'provider') ?? '');
161        $oidcproviderlist = [];
162        foreach (\BO\Slim\Middleware\OAuthMiddleware::$authInstances as $provider => $authInstance) {
163            if (
164                class_exists($authInstance) &&
165                in_array($provider, $allowedProviderList)
166            ) {
167                $oidcproviderlist[] = $provider;
168            }
169        }
170        return $oidcproviderlist;
171    }
172}