1 <?php namespace BookStack\Http\Controllers\Auth;
3 use BookStack\Exceptions\AuthException;
4 use Illuminate\Contracts\Auth\Authenticatable;
5 use Illuminate\Http\Request;
6 use BookStack\Exceptions\SocialSignInException;
7 use BookStack\Exceptions\UserRegistrationException;
8 use BookStack\Repos\UserRepo;
9 use BookStack\Services\EmailConfirmationService;
10 use BookStack\Services\SocialAuthService;
11 use BookStack\SocialAccount;
13 use BookStack\Http\Controllers\Controller;
14 use Illuminate\Foundation\Auth\ThrottlesLogins;
15 use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
17 class AuthController extends Controller
20 |--------------------------------------------------------------------------
21 | Registration & Login Controller
22 |--------------------------------------------------------------------------
24 | This controller handles the registration of new users, as well as the
25 | authentication of existing users. By default, this controller uses
26 | a simple trait to add these behaviors. Why don't you explore it?
30 use AuthenticatesAndRegistersUsers, ThrottlesLogins;
32 protected $redirectPath = '/';
33 protected $redirectAfterLogout = '/login';
34 protected $username = 'email';
36 protected $socialAuthService;
37 protected $emailConfirmationService;
41 * Create a new authentication controller instance.
42 * @param SocialAuthService $socialAuthService
43 * @param EmailConfirmationService $emailConfirmationService
44 * @param UserRepo $userRepo
46 public function __construct(SocialAuthService $socialAuthService, EmailConfirmationService $emailConfirmationService, UserRepo $userRepo)
48 $this->middleware('guest', ['only' => ['getLogin', 'postLogin', 'getRegister', 'postRegister']]);
49 $this->socialAuthService = $socialAuthService;
50 $this->emailConfirmationService = $emailConfirmationService;
51 $this->userRepo = $userRepo;
52 $this->redirectPath = baseUrl('/');
53 $this->redirectAfterLogout = baseUrl('/login');
54 $this->username = config('auth.method') === 'standard' ? 'email' : 'username';
55 parent::__construct();
59 * Get a validator for an incoming registration request.
61 * @return \Illuminate\Contracts\Validation\Validator
63 protected function validator(array $data)
65 return Validator::make($data, [
66 'name' => 'required|max:255',
67 'email' => 'required|email|max:255|unique:users',
68 'password' => 'required|min:6',
72 protected function checkRegistrationAllowed()
74 if (!setting('registration-enabled')) {
75 throw new UserRegistrationException('Registrations are currently disabled.', '/login');
80 * Show the application registration form.
81 * @return \Illuminate\Http\Response
83 public function getRegister()
85 $this->checkRegistrationAllowed();
86 $socialDrivers = $this->socialAuthService->getActiveDrivers();
87 return view('auth.register', ['socialDrivers' => $socialDrivers]);
91 * Handle a registration request for the application.
92 * @param \Illuminate\Http\Request $request
93 * @return \Illuminate\Http\Response
94 * @throws UserRegistrationException
96 public function postRegister(Request $request)
98 $this->checkRegistrationAllowed();
99 $validator = $this->validator($request->all());
101 if ($validator->fails()) {
102 $this->throwValidationException(
107 $userData = $request->all();
108 return $this->registerUser($userData);
113 * Overrides the action when a user is authenticated.
114 * If the user authenticated but does not exist in the user table we create them.
115 * @param Request $request
116 * @param Authenticatable $user
117 * @return \Illuminate\Http\RedirectResponse
118 * @throws AuthException
120 protected function authenticated(Request $request, Authenticatable $user)
122 // Explicitly log them out for now if they do no exist.
123 if (!$user->exists) auth()->logout($user);
125 if (!$user->exists && $user->email === null && !$request->has('email')) {
127 session()->flash('request-email', true);
128 return redirect('/login');
131 if (!$user->exists && $user->email === null && $request->has('email')) {
132 $user->email = $request->get('email');
135 if (!$user->exists) {
137 // Check for users with same email already
138 $alreadyUser = $user->newQuery()->where('email', '=', $user->email)->count() > 0;
140 throw new AuthException('A user with the email ' . $user->email . ' already exists but with different credentials.');
144 $this->userRepo->attachDefaultRole($user);
145 auth()->login($user);
148 return redirect()->intended($this->redirectPath());
152 * Register a new user after a registration callback.
153 * @param $socialDriver
154 * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
155 * @throws UserRegistrationException
157 protected function socialRegisterCallback($socialDriver)
159 $socialUser = $this->socialAuthService->handleRegistrationCallback($socialDriver);
160 $socialAccount = $this->socialAuthService->fillSocialAccount($socialDriver, $socialUser);
162 // Create an array of the user data to create a new user instance
164 'name' => $socialUser->getName(),
165 'email' => $socialUser->getEmail(),
166 'password' => str_random(30)
168 return $this->registerUser($userData, $socialAccount);
172 * The registrations flow for all users.
173 * @param array $userData
174 * @param bool|false|SocialAccount $socialAccount
175 * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
176 * @throws UserRegistrationException
177 * @throws \BookStack\Exceptions\ConfirmationEmailException
179 protected function registerUser(array $userData, $socialAccount = false)
181 if (setting('registration-restrict')) {
182 $restrictedEmailDomains = explode(',', str_replace(' ', '', setting('registration-restrict')));
183 $userEmailDomain = $domain = substr(strrchr($userData['email'], "@"), 1);
184 if (!in_array($userEmailDomain, $restrictedEmailDomains)) {
185 throw new UserRegistrationException('That email domain does not have access to this application', '/register');
189 $newUser = $this->userRepo->registerNew($userData);
190 if ($socialAccount) {
191 $newUser->socialAccounts()->save($socialAccount);
194 if (setting('registration-confirmation') || setting('registration-restrict')) {
196 $this->emailConfirmationService->sendConfirmation($newUser);
197 return redirect('/register/confirm');
200 auth()->login($newUser);
201 session()->flash('success', 'Thanks for signing up! You are now registered and signed in.');
202 return redirect($this->redirectPath());
206 * Show the page to tell the user to check their email
207 * and confirm their address.
209 public function getRegisterConfirmation()
211 return view('auth/register-confirm');
215 * View the confirmation email as a standard web page.
217 * @return \Illuminate\View\View
218 * @throws UserRegistrationException
220 public function viewConfirmEmail($token)
222 $confirmation = $this->emailConfirmationService->getEmailConfirmationFromToken($token);
223 return view('emails/email-confirmation', ['token' => $confirmation->token]);
227 * Confirms an email via a token and logs the user into the system.
229 * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
230 * @throws UserRegistrationException
232 public function confirmEmail($token)
234 $confirmation = $this->emailConfirmationService->getEmailConfirmationFromToken($token);
235 $user = $confirmation->user;
236 $user->email_confirmed = true;
238 auth()->login($confirmation->user);
239 session()->flash('success', 'Your email has been confirmed!');
240 $this->emailConfirmationService->deleteConfirmationsByUser($user);
241 return redirect($this->redirectPath);
245 * Shows a notice that a user's email address has not been confirmed,
246 * Also has the option to re-send the confirmation email.
247 * @return \Illuminate\View\View
249 public function showAwaitingConfirmation()
251 return view('auth/user-unconfirmed');
255 * Resend the confirmation email
256 * @param Request $request
257 * @return \Illuminate\View\View
259 public function resendConfirmation(Request $request)
261 $this->validate($request, [
262 'email' => 'required|email|exists:users,email'
264 $user = $this->userRepo->getByEmail($request->get('email'));
265 $this->emailConfirmationService->sendConfirmation($user);
266 session()->flash('success', 'Confirmation email resent, Please check your inbox.');
267 return redirect('/register/confirm');
271 * Show the application login form.
272 * @return \Illuminate\Http\Response
274 public function getLogin()
276 $socialDrivers = $this->socialAuthService->getActiveDrivers();
277 $authMethod = config('auth.method');
278 return view('auth/login', ['socialDrivers' => $socialDrivers, 'authMethod' => $authMethod]);
282 * Redirect to the relevant social site.
283 * @param $socialDriver
284 * @return \Symfony\Component\HttpFoundation\RedirectResponse
286 public function getSocialLogin($socialDriver)
288 session()->put('social-callback', 'login');
289 return $this->socialAuthService->startLogIn($socialDriver);
293 * Redirect to the social site for authentication intended to register.
294 * @param $socialDriver
297 public function socialRegister($socialDriver)
299 $this->checkRegistrationAllowed();
300 session()->put('social-callback', 'register');
301 return $this->socialAuthService->startRegister($socialDriver);
305 * The callback for social login services.
306 * @param $socialDriver
307 * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
308 * @throws SocialSignInException
310 public function socialCallback($socialDriver)
312 if (session()->has('social-callback')) {
313 $action = session()->pull('social-callback');
314 if ($action == 'login') {
315 return $this->socialAuthService->handleLoginCallback($socialDriver);
316 } elseif ($action == 'register') {
317 return $this->socialRegisterCallback($socialDriver);
320 throw new SocialSignInException('No action defined', '/login');
322 return redirect()->back();
326 * Detach a social account from a user.
327 * @param $socialDriver
328 * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
330 public function detachSocialAccount($socialDriver)
332 return $this->socialAuthService->detachSocialAccount($socialDriver);