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