3 namespace BookStack\Http\Controllers\Auth;
5 use BookStack\Auth\Access\EmailConfirmationService;
6 use BookStack\Auth\Access\SocialAuthService;
7 use BookStack\Auth\SocialAccount;
8 use BookStack\Auth\User;
9 use BookStack\Auth\UserRepo;
10 use BookStack\Exceptions\ConfirmationEmailException;
11 use BookStack\Exceptions\SocialDriverNotConfigured;
12 use BookStack\Exceptions\SocialSignInAccountNotUsed;
13 use BookStack\Exceptions\SocialSignInException;
14 use BookStack\Exceptions\UserRegistrationException;
15 use BookStack\Exceptions\UserTokenExpiredException;
16 use BookStack\Exceptions\UserTokenNotFoundException;
17 use BookStack\Http\Controllers\Controller;
19 use Illuminate\Foundation\Auth\RegistersUsers;
20 use Illuminate\Http\RedirectResponse;
21 use Illuminate\Http\Request;
22 use Illuminate\Http\Response;
23 use Illuminate\Routing\Redirector;
24 use Illuminate\View\View;
25 use Laravel\Socialite\Contracts\User as SocialUser;
28 class RegisterController extends Controller
31 |--------------------------------------------------------------------------
33 |--------------------------------------------------------------------------
35 | This controller handles the registration of new users as well as their
36 | validation and creation. By default this controller uses a trait to
37 | provide this functionality without requiring any additional code.
43 protected $socialAuthService;
44 protected $emailConfirmationService;
48 * Where to redirect users after login / registration.
52 protected $redirectTo = '/';
53 protected $redirectPath = '/';
56 * Create a new controller instance.
58 * @param SocialAuthService $socialAuthService
59 * @param \BookStack\Auth\EmailConfirmationService $emailConfirmationService
60 * @param UserRepo $userRepo
62 public function __construct(SocialAuthService $socialAuthService, EmailConfirmationService $emailConfirmationService, UserRepo $userRepo)
64 $this->middleware('guest')->only(['getRegister', 'postRegister', 'socialRegister']);
65 $this->socialAuthService = $socialAuthService;
66 $this->emailConfirmationService = $emailConfirmationService;
67 $this->userRepo = $userRepo;
68 $this->redirectTo = url('/');
69 $this->redirectPath = url('/');
70 parent::__construct();
74 * Get a validator for an incoming registration request.
77 * @return \Illuminate\Contracts\Validation\Validator
79 protected function validator(array $data)
81 return Validator::make($data, [
82 'name' => 'required|min:2|max:255',
83 'email' => 'required|email|max:255|unique:users',
84 'password' => 'required|min:6',
89 * Check whether or not registrations are allowed in the app settings.
90 * @throws UserRegistrationException
92 protected function checkRegistrationAllowed()
94 if (!setting('registration-enabled')) {
95 throw new UserRegistrationException(trans('auth.registrations_disabled'), '/login');
100 * Show the application registration form.
102 * @throws UserRegistrationException
104 public function getRegister()
106 $this->checkRegistrationAllowed();
107 $socialDrivers = $this->socialAuthService->getActiveDrivers();
108 return view('auth.register', ['socialDrivers' => $socialDrivers]);
112 * Handle a registration request for the application.
113 * @param Request|Request $request
114 * @return RedirectResponse|Redirector
115 * @throws UserRegistrationException
117 public function postRegister(Request $request)
119 $this->checkRegistrationAllowed();
120 $this->validator($request->all())->validate();
122 $userData = $request->all();
123 return $this->registerUser($userData);
127 * Create a new user instance after a valid registration.
131 protected function create(array $data)
133 return User::create([
134 'name' => $data['name'],
135 'email' => $data['email'],
136 'password' => bcrypt($data['password']),
141 * The registrations flow for all users.
142 * @param array $userData
143 * @param bool|false|SocialAccount $socialAccount
144 * @param bool $emailVerified
145 * @return RedirectResponse|Redirector
146 * @throws UserRegistrationException
148 protected function registerUser(array $userData, $socialAccount = false, $emailVerified = false)
150 $registrationRestrict = setting('registration-restrict');
152 if ($registrationRestrict) {
153 $restrictedEmailDomains = explode(',', str_replace(' ', '', $registrationRestrict));
154 $userEmailDomain = $domain = mb_substr(mb_strrchr($userData['email'], "@"), 1);
155 if (!in_array($userEmailDomain, $restrictedEmailDomains)) {
156 throw new UserRegistrationException(trans('auth.registration_email_domain_invalid'), '/register');
160 $newUser = $this->userRepo->registerNew($userData, $emailVerified);
161 if ($socialAccount) {
162 $newUser->socialAccounts()->save($socialAccount);
165 if ((setting('registration-confirmation') || $registrationRestrict) && !$emailVerified) {
169 $this->emailConfirmationService->sendConfirmation($newUser);
170 } catch (Exception $e) {
171 session()->flash('error', trans('auth.email_confirm_send_error'));
174 return redirect('/register/confirm');
177 auth()->login($newUser);
178 session()->flash('success', trans('auth.register_success'));
179 return redirect($this->redirectPath());
183 * Show the page to tell the user to check their email
184 * and confirm their address.
186 public function getRegisterConfirmation()
188 return view('auth.register-confirm');
192 * Confirms an email via a token and logs the user into the system.
194 * @return RedirectResponse|Redirector
195 * @throws ConfirmationEmailException
198 public function confirmEmail($token)
201 $userId = $this->emailConfirmationService->checkTokenAndGetUserId($token);
202 } catch (Exception $exception) {
204 if ($exception instanceof UserTokenNotFoundException) {
205 session()->flash('error', trans('errors.email_confirmation_invalid'));
206 return redirect('/register');
209 if ($exception instanceof UserTokenExpiredException) {
210 $user = $this->userRepo->getById($exception->userId);
211 $this->emailConfirmationService->sendConfirmation($user);
212 session()->flash('error', trans('errors.email_confirmation_expired'));
213 return redirect('/register/confirm');
219 $user = $this->userRepo->getById($userId);
220 $user->email_confirmed = true;
223 auth()->login($user);
224 session()->flash('success', trans('auth.email_confirm_success'));
225 $this->emailConfirmationService->deleteByUser($user);
227 return redirect($this->redirectPath);
231 * Shows a notice that a user's email address has not been confirmed,
232 * Also has the option to re-send the confirmation email.
235 public function showAwaitingConfirmation()
237 return view('auth.user-unconfirmed');
241 * Resend the confirmation email
242 * @param Request $request
245 public function resendConfirmation(Request $request)
247 $this->validate($request, [
248 'email' => 'required|email|exists:users,email'
250 $user = $this->userRepo->getByEmail($request->get('email'));
253 $this->emailConfirmationService->sendConfirmation($user);
254 } catch (Exception $e) {
255 session()->flash('error', trans('auth.email_confirm_send_error'));
256 return redirect('/register/confirm');
259 session()->flash('success', trans('auth.email_confirm_resent'));
260 return redirect('/register/confirm');
264 * Redirect to the social site for authentication intended to register.
265 * @param $socialDriver
267 * @throws UserRegistrationException
268 * @throws SocialDriverNotConfigured
270 public function socialRegister($socialDriver)
272 $this->checkRegistrationAllowed();
273 session()->put('social-callback', 'register');
274 return $this->socialAuthService->startRegister($socialDriver);
278 * The callback for social login services.
279 * @param $socialDriver
280 * @param Request $request
281 * @return RedirectResponse|Redirector
282 * @throws SocialSignInException
283 * @throws UserRegistrationException
284 * @throws SocialDriverNotConfigured
286 public function socialCallback($socialDriver, Request $request)
288 if (!session()->has('social-callback')) {
289 throw new SocialSignInException(trans('errors.social_no_action_defined'), '/login');
292 // Check request for error information
293 if ($request->has('error') && $request->has('error_description')) {
294 throw new SocialSignInException(trans('errors.social_login_bad_response', [
295 'socialAccount' => $socialDriver,
296 'error' => $request->get('error_description'),
300 $action = session()->pull('social-callback');
302 // Attempt login or fall-back to register if allowed.
303 $socialUser = $this->socialAuthService->getSocialUser($socialDriver);
304 if ($action == 'login') {
306 return $this->socialAuthService->handleLoginCallback($socialDriver, $socialUser);
307 } catch (SocialSignInAccountNotUsed $exception) {
308 if ($this->socialAuthService->driverAutoRegisterEnabled($socialDriver)) {
309 return $this->socialRegisterCallback($socialDriver, $socialUser);
315 if ($action == 'register') {
316 return $this->socialRegisterCallback($socialDriver, $socialUser);
319 return redirect()->back();
323 * Detach a social account from a user.
324 * @param $socialDriver
325 * @return RedirectResponse|Redirector
327 public function detachSocialAccount($socialDriver)
329 return $this->socialAuthService->detachSocialAccount($socialDriver);
333 * Register a new user after a registration callback.
334 * @param string $socialDriver
335 * @param SocialUser $socialUser
336 * @return RedirectResponse|Redirector
337 * @throws UserRegistrationException
339 protected function socialRegisterCallback(string $socialDriver, SocialUser $socialUser)
341 $socialUser = $this->socialAuthService->handleRegistrationCallback($socialDriver, $socialUser);
342 $socialAccount = $this->socialAuthService->fillSocialAccount($socialDriver, $socialUser);
343 $emailVerified = $this->socialAuthService->driverAutoConfirmEmailEnabled($socialDriver);
345 // Create an array of the user data to create a new user instance
347 'name' => $socialUser->getName(),
348 'email' => $socialUser->getEmail(),
349 'password' => str_random(30)
351 return $this->registerUser($userData, $socialAccount, $emailVerified);