]> BookStack Code Mirror - bookstack/blob - app/Access/RegistrationService.php
Comments: Fixed failing tests due to unset template variable
[bookstack] / app / Access / RegistrationService.php
1 <?php
2
3 namespace BookStack\Access;
4
5 use BookStack\Activity\ActivityType;
6 use BookStack\Exceptions\UserRegistrationException;
7 use BookStack\Facades\Activity;
8 use BookStack\Facades\Theme;
9 use BookStack\Theming\ThemeEvents;
10 use BookStack\Users\Models\User;
11 use BookStack\Users\UserRepo;
12 use Exception;
13 use Illuminate\Support\Str;
14
15 class RegistrationService
16 {
17     protected $userRepo;
18     protected $emailConfirmationService;
19
20     /**
21      * RegistrationService constructor.
22      */
23     public function __construct(UserRepo $userRepo, EmailConfirmationService $emailConfirmationService)
24     {
25         $this->userRepo = $userRepo;
26         $this->emailConfirmationService = $emailConfirmationService;
27     }
28
29     /**
30      * Check whether or not registrations are allowed in the app settings.
31      *
32      * @throws UserRegistrationException
33      */
34     public function ensureRegistrationAllowed()
35     {
36         if (!$this->registrationAllowed()) {
37             throw new UserRegistrationException(trans('auth.registrations_disabled'), '/login');
38         }
39     }
40
41     /**
42      * Check if standard BookStack User registrations are currently allowed.
43      * Does not prevent external-auth based registration.
44      */
45     protected function registrationAllowed(): bool
46     {
47         $authMethod = config('auth.method');
48         $authMethodsWithRegistration = ['standard'];
49
50         return in_array($authMethod, $authMethodsWithRegistration) && setting('registration-enabled');
51     }
52
53     /**
54      * Attempt to find a user in the system otherwise register them as a new
55      * user. For use with external auth systems since password is auto-generated.
56      *
57      * @throws UserRegistrationException
58      */
59     public function findOrRegister(string $name, string $email, string $externalId): User
60     {
61         $user = User::query()
62             ->where('external_auth_id', '=', $externalId)
63             ->first();
64
65         if (is_null($user)) {
66             $userData = [
67                 'name'             => $name,
68                 'email'            => $email,
69                 'password'         => Str::random(32),
70                 'external_auth_id' => $externalId,
71             ];
72
73             $user = $this->registerUser($userData, null, false);
74         }
75
76         return $user;
77     }
78
79     /**
80      * The registrations flow for all users.
81      *
82      * @throws UserRegistrationException
83      */
84     public function registerUser(array $userData, ?SocialAccount $socialAccount = null, bool $emailConfirmed = false): User
85     {
86         $userEmail = $userData['email'];
87
88         // Email restriction
89         $this->ensureEmailDomainAllowed($userEmail);
90
91         // Ensure user does not already exist
92         $alreadyUser = !is_null($this->userRepo->getByEmail($userEmail));
93         if ($alreadyUser) {
94             throw new UserRegistrationException(trans('errors.error_user_exists_different_creds', ['email' => $userEmail]), '/login');
95         }
96
97         // Create the user
98         $newUser = $this->userRepo->createWithoutActivity($userData, $emailConfirmed);
99         $newUser->attachDefaultRole();
100
101         // Assign social account if given
102         if ($socialAccount) {
103             $newUser->socialAccounts()->save($socialAccount);
104         }
105
106         Activity::add(ActivityType::AUTH_REGISTER, $socialAccount ?? $newUser);
107         Theme::dispatch(ThemeEvents::AUTH_REGISTER, $socialAccount ? $socialAccount->driver : auth()->getDefaultDriver(), $newUser);
108
109         // Start email confirmation flow if required
110         if ($this->emailConfirmationService->confirmationRequired() && !$emailConfirmed) {
111             $newUser->save();
112
113             try {
114                 $this->emailConfirmationService->sendConfirmation($newUser);
115                 session()->flash('sent-email-confirmation', true);
116             } catch (Exception $e) {
117                 $message = trans('auth.email_confirm_send_error');
118
119                 throw new UserRegistrationException($message, '/register/confirm');
120             }
121         }
122
123         return $newUser;
124     }
125
126     /**
127      * Ensure that the given email meets any active email domain registration restrictions.
128      * Throws if restrictions are active and the email does not match an allowed domain.
129      *
130      * @throws UserRegistrationException
131      */
132     protected function ensureEmailDomainAllowed(string $userEmail): void
133     {
134         $registrationRestrict = setting('registration-restrict');
135
136         if (!$registrationRestrict) {
137             return;
138         }
139
140         $restrictedEmailDomains = explode(',', str_replace(' ', '', $registrationRestrict));
141         $userEmailDomain = $domain = mb_substr(mb_strrchr($userEmail, '@'), 1);
142         if (!in_array($userEmailDomain, $restrictedEmailDomains)) {
143             $redirect = $this->registrationAllowed() ? '/register' : '/login';
144
145             throw new UserRegistrationException(trans('auth.registration_email_domain_invalid'), $redirect);
146         }
147     }
148 }