3 namespace BookStack\Auth\Access;
5 use BookStack\Actions\ActivityType;
6 use BookStack\Auth\Access\Mfa\MfaSession;
7 use BookStack\Auth\User;
8 use BookStack\Exceptions\StoppedAuthenticationException;
9 use BookStack\Facades\Activity;
10 use BookStack\Facades\Theme;
11 use BookStack\Theming\ThemeEvents;
16 protected const LAST_LOGIN_ATTEMPTED_SESSION_KEY = 'auth-login-last-attempted';
18 protected $mfaSession;
19 protected $emailConfirmationService;
21 public function __construct(MfaSession $mfaSession, EmailConfirmationService $emailConfirmationService)
23 $this->mfaSession = $mfaSession;
24 $this->emailConfirmationService = $emailConfirmationService;
28 * Log the given user into the system.
29 * Will start a login of the given user but will prevent if there's
30 * a reason to (MFA or Unconfirmed Email).
31 * Returns a boolean to indicate the current login result.
33 * @throws StoppedAuthenticationException
35 public function login(User $user, string $method, bool $remember = false): void
37 if ($this->awaitingEmailConfirmation($user) || $this->needsMfaVerification($user)) {
38 $this->setLastLoginAttemptedForUser($user, $method, $remember);
40 throw new StoppedAuthenticationException($user, $this);
43 $this->clearLastLoginAttempted();
44 auth()->login($user, $remember);
45 Activity::add(ActivityType::AUTH_LOGIN, "{$method}; {$user->logDescriptor()}");
46 Theme::dispatch(ThemeEvents::AUTH_LOGIN, $method, $user);
48 // Authenticate on all session guards if a likely admin
49 if ($user->can('users-manage') && $user->can('user-roles-manage')) {
50 $guards = ['standard', 'ldap', 'saml2'];
51 foreach ($guards as $guard) {
52 auth($guard)->login($user);
58 * Reattempt a system login after a previous stopped attempt.
62 public function reattemptLoginFor(User $user)
64 if ($user->id !== ($this->getLastLoginAttemptUser()->id ?? null)) {
65 throw new Exception('Login reattempt user does align with current session state');
68 $lastLoginDetails = $this->getLastLoginAttemptDetails();
69 $this->login($user, $lastLoginDetails['method'], $lastLoginDetails['remember'] ?? false);
73 * Get the last user that was attempted to be logged in.
74 * Only exists if the last login attempt had correct credentials
75 * but had been prevented by a secondary factor.
77 public function getLastLoginAttemptUser(): ?User
79 $id = $this->getLastLoginAttemptDetails()['user_id'];
81 return User::query()->where('id', '=', $id)->first();
85 * Get the details of the last login attempt.
86 * Checks upon a ttl of about 1 hour since that last attempted login.
88 * @return array{user_id: ?string, method: ?string, remember: bool}
90 protected function getLastLoginAttemptDetails(): array
92 $value = session()->get(self::LAST_LOGIN_ATTEMPTED_SESSION_KEY);
94 return ['user_id' => null, 'method' => null];
97 [$id, $method, $remember, $time] = explode(':', $value);
98 $hourAgo = time() - (60 * 60);
99 if ($time < $hourAgo) {
100 $this->clearLastLoginAttempted();
102 return ['user_id' => null, 'method' => null];
105 return ['user_id' => $id, 'method' => $method, 'remember' => boolval($remember)];
109 * Set the last login attempted user.
110 * Must be only used when credentials are correct and a login could be
111 * achieved but a secondary factor has stopped the login.
113 protected function setLastLoginAttemptedForUser(User $user, string $method, bool $remember)
116 self::LAST_LOGIN_ATTEMPTED_SESSION_KEY,
117 implode(':', [$user->id, $method, $remember, time()])
122 * Clear the last login attempted session value.
124 protected function clearLastLoginAttempted(): void
126 session()->remove(self::LAST_LOGIN_ATTEMPTED_SESSION_KEY);
130 * Check if MFA verification is needed.
132 public function needsMfaVerification(User $user): bool
134 return !$this->mfaSession->isVerifiedForUser($user) && $this->mfaSession->isRequiredForUser($user);
138 * Check if the given user is awaiting email confirmation.
140 public function awaitingEmailConfirmation(User $user): bool
142 return $this->emailConfirmationService->confirmationRequired() && !$user->email_confirmed;
146 * Attempt the login of a user using the given credentials.
147 * Meant to mirror Laravel's default guard 'attempt' method
148 * but in a manner that always routes through our login system.
149 * May interrupt the flow if extra authentication requirements are imposed.
151 * @throws StoppedAuthenticationException
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);