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