]> BookStack Code Mirror - bookstack/blob - app/Auth/Access/LoginService.php
Added method for using enity ownership in relation queries
[bookstack] / app / Auth / Access / LoginService.php
1 <?php
2
3 namespace BookStack\Auth\Access;
4
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;
13 use Exception;
14
15 class LoginService
16 {
17     protected const LAST_LOGIN_ATTEMPTED_SESSION_KEY = 'auth-login-last-attempted';
18
19     protected $mfaSession;
20     protected $emailConfirmationService;
21
22     public function __construct(MfaSession $mfaSession, EmailConfirmationService $emailConfirmationService)
23     {
24         $this->mfaSession = $mfaSession;
25         $this->emailConfirmationService = $emailConfirmationService;
26     }
27
28     /**
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.
33      *
34      * @throws StoppedAuthenticationException
35      */
36     public function login(User $user, string $method, bool $remember = false): void
37     {
38         if ($this->awaitingEmailConfirmation($user) || $this->needsMfaVerification($user)) {
39             $this->setLastLoginAttemptedForUser($user, $method, $remember);
40
41             throw new StoppedAuthenticationException($user, $this);
42         }
43
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);
48
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);
54             }
55         }
56     }
57
58     /**
59      * Reattempt a system login after a previous stopped attempt.
60      *
61      * @throws Exception
62      */
63     public function reattemptLoginFor(User $user)
64     {
65         if ($user->id !== ($this->getLastLoginAttemptUser()->id ?? null)) {
66             throw new Exception('Login reattempt user does align with current session state');
67         }
68
69         $lastLoginDetails = $this->getLastLoginAttemptDetails();
70         $this->login($user, $lastLoginDetails['method'], $lastLoginDetails['remember'] ?? false);
71     }
72
73     /**
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.
77      */
78     public function getLastLoginAttemptUser(): ?User
79     {
80         $id = $this->getLastLoginAttemptDetails()['user_id'];
81
82         return User::query()->where('id', '=', $id)->first();
83     }
84
85     /**
86      * Get the details of the last login attempt.
87      * Checks upon a ttl of about 1 hour since that last attempted login.
88      *
89      * @return array{user_id: ?string, method: ?string, remember: bool}
90      */
91     protected function getLastLoginAttemptDetails(): array
92     {
93         $value = session()->get(self::LAST_LOGIN_ATTEMPTED_SESSION_KEY);
94         if (!$value) {
95             return ['user_id' => null, 'method' => null];
96         }
97
98         [$id, $method, $remember, $time] = explode(':', $value);
99         $hourAgo = time() - (60 * 60);
100         if ($time < $hourAgo) {
101             $this->clearLastLoginAttempted();
102
103             return ['user_id' => null, 'method' => null];
104         }
105
106         return ['user_id' => $id, 'method' => $method, 'remember' => boolval($remember)];
107     }
108
109     /**
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.
113      */
114     protected function setLastLoginAttemptedForUser(User $user, string $method, bool $remember)
115     {
116         session()->put(
117             self::LAST_LOGIN_ATTEMPTED_SESSION_KEY,
118             implode(':', [$user->id, $method, $remember, time()])
119         );
120     }
121
122     /**
123      * Clear the last login attempted session value.
124      */
125     protected function clearLastLoginAttempted(): void
126     {
127         session()->remove(self::LAST_LOGIN_ATTEMPTED_SESSION_KEY);
128     }
129
130     /**
131      * Check if MFA verification is needed.
132      */
133     public function needsMfaVerification(User $user): bool
134     {
135         return !$this->mfaSession->isVerifiedForUser($user) && $this->mfaSession->isRequiredForUser($user);
136     }
137
138     /**
139      * Check if the given user is awaiting email confirmation.
140      */
141     public function awaitingEmailConfirmation(User $user): bool
142     {
143         return $this->emailConfirmationService->confirmationRequired() && !$user->email_confirmed;
144     }
145
146     /**
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.
151      *
152      * @throws StoppedAuthenticationException
153      * @throws LoginAttemptException
154      */
155     public function attempt(array $credentials, string $method, bool $remember = false): bool
156     {
157         $result = auth()->attempt($credentials, $remember);
158         if ($result) {
159             $user = auth()->user();
160             auth()->logout();
161             $this->login($user, $method, $remember);
162         }
163
164         return $result;
165     }
166 }