3 namespace BookStack\Http\Controllers\Auth;
5 use BookStack\Exceptions\AuthException;
6 use BookStack\Exceptions\PrettyException;
7 use Illuminate\Contracts\Auth\Authenticatable;
8 use Illuminate\Http\Request;
9 use BookStack\Exceptions\SocialSignInException;
10 use BookStack\Exceptions\UserRegistrationException;
11 use BookStack\Repos\UserRepo;
12 use BookStack\Services\EmailConfirmationService;
13 use BookStack\Services\SocialAuthService;
14 use BookStack\SocialAccount;
16 use BookStack\Http\Controllers\Controller;
17 use Illuminate\Foundation\Auth\ThrottlesLogins;
18 use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
20 class AuthController extends Controller
23 |--------------------------------------------------------------------------
24 | Registration & Login Controller
25 |--------------------------------------------------------------------------
27 | This controller handles the registration of new users, as well as the
28 | authentication of existing users. By default, this controller uses
29 | a simple trait to add these behaviors. Why don't you explore it?
33 use AuthenticatesAndRegistersUsers, ThrottlesLogins;
35 protected $redirectPath = '/';
36 protected $redirectAfterLogout = '/login';
37 protected $username = 'email';
40 protected $socialAuthService;
41 protected $emailConfirmationService;
45 * Create a new authentication controller instance.
46 * @param SocialAuthService $socialAuthService
47 * @param EmailConfirmationService $emailConfirmationService
48 * @param UserRepo $userRepo
50 public function __construct(SocialAuthService $socialAuthService, EmailConfirmationService $emailConfirmationService, UserRepo $userRepo)
52 $this->middleware('guest', ['only' => ['getLogin', 'postLogin', 'getRegister', 'postRegister']]);
53 $this->socialAuthService = $socialAuthService;
54 $this->emailConfirmationService = $emailConfirmationService;
55 $this->userRepo = $userRepo;
56 $this->username = config('auth.method') === 'standard' ? 'email' : 'username';
57 parent::__construct();
61 * Get a validator for an incoming registration request.
63 * @return \Illuminate\Contracts\Validation\Validator
65 protected function validator(array $data)
67 return Validator::make($data, [
68 'name' => 'required|max:255',
69 'email' => 'required|email|max:255|unique:users',
70 'password' => 'required|min:6',
74 protected function checkRegistrationAllowed()
76 if (!setting('registration-enabled')) {
77 throw new UserRegistrationException('Registrations are currently disabled.', '/login');
82 * Show the application registration form.
83 * @return \Illuminate\Http\Response
85 public function getRegister()
87 $this->checkRegistrationAllowed();
88 $socialDrivers = $this->socialAuthService->getActiveDrivers();
89 return view('auth.register', ['socialDrivers' => $socialDrivers]);
93 * Handle a registration request for the application.
94 * @param \Illuminate\Http\Request $request
95 * @return \Illuminate\Http\Response
96 * @throws UserRegistrationException
98 public function postRegister(Request $request)
100 $this->checkRegistrationAllowed();
101 $validator = $this->validator($request->all());
103 if ($validator->fails()) {
104 $this->throwValidationException(
109 $userData = $request->all();
110 return $this->registerUser($userData);
115 * Overrides the action when a user is authenticated.
116 * If the user authenticated but does not exist in the user table we create them.
117 * @param Request $request
118 * @param Authenticatable $user
119 * @return \Illuminate\Http\RedirectResponse
120 * @throws AuthException
122 protected function authenticated(Request $request, Authenticatable $user)
124 // Explicitly log them out for now if they do no exist.
125 if (!$user->exists) auth()->logout($user);
127 if (!$user->exists && $user->email === null && !$request->has('email')) {
129 session()->flash('request-email', true);
130 return redirect('/login');
133 if (!$user->exists && $user->email === null && $request->has('email')) {
134 $user->email = $request->get('email');
137 if (!$user->exists) {
139 // Check for users with same email already
140 $alreadyUser = $user->newQuery()->where('email', '=', $user->email)->count() > 0;
142 throw new AuthException('A user with the email ' . $user->email . ' already exists but with different credentials.');
146 $this->userRepo->attachDefaultRole($user);
147 auth()->login($user);
150 return redirect()->intended($this->redirectPath());
154 * Register a new user after a registration callback.
155 * @param $socialDriver
156 * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
157 * @throws UserRegistrationException
159 protected function socialRegisterCallback($socialDriver)
161 $socialUser = $this->socialAuthService->handleRegistrationCallback($socialDriver);
162 $socialAccount = $this->socialAuthService->fillSocialAccount($socialDriver, $socialUser);
164 // Create an array of the user data to create a new user instance
166 'name' => $socialUser->getName(),
167 'email' => $socialUser->getEmail(),
168 'password' => str_random(30)
170 return $this->registerUser($userData, $socialAccount);
174 * The registrations flow for all users.
175 * @param array $userData
176 * @param bool|false|SocialAccount $socialAccount
177 * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
178 * @throws UserRegistrationException
179 * @throws \BookStack\Exceptions\ConfirmationEmailException
181 protected function registerUser(array $userData, $socialAccount = false)
183 if (setting('registration-restrict')) {
184 $restrictedEmailDomains = explode(',', str_replace(' ', '', setting('registration-restrict')));
185 $userEmailDomain = $domain = substr(strrchr($userData['email'], "@"), 1);
186 if (!in_array($userEmailDomain, $restrictedEmailDomains)) {
187 throw new UserRegistrationException('That email domain does not have access to this application', '/register');
191 $newUser = $this->userRepo->registerNew($userData);
192 if ($socialAccount) {
193 $newUser->socialAccounts()->save($socialAccount);
196 if (setting('registration-confirmation') || setting('registration-restrict')) {
198 $this->emailConfirmationService->sendConfirmation($newUser);
199 return redirect('/register/confirm');
202 auth()->login($newUser);
203 session()->flash('success', 'Thanks for signing up! You are now registered and signed in.');
204 return redirect($this->redirectPath());
208 * Show the page to tell the user to check their email
209 * and confirm their address.
211 public function getRegisterConfirmation()
213 return view('auth/register-confirm');
217 * View the confirmation email as a standard web page.
219 * @return \Illuminate\View\View
220 * @throws UserRegistrationException
222 public function viewConfirmEmail($token)
224 $confirmation = $this->emailConfirmationService->getEmailConfirmationFromToken($token);
225 return view('emails/email-confirmation', ['token' => $confirmation->token]);
229 * Confirms an email via a token and logs the user into the system.
231 * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
232 * @throws UserRegistrationException
234 public function confirmEmail($token)
236 $confirmation = $this->emailConfirmationService->getEmailConfirmationFromToken($token);
237 $user = $confirmation->user;
238 $user->email_confirmed = true;
240 auth()->login($confirmation->user);
241 session()->flash('success', 'Your email has been confirmed!');
242 $this->emailConfirmationService->deleteConfirmationsByUser($user);
243 return redirect($this->redirectPath);
247 * Shows a notice that a user's email address has not been confirmed,
248 * Also has the option to re-send the confirmation email.
249 * @return \Illuminate\View\View
251 public function showAwaitingConfirmation()
253 return view('auth/user-unconfirmed');
257 * Resend the confirmation email
258 * @param Request $request
259 * @return \Illuminate\View\View
261 public function resendConfirmation(Request $request)
263 $this->validate($request, [
264 'email' => 'required|email|exists:users,email'
266 $user = $this->userRepo->getByEmail($request->get('email'));
267 $this->emailConfirmationService->sendConfirmation($user);
268 session()->flash('success', 'Confirmation email resent, Please check your inbox.');
269 return redirect('/register/confirm');
273 * Show the application login form.
274 * @return \Illuminate\Http\Response
276 public function getLogin()
278 $socialDrivers = $this->socialAuthService->getActiveDrivers();
279 $authMethod = config('auth.method');
280 return view('auth/login', ['socialDrivers' => $socialDrivers, 'authMethod' => $authMethod]);
284 * Redirect to the relevant social site.
285 * @param $socialDriver
286 * @return \Symfony\Component\HttpFoundation\RedirectResponse
288 public function getSocialLogin($socialDriver)
290 session()->put('social-callback', 'login');
291 return $this->socialAuthService->startLogIn($socialDriver);
295 * Redirect to the social site for authentication intended to register.
296 * @param $socialDriver
299 public function socialRegister($socialDriver)
301 $this->checkRegistrationAllowed();
302 session()->put('social-callback', 'register');
303 return $this->socialAuthService->startRegister($socialDriver);
307 * The callback for social login services.
308 * @param $socialDriver
309 * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
310 * @throws SocialSignInException
312 public function socialCallback($socialDriver)
314 if (session()->has('social-callback')) {
315 $action = session()->pull('social-callback');
316 if ($action == 'login') {
317 return $this->socialAuthService->handleLoginCallback($socialDriver);
318 } elseif ($action == 'register') {
319 return $this->socialRegisterCallback($socialDriver);
322 throw new SocialSignInException('No action defined', '/login');
324 return redirect()->back();
328 * Detach a social account from a user.
329 * @param $socialDriver
330 * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
332 public function detachSocialAccount($socialDriver)
334 return $this->socialAuthService->detachSocialAccount($socialDriver);