]> BookStack Code Mirror - bookstack/blob - app/Http/Controllers/Auth/RegisterController.php
Updated remaining views to 2017 design update.
[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')->except(['socialCallback', 'detachSocialAccount']);
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      */
95     public function getRegister()
96     {
97         $this->checkRegistrationAllowed();
98         $socialDrivers = $this->socialAuthService->getActiveDrivers();
99         return view('auth.register', ['socialDrivers' => $socialDrivers]);
100     }
101
102     /**
103      * Handle a registration request for the application.
104      * @param Request|\Illuminate\Http\Request $request
105      * @return Response
106      * @throws UserRegistrationException
107      * @throws \Illuminate\Validation\ValidationException
108      */
109     public function postRegister(Request $request)
110     {
111         $this->checkRegistrationAllowed();
112         $validator = $this->validator($request->all());
113
114         if ($validator->fails()) {
115             $this->throwValidationException(
116                 $request, $validator
117             );
118         }
119
120         $userData = $request->all();
121         return $this->registerUser($userData);
122     }
123
124     /**
125      * Create a new user instance after a valid registration.
126      * @param  array  $data
127      * @return User
128      */
129     protected function create(array $data)
130     {
131         return User::create([
132             'name' => $data['name'],
133             'email' => $data['email'],
134             'password' => bcrypt($data['password']),
135         ]);
136     }
137
138     /**
139      * The registrations flow for all users.
140      * @param array $userData
141      * @param bool|false|SocialAccount $socialAccount
142      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
143      * @throws UserRegistrationException
144      * @throws ConfirmationEmailException
145      */
146     protected function registerUser(array $userData, $socialAccount = false)
147     {
148         if (setting('registration-restrict')) {
149             $restrictedEmailDomains = explode(',', str_replace(' ', '', setting('registration-restrict')));
150             $userEmailDomain = $domain = substr(strrchr($userData['email'], "@"), 1);
151             if (!in_array($userEmailDomain, $restrictedEmailDomains)) {
152                 throw new UserRegistrationException(trans('auth.registration_email_domain_invalid'), '/register');
153             }
154         }
155
156         $newUser = $this->userRepo->registerNew($userData);
157         if ($socialAccount) {
158             $newUser->socialAccounts()->save($socialAccount);
159         }
160
161         if (setting('registration-confirmation') || setting('registration-restrict')) {
162             $newUser->save();
163
164             try {
165                 $this->emailConfirmationService->sendConfirmation($newUser);
166             } catch (Exception $e) {
167                 session()->flash('error', trans('auth.email_confirm_send_error'));
168             }
169
170             return redirect('/register/confirm');
171         }
172
173         auth()->login($newUser);
174         session()->flash('success', trans('auth.register_success'));
175         return redirect($this->redirectPath());
176     }
177
178     /**
179      * Show the page to tell the user to check their email
180      * and confirm their address.
181      */
182     public function getRegisterConfirmation()
183     {
184         return view('auth/register-confirm');
185     }
186
187     /**
188      * Confirms an email via a token and logs the user into the system.
189      * @param $token
190      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
191      * @throws UserRegistrationException
192      */
193     public function confirmEmail($token)
194     {
195         $confirmation = $this->emailConfirmationService->getEmailConfirmationFromToken($token);
196         $user = $confirmation->user;
197         $user->email_confirmed = true;
198         $user->save();
199         auth()->login($user);
200         session()->flash('success', trans('auth.email_confirm_success'));
201         $this->emailConfirmationService->deleteConfirmationsByUser($user);
202         return redirect($this->redirectPath);
203     }
204
205     /**
206      * Shows a notice that a user's email address has not been confirmed,
207      * Also has the option to re-send the confirmation email.
208      * @return \Illuminate\View\View
209      */
210     public function showAwaitingConfirmation()
211     {
212         return view('auth/user-unconfirmed');
213     }
214
215     /**
216      * Resend the confirmation email
217      * @param Request $request
218      * @return \Illuminate\View\View
219      */
220     public function resendConfirmation(Request $request)
221     {
222         $this->validate($request, [
223             'email' => 'required|email|exists:users,email'
224         ]);
225         $user = $this->userRepo->getByEmail($request->get('email'));
226
227         try {
228             $this->emailConfirmationService->sendConfirmation($user);
229         } catch (Exception $e) {
230             session()->flash('error', trans('auth.email_confirm_send_error'));
231             return redirect('/register/confirm');
232         }
233
234         session()->flash('success', trans('auth.email_confirm_resent'));
235         return redirect('/register/confirm');
236     }
237
238     /**
239      * Redirect to the social site for authentication intended to register.
240      * @param $socialDriver
241      * @return mixed
242      */
243     public function socialRegister($socialDriver)
244     {
245         $this->checkRegistrationAllowed();
246         session()->put('social-callback', 'register');
247         return $this->socialAuthService->startRegister($socialDriver);
248     }
249
250     /**
251      * The callback for social login services.
252      * @param $socialDriver
253      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
254      * @throws SocialSignInException
255      */
256     public function socialCallback($socialDriver)
257     {
258         if (!session()->has('social-callback')) {
259             throw new SocialSignInException(trans('errors.social_no_action_defined'), '/login');
260         }
261
262         $action = session()->pull('social-callback');
263         if ($action == 'login') return $this->socialAuthService->handleLoginCallback($socialDriver);
264         if ($action == 'register') return $this->socialRegisterCallback($socialDriver);
265         return redirect()->back();
266     }
267
268     /**
269      * Detach a social account from a user.
270      * @param $socialDriver
271      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
272      */
273     public function detachSocialAccount($socialDriver)
274     {
275         return $this->socialAuthService->detachSocialAccount($socialDriver);
276     }
277
278     /**
279      * Register a new user after a registration callback.
280      * @param $socialDriver
281      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
282      * @throws UserRegistrationException
283      */
284     protected function socialRegisterCallback($socialDriver)
285     {
286         $socialUser = $this->socialAuthService->handleRegistrationCallback($socialDriver);
287         $socialAccount = $this->socialAuthService->fillSocialAccount($socialDriver, $socialUser);
288
289         // Create an array of the user data to create a new user instance
290         $userData = [
291             'name' => $socialUser->getName(),
292             'email' => $socialUser->getEmail(),
293             'password' => str_random(30)
294         ];
295         return $this->registerUser($userData, $socialAccount);
296     }
297
298 }