3 namespace BookStack\Access;
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;
17 protected const LAST_LOGIN_ATTEMPTED_SESSION_KEY = 'auth-login-last-attempted';
19 public function __construct(
20 protected MfaSession $mfaSession,
21 protected EmailConfirmationService $emailConfirmationService,
22 protected SocialDriverManager $socialDriverManager,
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.
32 * @throws StoppedAuthenticationException
34 public function login(User $user, string $method, bool $remember = false): void
36 if ($this->awaitingEmailConfirmation($user) || $this->needsMfaVerification($user)) {
37 $this->setLastLoginAttemptedForUser($user, $method, $remember);
39 throw new StoppedAuthenticationException($user, $this);
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);
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);
57 * Reattempt a system login after a previous stopped attempt.
61 public function reattemptLoginFor(User $user)
63 if ($user->id !== ($this->getLastLoginAttemptUser()->id ?? null)) {
64 throw new Exception('Login reattempt user does align with current session state');
67 $lastLoginDetails = $this->getLastLoginAttemptDetails();
68 $this->login($user, $lastLoginDetails['method'], $lastLoginDetails['remember'] ?? false);
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.
76 public function getLastLoginAttemptUser(): ?User
78 $id = $this->getLastLoginAttemptDetails()['user_id'];
80 return User::query()->where('id', '=', $id)->first();
84 * Get the details of the last login attempt.
85 * Checks upon a ttl of about 1 hour since that last attempted login.
87 * @return array{user_id: ?string, method: ?string, remember: bool}
89 protected function getLastLoginAttemptDetails(): array
91 $value = session()->get(self::LAST_LOGIN_ATTEMPTED_SESSION_KEY);
93 return ['user_id' => null, 'method' => null];
96 [$id, $method, $remember, $time] = explode(':', $value);
97 $hourAgo = time() - (60 * 60);
98 if ($time < $hourAgo) {
99 $this->clearLastLoginAttempted();
101 return ['user_id' => null, 'method' => null];
104 return ['user_id' => $id, 'method' => $method, 'remember' => boolval($remember)];
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.
112 protected function setLastLoginAttemptedForUser(User $user, string $method, bool $remember)
115 self::LAST_LOGIN_ATTEMPTED_SESSION_KEY,
116 implode(':', [$user->id, $method, $remember, time()])
121 * Clear the last login attempted session value.
123 protected function clearLastLoginAttempted(): void
125 session()->remove(self::LAST_LOGIN_ATTEMPTED_SESSION_KEY);
129 * Check if MFA verification is needed.
131 public function needsMfaVerification(User $user): bool
133 return !$this->mfaSession->isVerifiedForUser($user) && $this->mfaSession->isRequiredForUser($user);
137 * Check if the given user is awaiting email confirmation.
139 public function awaitingEmailConfirmation(User $user): bool
141 return $this->emailConfirmationService->confirmationRequired() && !$user->email_confirmed;
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.
150 * @throws StoppedAuthenticationException
151 * @throws LoginAttemptException
153 public function attempt(array $credentials, string $method, bool $remember = false): bool
155 $result = auth()->attempt($credentials, $remember);
157 $user = auth()->user();
159 $this->login($user, $method, $remember);
166 * Logs the current user out of the application.
167 * Returns an app post-redirect path.
169 public function logout(): string
172 session()->invalidate();
173 session()->regenerateToken();
175 return $this->shouldAutoInitiate() ? '/login?prevent_auto_init=true' : '/';
179 * Check if login auto-initiate should be active based upon authentication config.
181 public function shouldAutoInitiate(): bool
183 $autoRedirect = config('auth.auto_initiate');
184 if (!$autoRedirect) {
188 $socialDrivers = $this->socialDriverManager->getActive();
189 $authMethod = config('auth.method');
191 return count($socialDrivers) === 0 && in_array($authMethod, ['oidc', 'saml2']);