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