]> BookStack Code Mirror - bookstack/blob - app/Access/LoginService.php
OIDC RP Logout: Added autodiscovery support and test cases
[bookstack] / app / Access / LoginService.php
1 <?php
2
3 namespace BookStack\Access;
4
5 use BookStack\Access\Mfa\MfaSession;
6 use BookStack\Activity\ActivityType;
7 use BookStack\Exceptions\LoginAttemptException;
8 use BookStack\Exceptions\StoppedAuthenticationException;
9 use BookStack\Facades\Activity;
10 use BookStack\Facades\Theme;
11 use BookStack\Theming\ThemeEvents;
12 use BookStack\Users\Models\User;
13 use Exception;
14
15 class LoginService
16 {
17     protected const LAST_LOGIN_ATTEMPTED_SESSION_KEY = 'auth-login-last-attempted';
18
19     public function __construct(
20         protected MfaSession $mfaSession,
21         protected EmailConfirmationService $emailConfirmationService,
22         protected SocialDriverManager $socialDriverManager,
23     ) {
24     }
25
26     /**
27      * Log the given user into the system.
28      * Will start a login of the given user but will prevent if there's
29      * a reason to (MFA or Unconfirmed Email).
30      * Returns a boolean to indicate the current login result.
31      *
32      * @throws StoppedAuthenticationException
33      */
34     public function login(User $user, string $method, bool $remember = false): void
35     {
36         if ($this->awaitingEmailConfirmation($user) || $this->needsMfaVerification($user)) {
37             $this->setLastLoginAttemptedForUser($user, $method, $remember);
38
39             throw new StoppedAuthenticationException($user, $this);
40         }
41
42         $this->clearLastLoginAttempted();
43         auth()->login($user, $remember);
44         Activity::add(ActivityType::AUTH_LOGIN, "{$method}; {$user->logDescriptor()}");
45         Theme::dispatch(ThemeEvents::AUTH_LOGIN, $method, $user);
46
47         // Authenticate on all session guards if a likely admin
48         if ($user->can('users-manage') && $user->can('user-roles-manage')) {
49             $guards = ['standard', 'ldap', 'saml2', 'oidc'];
50             foreach ($guards as $guard) {
51                 auth($guard)->login($user);
52             }
53         }
54     }
55
56     /**
57      * Reattempt a system login after a previous stopped attempt.
58      *
59      * @throws Exception
60      */
61     public function reattemptLoginFor(User $user)
62     {
63         if ($user->id !== ($this->getLastLoginAttemptUser()->id ?? null)) {
64             throw new Exception('Login reattempt user does align with current session state');
65         }
66
67         $lastLoginDetails = $this->getLastLoginAttemptDetails();
68         $this->login($user, $lastLoginDetails['method'], $lastLoginDetails['remember'] ?? false);
69     }
70
71     /**
72      * Get the last user that was attempted to be logged in.
73      * Only exists if the last login attempt had correct credentials
74      * but had been prevented by a secondary factor.
75      */
76     public function getLastLoginAttemptUser(): ?User
77     {
78         $id = $this->getLastLoginAttemptDetails()['user_id'];
79
80         return User::query()->where('id', '=', $id)->first();
81     }
82
83     /**
84      * Get the details of the last login attempt.
85      * Checks upon a ttl of about 1 hour since that last attempted login.
86      *
87      * @return array{user_id: ?string, method: ?string, remember: bool}
88      */
89     protected function getLastLoginAttemptDetails(): array
90     {
91         $value = session()->get(self::LAST_LOGIN_ATTEMPTED_SESSION_KEY);
92         if (!$value) {
93             return ['user_id' => null, 'method' => null];
94         }
95
96         [$id, $method, $remember, $time] = explode(':', $value);
97         $hourAgo = time() - (60 * 60);
98         if ($time < $hourAgo) {
99             $this->clearLastLoginAttempted();
100
101             return ['user_id' => null, 'method' => null];
102         }
103
104         return ['user_id' => $id, 'method' => $method, 'remember' => boolval($remember)];
105     }
106
107     /**
108      * Set the last login attempted user.
109      * Must be only used when credentials are correct and a login could be
110      * achieved but a secondary factor has stopped the login.
111      */
112     protected function setLastLoginAttemptedForUser(User $user, string $method, bool $remember)
113     {
114         session()->put(
115             self::LAST_LOGIN_ATTEMPTED_SESSION_KEY,
116             implode(':', [$user->id, $method, $remember, time()])
117         );
118     }
119
120     /**
121      * Clear the last login attempted session value.
122      */
123     protected function clearLastLoginAttempted(): void
124     {
125         session()->remove(self::LAST_LOGIN_ATTEMPTED_SESSION_KEY);
126     }
127
128     /**
129      * Check if MFA verification is needed.
130      */
131     public function needsMfaVerification(User $user): bool
132     {
133         return !$this->mfaSession->isVerifiedForUser($user) && $this->mfaSession->isRequiredForUser($user);
134     }
135
136     /**
137      * Check if the given user is awaiting email confirmation.
138      */
139     public function awaitingEmailConfirmation(User $user): bool
140     {
141         return $this->emailConfirmationService->confirmationRequired() && !$user->email_confirmed;
142     }
143
144     /**
145      * Attempt the login of a user using the given credentials.
146      * Meant to mirror Laravel's default guard 'attempt' method
147      * but in a manner that always routes through our login system.
148      * May interrupt the flow if extra authentication requirements are imposed.
149      *
150      * @throws StoppedAuthenticationException
151      * @throws LoginAttemptException
152      */
153     public function attempt(array $credentials, string $method, bool $remember = false): bool
154     {
155         $result = auth()->attempt($credentials, $remember);
156         if ($result) {
157             $user = auth()->user();
158             auth()->logout();
159             $this->login($user, $method, $remember);
160         }
161
162         return $result;
163     }
164
165     /**
166      * Logs the current user out of the application.
167      * Returns an app post-redirect path.
168      */
169     public function logout(): string
170     {
171         auth()->logout();
172         session()->invalidate();
173         session()->regenerateToken();
174
175         return $this->shouldAutoInitiate() ? '/login?prevent_auto_init=true' : '/';
176     }
177
178     /**
179      * Check if login auto-initiate should be active based upon authentication config.
180      */
181     public function shouldAutoInitiate(): bool
182     {
183         $autoRedirect = config('auth.auto_initiate');
184         if (!$autoRedirect) {
185             return false;
186         }
187
188         $socialDrivers = $this->socialDriverManager->getActive();
189         $authMethod = config('auth.method');
190
191         return count($socialDrivers) === 0 && in_array($authMethod, ['oidc', 'saml2']);
192     }
193 }