3 namespace BookStack\Access;
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;
19 protected const LAST_LOGIN_ATTEMPTED_SESSION_KEY = 'auth-login-last-attempted';
21 public function __construct(
22 protected MfaSession $mfaSession,
23 protected EmailConfirmationService $emailConfirmationService,
24 protected SocialDriverManager $socialDriverManager,
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.
34 * @throws StoppedAuthenticationException|LoginAttemptInvalidUserException
36 public function login(User $user, string $method, bool $remember = false): void
38 if ($user->isGuest()) {
39 throw new LoginAttemptInvalidUserException('Login not allowed for guest user');
42 if ($this->awaitingEmailConfirmation($user) || $this->needsMfaVerification($user)) {
43 $this->setLastLoginAttemptedForUser($user, $method, $remember);
45 throw new StoppedAuthenticationException($user, $this);
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);
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);
63 * Reattempt a system login after a previous stopped attempt.
67 public function reattemptLoginFor(User $user): void
69 if ($user->id !== ($this->getLastLoginAttemptUser()->id ?? null)) {
70 throw new Exception('Login reattempt user does align with current session state');
73 $lastLoginDetails = $this->getLastLoginAttemptDetails();
74 $this->login($user, $lastLoginDetails['method'], $lastLoginDetails['remember'] ?? false);
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.
82 public function getLastLoginAttemptUser(): ?User
84 $id = $this->getLastLoginAttemptDetails()['user_id'];
86 return User::query()->where('id', '=', $id)->first();
90 * Get the details of the last login attempt.
91 * Checks upon a ttl of about 1 hour since that last attempted login.
93 * @return array{user_id: ?string, method: ?string, remember: bool}
95 protected function getLastLoginAttemptDetails(): array
97 $value = session()->get(self::LAST_LOGIN_ATTEMPTED_SESSION_KEY);
99 return ['user_id' => null, 'method' => null, 'remember' => false];
102 [$id, $method, $remember, $time] = explode(':', $value);
103 $hourAgo = time() - (60 * 60);
104 if ($time < $hourAgo) {
105 $this->clearLastLoginAttempted();
107 return ['user_id' => null, 'method' => null, 'remember' => false];
110 return ['user_id' => $id, 'method' => $method, 'remember' => boolval($remember)];
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.
118 protected function setLastLoginAttemptedForUser(User $user, string $method, bool $remember): void
121 self::LAST_LOGIN_ATTEMPTED_SESSION_KEY,
122 implode(':', [$user->id, $method, $remember, time()])
127 * Clear the last login attempted session value.
129 protected function clearLastLoginAttempted(): void
131 session()->remove(self::LAST_LOGIN_ATTEMPTED_SESSION_KEY);
135 * Check if MFA verification is needed.
137 public function needsMfaVerification(User $user): bool
139 return !$this->mfaSession->isVerifiedForUser($user) && $this->mfaSession->isRequiredForUser($user);
143 * Check if the given user is awaiting email confirmation.
145 public function awaitingEmailConfirmation(User $user): bool
147 return $this->emailConfirmationService->confirmationRequired() && !$user->email_confirmed;
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.
156 * @throws StoppedAuthenticationException
157 * @throws LoginAttemptException
159 public function attempt(array $credentials, string $method, bool $remember = false): bool
161 if ($this->areCredentialsForGuest($credentials)) {
165 $result = auth()->attempt($credentials, $remember);
167 $user = auth()->user();
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.
182 * Check if the given credentials are likely for the system guest account.
184 protected function areCredentialsForGuest(array $credentials): bool
186 if (isset($credentials['email'])) {
187 return User::query()->where('email', '=', $credentials['email'])
188 ->where('system_name', '=', 'public')
196 * Logs the current user out of the application.
197 * Returns an app post-redirect path.
199 public function logout(): string
202 session()->invalidate();
203 session()->regenerateToken();
205 return $this->shouldAutoInitiate() ? '/login?prevent_auto_init=true' : '/';
209 * Check if login auto-initiate should be active based upon authentication config.
211 public function shouldAutoInitiate(): bool
213 $autoRedirect = config('auth.auto_initiate');
214 if (!$autoRedirect) {
218 $socialDrivers = $this->socialDriverManager->getActive();
219 $authMethod = config('auth.method');
221 return count($socialDrivers) === 0 && in_array($authMethod, ['oidc', 'saml2']);