PluginProbe
FluentCart A New Era of eCommerce – Faster, Lighter, and Simpler / 1.7.0
FluentCart A New Era of eCommerce – Faster, Lighter, and Simpler v1.7.0
1.7.0 1.6.6 1.6.5 1.6.4 1.6.3 1.6.2 1.6.1 1.6.0 1.5.4 1.5.5 1.5.3 1.5.2 1.5.1 1.5.0 1.4.2 1.4.1 1.4.0 1.3.28 1.3.27 1.3.26 1.3.25 1.3.23 1.3.22 1.3.21 1.3.20 All 50 releases
fluent-cart / app / Services / AuthService.php

AuthService.php in FluentCart A New Era of eCommerce – Faster, Lighter, and Simpler 1.7.0, at app/Services/AuthService.php

262 lines 10.1 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 namespace FluentCart\App\Services;
4
5 use FluentCart\App\Models\Customer;
6 use FluentCart\Api\Resource\CustomerResource;
7 use FluentCart\App\Services\CustomerIdentity\EmailVerificationService;
8
9 class AuthService
10 {
11
12 public static function createUserFromCustomer(Customer $customer, $sendUserEmail = true, $userRole = '')
13 {
14 $userName = self::createUserNameFromStrings($customer->email, [$customer->first_name, $customer->last_name]);
15
16 // With verification not required, link the account to its customer before
17 // other registration listeners run. The update never takes a customer
18 // another account owns, nor one whose stored email changed meanwhile;
19 // an unlinked one is linked on the first portal visit.
20 $link = function ($userId) use ($customer) {
21 $user = get_userdata($userId);
22 if ($user && EmailVerificationService::isSame($user->user_email, $customer->email)) {
23 $linked = Customer::query()->where('id', $customer->id)->unclaimed()
24 ->whereRaw('LOWER(TRIM(email)) = ?', [EmailVerificationService::normalize($user->user_email)])
25 ->update(['user_id' => (int) $userId]);
26 if ($linked) {
27 $customer->refresh();
28 }
29 CustomerResource::resetCurrentCustomerRuntimeCache();
30 }
31 };
32
33 $linkCustomer = !EmailVerificationService::isEnabled();
34 if ($linkCustomer) {
35 add_action('user_register', $link, PHP_INT_MIN, 1);
36 }
37
38 try {
39 return self::registerNewUser($userName, $customer->email, '', [
40 'first_name' => $customer->first_name,
41 'last_name' => $customer->last_name,
42 'role' => $userRole
43 ]);
44 } finally {
45 if ($linkCustomer) {
46 remove_action('user_register', $link, PHP_INT_MIN);
47 }
48 }
49 }
50
51 public static function registerNewUser($user_login, $user_email, $user_pass = '', $extraData = [])
52 {
53 $errors = new \WP_Error();
54
55 $sanitized_user_login = sanitize_user($user_login);
56
57 // Check the username.
58 if ('' === $sanitized_user_login) {
59 $errors->add('empty_username', __('<strong>Error</strong>: Please enter a username.', 'fluent-cart'));
60 } elseif (username_exists($sanitized_user_login)) {
61 $errors->add('username_exists', __('<strong>Error</strong>: This username is already registered. Please choose another one.', 'fluent-cart'));
62 }
63
64 // Check the email address.
65 if ('' === $user_email) {
66 $errors->add('empty_email', __('<strong>Error</strong>: Please type your email address.', 'fluent-cart'));
67 } elseif (!is_email($user_email)) {
68 $errors->add('invalid_email', __('<strong>Error</strong>: The email address is not correct.', 'fluent-cart'));
69 $user_email = '';
70 } elseif (email_exists($user_email)) {
71 $errors->add(
72 'email_exists',
73 __('<strong>Error:</strong> This email address is already registered. Please login or try resetting your password.', 'fluent-cart')
74 );
75 }
76
77 if ($errors->has_errors()) {
78 return $errors;
79 }
80
81 $isGeneratedPassword = false;
82 if (!$user_pass) {
83 $isGeneratedPassword = true;
84 $user_pass = wp_generate_password(8, false);
85 }
86
87 $data = [
88 'user_login' => wp_slash($sanitized_user_login),
89 'user_email' => wp_slash($user_email),
90 'user_pass' => $user_pass
91 ];
92
93 if (!empty($extraData['first_name'])) {
94 $data['first_name'] = sanitize_text_field($extraData['first_name']);
95 }
96
97 if (!empty($extraData['last_name'])) {
98 $data['last_name'] = sanitize_text_field($extraData['last_name']);
99 }
100
101 if (!empty($extraData['full_name']) && empty($extraData['first_name']) && empty($extraData['last_name'])) {
102 $extraData['full_name'] = sanitize_text_field($extraData['full_name']);
103 // extract the names
104 $fullNameArray = explode(' ', $extraData['full_name']);
105 $data['first_name'] = array_shift($fullNameArray);
106 if ($fullNameArray) {
107 $data['last_name'] = implode(' ', $fullNameArray);
108 } else {
109 $data['last_name'] = '';
110 }
111 }
112
113 if (!empty($extraData['description'])) {
114 $data['description'] = sanitize_textarea_field($extraData['description']);
115 }
116
117 if (!empty($extraData['user_url']) && filter_var($extraData['user_url'], FILTER_VALIDATE_URL)) {
118 $data['user_url'] = sanitize_url($extraData['user_url']);
119 }
120
121 if (!empty($extraData['role'])) {
122 $data['role'] = $extraData['role'];
123 }
124
125 $user_id = wp_insert_user($data);
126
127 if (!$user_id || is_wp_error($user_id)) {
128 $errors->add('registerfail', __('<strong>Error</strong>: Could not register you. Please contact the site admin!', 'fluent-cart'));
129 return $errors;
130 }
131
132 if (!empty($_COOKIE['wp_lang'])) {
133 $wp_lang = sanitize_text_field(wp_unslash($_COOKIE['wp_lang']));
134 if (in_array($wp_lang, get_available_languages(), true)) {
135 update_user_meta($user_id, 'locale', $wp_lang); // Set user locale if defined on registration.
136 }
137 }
138
139 if ($isGeneratedPassword) {
140 update_user_meta($user_id, 'default_password_nag', true); // Set up the password change nag.
141 }
142
143 do_action('fluent_cart/user/after_register', $user_id, [
144 'user_id' => $user_id
145 ]);
146
147 if (apply_filters('fluent_cart/user/after_register/skip_hooks', false, $user_id)) {
148 return $user_id;
149 }
150
151 do_action('register_new_user', $user_id);
152
153 return $user_id;
154 }
155
156 public static function makeLogin($user)
157 {
158 wp_clear_auth_cookie();
159 wp_set_current_user($user->ID, $user->user_login);
160 wp_set_auth_cookie($user->ID, true, is_ssl());
161
162 $user = get_user_by('ID', $user->ID);
163
164 if ($user) {
165 // do_action('wp_login', $user->user_login, $user);
166 }
167
168 return $user;
169 }
170
171 public static function createUserNameFromStrings($maybeEmail, $fallbacks = [])
172 {
173 $emailParts = explode('@', $maybeEmail);
174 $userName = $emailParts[0];
175
176 $userName = self::sanitizeUserName($userName);
177
178 if (self::isUsernameAvailable($userName)) {
179 return $userName;
180 }
181
182 foreach ($fallbacks as $fallback) {
183 // only take alphanumeric characters and _ -
184 $fallback = preg_replace('/[^a-zA-Z0-9_-]/', '', $fallback);
185 $userName = self::sanitizeUserName($fallback);
186 if (self::isUsernameAvailable($userName)) {
187 return $userName;
188 }
189 }
190
191 $userName = strtolower($emailParts[0]);
192
193 $finalUserName = $userName;
194
195 // loop until we find a unique username
196 $counter = 2;
197 while (!self::isUsernameAvailable($userName)) {
198 $userName = $finalUserName . $counter;
199 $counter++;
200 if ($counter % 100 === 0) {
201 $finalUserName = $finalUserName . '-' . time();
202 }
203 }
204
205 return $userName;
206 }
207
208 private static function sanitizeUserName($username)
209 {
210 $username = strtolower($username);
211
212 // check of @ symbol
213 if (strpos($username, '@') !== false) {
214 $username = explode('@', $username)[0];
215 }
216
217 $username = sanitize_user($username);
218 $username = preg_replace('/[^a-zA-Z0-9_]/', '', $username);
219 return $username;
220 }
221
222 private static function isUsernameAvailable($userName)
223 {
224 $userName = strtolower($userName);
225 if (strlen($userName) < 3) {
226 return false;
227 }
228
229 $reservedUserNames = self::getReservedUserNames();
230 if (in_array($userName, $reservedUserNames)) {
231 return false;
232 }
233
234 if (defined('FLUENT_COMMUNITY_PLUGIN_VERSION')) {
235 $xProfile = \FluentCommunity\App\Models\XProfile::where('username', $userName)
236 ->exists();
237 if ($xProfile) {
238 return false;
239 }
240 }
241
242 $illegal_user_logins = (array)apply_filters('illegal_user_logins', array());
243 if (in_array($userName, array_map('strtolower', $illegal_user_logins), true)) {
244 return false;
245 }
246
247 if (username_exists($userName)) {
248 return false;
249 }
250
251 return true;
252 }
253
254 private static function getReservedUserNames()
255 {
256 return apply_filters('fluent_community/reserved_usernames', [
257 'admin', 'administrator', 'me', 'moderator', 'mod', 'superuser', 'root', 'system', 'official', 'staff', 'support', 'helpdesk', 'user', 'guest', 'anonymous', 'everyone', 'anybody', 'someone', 'webmaster', 'postmaster', 'hostmaster', 'abuse', 'security', 'ssl', 'firewall', 'no-reply', 'noreply', 'mail', 'email', 'mailer', 'smtp', 'pop', 'imap', 'ftp', 'sftp', 'ssh', 'ceo', 'cfo', 'cto', 'founder', 'cofounder', 'owner', 'president', 'vicepresident', 'director', 'manager', 'supervisor', 'executive', 'info', 'contact', 'sales', 'marketing', 'support', 'billing', 'accounting', 'finance', 'hr', 'humanresources', 'legal', 'compliance', 'it', 'itsupport', 'customerservice', 'customersupport', 'dev', 'developer', 'api', 'sdk', 'app', 'bot', 'chatbot', 'sysadmin', 'devops', 'infosec', 'security', 'test', 'testing', 'beta', 'alpha', 'staging', 'production', 'development', 'home', 'about', 'contact', 'faq', 'help', 'news', 'blog', 'forum', 'community', 'events', 'calendar', 'shop', 'store', 'cart', 'checkout', 'social', 'follow', 'like', 'share', 'tweet', 'post', 'status', 'privacy', 'terms', 'copyright', 'trademark', 'legal', 'policy', 'all', 'none', 'null', 'undefined', 'true', 'false', 'default', 'example', 'sample', 'demo', 'temporary', 'delete', 'remove', 'profanity', 'explicit', 'offensive', 'yourappname', 'yourbrandname', 'yourdomain',
258 ]);
259 }
260
261 }
262