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;
13 use phpDocumentor\Reflection\DocBlock\Tags\Method;
18 protected const LAST_LOGIN_ATTEMPTED_SESSION_KEY = 'auth-login-last-attempted';
20 protected $mfaSession;
22 public function __construct(MfaSession $mfaSession)
24 $this->mfaSession = $mfaSession;
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.
32 * @throws StoppedAuthenticationException
34 public function login(User $user, string $method): void
36 if ($this->awaitingEmailConfirmation($user) || $this->needsMfaVerification($user)) {
37 $this->setLastLoginAttemptedForUser($user, $method);
38 throw new StoppedAuthenticationException($user, $this);
39 // TODO - Does 'remember' still work? Probably not right now.
41 // TODO - Need to clear MFA sessions out upon logout
43 // Old MFA middleware todos:
45 // TODO - Handle email confirmation handling
46 // Left BookStack\Http\Middleware\Authenticate@emailConfirmationErrorResponse in which needs
47 // be removed as an example of old behaviour.
50 $this->clearLastLoginAttempted();
52 Activity::add(ActivityType::AUTH_LOGIN, "{$method}; {$user->logDescriptor()}");
53 Theme::dispatch(ThemeEvents::AUTH_LOGIN, $method, $user);
55 // Authenticate on all session guards if a likely admin
56 if ($user->can('users-manage') && $user->can('user-roles-manage')) {
57 $guards = ['standard', 'ldap', 'saml2'];
58 foreach ($guards as $guard) {
59 auth($guard)->login($user);
65 * Reattempt a system login after a previous stopped attempt.
68 public function reattemptLoginFor(User $user)
70 if ($user->id !== ($this->getLastLoginAttemptUser()->id ?? null)) {
71 throw new Exception('Login reattempt user does align with current session state');
74 $this->login($user, $this->getLastLoginAttemptMethod());
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'];
85 return User::query()->where('id', '=', $id)->first();
89 * Get the method for the last login attempt.
91 protected function getLastLoginAttemptMethod(): ?string
93 return $this->getLastLoginAttemptDetails()['method'];
97 * Get the details of the last login attempt.
98 * Checks upon a ttl of about 1 hour since that last attempted login.
99 * @return array{user_id: ?string, method: ?string}
101 protected function getLastLoginAttemptDetails(): array
103 $value = session()->get(self::LAST_LOGIN_ATTEMPTED_SESSION_KEY);
105 return ['user_id' => null, 'method' => null];
108 [$id, $method, $time] = explode(':', $value);
109 $hourAgo = time() - (60*60);
110 if ($time < $hourAgo) {
111 $this->clearLastLoginAttempted();
112 return ['user_id' => null, 'method' => null];
115 return ['user_id' => $id, 'method' => $method];
119 * Set the last login attempted user.
120 * Must be only used when credentials are correct and a login could be
121 * achieved but a secondary factor has stopped the login.
123 protected function setLastLoginAttemptedForUser(User $user, string $method)
126 self::LAST_LOGIN_ATTEMPTED_SESSION_KEY,
127 implode(':', [$user->id, $method, time()])
132 * Clear the last login attempted session value.
134 protected function clearLastLoginAttempted(): void
136 session()->remove(self::LAST_LOGIN_ATTEMPTED_SESSION_KEY);
140 * Check if MFA verification is needed.
142 public function needsMfaVerification(User $user): bool
144 return !$this->mfaSession->isVerifiedForUser($user) && $this->mfaSession->isRequiredForUser($user);
148 * Check if the given user is awaiting email confirmation.
150 public function awaitingEmailConfirmation(User $user): bool
152 $requireConfirmation = (setting('registration-confirmation') || setting('registration-restrict'));
153 return $requireConfirmation && !$user->email_confirmed;
157 * Attempt the login of a user using the given credentials.
158 * Meant to mirror Laravel's default guard 'attempt' method
159 * but in a manner that always routes through our login system.
160 * May interrupt the flow if extra authentication requirements are imposed.
162 * @throws StoppedAuthenticationException
164 public function attempt(array $credentials, string $method, bool $remember = false): bool
166 $result = auth()->attempt($credentials, $remember);
168 $user = auth()->user();
170 $this->login($user, $method);