]> BookStack Code Mirror - bookstack/blob - app/Http/Controllers/Auth/RegisterController.php
Add Carbon localization support
[bookstack] / app / Http / Controllers / Auth / RegisterController.php
1 <?php
2
3 namespace BookStack\Http\Controllers\Auth;
4
5 use BookStack\Exceptions\ConfirmationEmailException;
6 use BookStack\Exceptions\UserRegistrationException;
7 use BookStack\Repos\UserRepo;
8 use BookStack\Services\EmailConfirmationService;
9 use BookStack\Services\SocialAuthService;
10 use BookStack\User;
11 use Exception;
12 use Illuminate\Http\Request;
13 use Illuminate\Http\Response;
14 use Validator;
15 use BookStack\Http\Controllers\Controller;
16 use Illuminate\Foundation\Auth\RegistersUsers;
17
18 class RegisterController extends Controller
19 {
20     /*
21     |--------------------------------------------------------------------------
22     | Register Controller
23     |--------------------------------------------------------------------------
24     |
25     | This controller handles the registration of new users as well as their
26     | validation and creation. By default this controller uses a trait to
27     | provide this functionality without requiring any additional code.
28     |
29     */
30
31     use RegistersUsers;
32
33     protected $socialAuthService;
34     protected $emailConfirmationService;
35     protected $userRepo;
36
37     /**
38      * Where to redirect users after login / registration.
39      *
40      * @var string
41      */
42     protected $redirectTo = '/';
43     protected $redirectPath = '/';
44
45     /**
46      * Create a new controller instance.
47      *
48      * @param SocialAuthService $socialAuthService
49      * @param EmailConfirmationService $emailConfirmationService
50      * @param UserRepo $userRepo
51      */
52     public function __construct(SocialAuthService $socialAuthService, EmailConfirmationService $emailConfirmationService, UserRepo $userRepo)
53     {
54         $this->middleware('guest')->except(['socialCallback', 'detachSocialAccount']);
55         $this->socialAuthService = $socialAuthService;
56         $this->emailConfirmationService = $emailConfirmationService;
57         $this->userRepo = $userRepo;
58         $this->redirectTo = baseUrl('/');
59         $this->redirectPath = baseUrl('/');
60         parent::__construct();
61     }
62
63     /**
64      * Get a validator for an incoming registration request.
65      *
66      * @param  array $data
67      * @return \Illuminate\Contracts\Validation\Validator
68      */
69     protected function validator(array $data)
70     {
71         return Validator::make($data, [
72             'name' => 'required|max:255',
73             'email' => 'required|email|max:255|unique:users',
74             'password' => 'required|min:6',
75         ]);
76     }
77
78     /**
79      * Check whether or not registrations are allowed in the app settings.
80      * @throws UserRegistrationException
81      */
82     protected function checkRegistrationAllowed()
83     {
84         if (!setting('registration-enabled')) {
85             throw new UserRegistrationException('Registrations are currently disabled.', '/login');
86         }
87     }
88
89     /**
90      * Show the application registration form.
91      * @return Response
92      */
93     public function getRegister()
94     {
95         $this->checkRegistrationAllowed();
96         $socialDrivers = $this->socialAuthService->getActiveDrivers();
97         return view('auth.register', ['socialDrivers' => $socialDrivers]);
98     }
99
100     /**
101      * Handle a registration request for the application.
102      * @param Request|\Illuminate\Http\Request $request
103      * @return Response
104      * @throws UserRegistrationException
105      * @throws \Illuminate\Foundation\Validation\ValidationException
106      */
107     public function postRegister(Request $request)
108     {
109         $this->checkRegistrationAllowed();
110         $validator = $this->validator($request->all());
111
112         if ($validator->fails()) {
113             $this->throwValidationException(
114                 $request, $validator
115             );
116         }
117
118         $userData = $request->all();
119         return $this->registerUser($userData);
120     }
121
122     /**
123      * Create a new user instance after a valid registration.
124      * @param  array  $data
125      * @return User
126      */
127     protected function create(array $data)
128     {
129         return User::create([
130             'name' => $data['name'],
131             'email' => $data['email'],
132             'password' => bcrypt($data['password']),
133         ]);
134     }
135
136     /**
137      * The registrations flow for all users.
138      * @param array $userData
139      * @param bool|false|SocialAccount $socialAccount
140      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
141      * @throws UserRegistrationException
142      * @throws ConfirmationEmailException
143      */
144     protected function registerUser(array $userData, $socialAccount = false)
145     {
146         if (setting('registration-restrict')) {
147             $restrictedEmailDomains = explode(',', str_replace(' ', '', setting('registration-restrict')));
148             $userEmailDomain = $domain = substr(strrchr($userData['email'], "@"), 1);
149             if (!in_array($userEmailDomain, $restrictedEmailDomains)) {
150                 throw new UserRegistrationException('That email domain does not have access to this application', '/register');
151             }
152         }
153
154         $newUser = $this->userRepo->registerNew($userData);
155         if ($socialAccount) {
156             $newUser->socialAccounts()->save($socialAccount);
157         }
158
159         if (setting('registration-confirmation') || setting('registration-restrict')) {
160             $newUser->save();
161
162             try {
163                 $this->emailConfirmationService->sendConfirmation($newUser);
164             } catch (Exception $e) {
165                 session()->flash('error', trans('auth.email_confirm_send_error'));
166             }
167
168             return redirect('/register/confirm');
169         }
170
171         auth()->login($newUser);
172         session()->flash('success', 'Thanks for signing up! You are now registered and signed in.');
173         return redirect($this->redirectPath());
174     }
175
176     /**
177      * Show the page to tell the user to check their email
178      * and confirm their address.
179      */
180     public function getRegisterConfirmation()
181     {
182         return view('auth/register-confirm');
183     }
184
185     /**
186      * Confirms an email via a token and logs the user into the system.
187      * @param $token
188      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
189      * @throws UserRegistrationException
190      */
191     public function confirmEmail($token)
192     {
193         $confirmation = $this->emailConfirmationService->getEmailConfirmationFromToken($token);
194         $user = $confirmation->user;
195         $user->email_confirmed = true;
196         $user->save();
197         auth()->login($user);
198         session()->flash('success', trans('auth.email_confirm_success'));
199         $this->emailConfirmationService->deleteConfirmationsByUser($user);
200         return redirect($this->redirectPath);
201     }
202
203     /**
204      * Shows a notice that a user's email address has not been confirmed,
205      * Also has the option to re-send the confirmation email.
206      * @return \Illuminate\View\View
207      */
208     public function showAwaitingConfirmation()
209     {
210         return view('auth/user-unconfirmed');
211     }
212
213     /**
214      * Resend the confirmation email
215      * @param Request $request
216      * @return \Illuminate\View\View
217      */
218     public function resendConfirmation(Request $request)
219     {
220         $this->validate($request, [
221             'email' => 'required|email|exists:users,email'
222         ]);
223         $user = $this->userRepo->getByEmail($request->get('email'));
224
225         try {
226             $this->emailConfirmationService->sendConfirmation($user);
227         } catch (Exception $e) {
228             session()->flash('error', trans('auth.email_confirm_send_error'));
229             return redirect('/register/confirm');
230         }
231
232         $this->emailConfirmationService->sendConfirmation($user);
233         session()->flash('success', trans('auth.email_confirm_resent'));
234         return redirect('/register/confirm');
235     }
236
237     /**
238      * Redirect to the social site for authentication intended to register.
239      * @param $socialDriver
240      * @return mixed
241      */
242     public function socialRegister($socialDriver)
243     {
244         $this->checkRegistrationAllowed();
245         session()->put('social-callback', 'register');
246         return $this->socialAuthService->startRegister($socialDriver);
247     }
248
249     /**
250      * The callback for social login services.
251      * @param $socialDriver
252      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
253      * @throws SocialSignInException
254      */
255     public function socialCallback($socialDriver)
256     {
257         if (session()->has('social-callback')) {
258             $action = session()->pull('social-callback');
259             if ($action == 'login') {
260                 return $this->socialAuthService->handleLoginCallback($socialDriver);
261             } elseif ($action == 'register') {
262                 return $this->socialRegisterCallback($socialDriver);
263             }
264         } else {
265             throw new SocialSignInException('No action defined', '/login');
266         }
267         return redirect()->back();
268     }
269
270     /**
271      * Detach a social account from a user.
272      * @param $socialDriver
273      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
274      */
275     public function detachSocialAccount($socialDriver)
276     {
277         return $this->socialAuthService->detachSocialAccount($socialDriver);
278     }
279
280     /**
281      * Register a new user after a registration callback.
282      * @param $socialDriver
283      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
284      * @throws UserRegistrationException
285      */
286     protected function socialRegisterCallback($socialDriver)
287     {
288         $socialUser = $this->socialAuthService->handleRegistrationCallback($socialDriver);
289         $socialAccount = $this->socialAuthService->fillSocialAccount($socialDriver, $socialUser);
290
291         // Create an array of the user data to create a new user instance
292         $userData = [
293             'name' => $socialUser->getName(),
294             'email' => $socialUser->getEmail(),
295             'password' => str_random(30)
296         ];
297         return $this->registerUser($userData, $socialAccount);
298     }
299
300 }