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\LoginAttemptException;
9 use BookStack\Exceptions\StoppedAuthenticationException;
10 use BookStack\Facades\Activity;
11 use BookStack\Facades\Theme;
12 use BookStack\Theming\ThemeEvents;
17 protected const LAST_LOGIN_ATTEMPTED_SESSION_KEY = 'auth-login-last-attempted';
19 protected $mfaSession;
20 protected $emailConfirmationService;
22 public function __construct(MfaSession $mfaSession, EmailConfirmationService $emailConfirmationService)
24 $this->mfaSession = $mfaSession;
25 $this->emailConfirmationService = $emailConfirmationService;
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
36 public function login(User $user, string $method, bool $remember = false): void
38 if ($this->awaitingEmailConfirmation($user) || $this->needsMfaVerification($user)) {
39 $this->setLastLoginAttemptedForUser($user, $method, $remember);
41 throw new StoppedAuthenticationException($user, $this);
44 $this->clearLastLoginAttempted();
45 auth()->login($user, $remember);
46 Activity::add(ActivityType::AUTH_LOGIN, "{$method}; {$user->logDescriptor()}");
47 Theme::dispatch(ThemeEvents::AUTH_LOGIN, $method, $user);
49 // Authenticate on all session guards if a likely admin
50 if ($user->can('users-manage') && $user->can('user-roles-manage')) {
51 $guards = ['standard', 'ldap', 'saml2', 'oidc'];
52 foreach ($guards as $guard) {
53 auth($guard)->login($user);
59 * Reattempt a system login after a previous stopped attempt.
63 public function reattemptLoginFor(User $user)
65 if ($user->id !== ($this->getLastLoginAttemptUser()->id ?? null)) {
66 throw new Exception('Login reattempt user does align with current session state');
69 $lastLoginDetails = $this->getLastLoginAttemptDetails();
70 $this->login($user, $lastLoginDetails['method'], $lastLoginDetails['remember'] ?? false);
74 * Get the last user that was attempted to be logged in.
75 * Only exists if the last login attempt had correct credentials
76 * but had been prevented by a secondary factor.
78 public function getLastLoginAttemptUser(): ?User
80 $id = $this->getLastLoginAttemptDetails()['user_id'];
82 return User::query()->where('id', '=', $id)->first();
86 * Get the details of the last login attempt.
87 * Checks upon a ttl of about 1 hour since that last attempted login.
89 * @return array{user_id: ?string, method: ?string, remember: bool}
91 protected function getLastLoginAttemptDetails(): array
93 $value = session()->get(self::LAST_LOGIN_ATTEMPTED_SESSION_KEY);
95 return ['user_id' => null, 'method' => null];
98 [$id, $method, $remember, $time] = explode(':', $value);
99 $hourAgo = time() - (60 * 60);
100 if ($time < $hourAgo) {
101 $this->clearLastLoginAttempted();
103 return ['user_id' => null, 'method' => null];
106 return ['user_id' => $id, 'method' => $method, 'remember' => boolval($remember)];
110 * Set the last login attempted user.
111 * Must be only used when credentials are correct and a login could be
112 * achieved but a secondary factor has stopped the login.
114 protected function setLastLoginAttemptedForUser(User $user, string $method, bool $remember)
117 self::LAST_LOGIN_ATTEMPTED_SESSION_KEY,
118 implode(':', [$user->id, $method, $remember, time()])
123 * Clear the last login attempted session value.
125 protected function clearLastLoginAttempted(): void
127 session()->remove(self::LAST_LOGIN_ATTEMPTED_SESSION_KEY);
131 * Check if MFA verification is needed.
133 public function needsMfaVerification(User $user): bool
135 return !$this->mfaSession->isVerifiedForUser($user) && $this->mfaSession->isRequiredForUser($user);
139 * Check if the given user is awaiting email confirmation.
141 public function awaitingEmailConfirmation(User $user): bool
143 return $this->emailConfirmationService->confirmationRequired() && !$user->email_confirmed;
147 * Attempt the login of a user using the given credentials.
148 * Meant to mirror Laravel's default guard 'attempt' method
149 * but in a manner that always routes through our login system.
150 * May interrupt the flow if extra authentication requirements are imposed.
152 * @throws StoppedAuthenticationException
153 * @throws LoginAttemptException
155 public function attempt(array $credentials, string $method, bool $remember = false): bool
157 $result = auth()->attempt($credentials, $remember);
159 $user = auth()->user();
161 $this->login($user, $method, $remember);