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