PluginProbe
Fluent Support – Helpdesk & Customer Support Ticket System / 2.3.1
Fluent Support – Helpdesk & Customer Support Ticket System v2.3.1
2.4.0 2.3.2 2.3.1 2.3.0 2.2.1 2.2.0 trunk 1.10.0 1.10.1 1.10.2 1.10.3 1.10.4 1.10.5 1.4.0 1.4.1 1.4.2 1.4.5 1.4.6 1.4.7 1.5.0 1.5.1 1.5.2 1.5.3 1.5.4 1.5.5 All 68 releases
fluent-support / app / Http / Controllers / AuthController.php

AuthController.php in Fluent Support – Helpdesk & Customer Support Ticket System 2.3.1, at app/Http/Controllers/AuthController.php

827 lines 28.9 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 namespace FluentSupport\App\Http\Controllers;
4
5 use FluentSupport\App\Models\Meta;
6 use FluentSupport\App\Services\Helper;
7 use FluentSupport\Framework\Support\Arr;
8 use FluentSupport\Framework\Http\Request\Request;
9 use FluentSupport\App\Hooks\Handlers\AuthHandler;
10 use FluentSupport\App\Hooks\Handlers\ReCaptchaHandler;
11 use FluentSupport\App\Hooks\Handlers\TwoFaHandler;
12 use FluentSupport\App\Hooks\Handlers\EmailVerificationHandler;
13
14
15 class AuthController extends Controller
16 {
17 /**
18 * signUp method will create new user submitted data from sign up form
19 * @param Request $request
20 * @return \WP_REST_Response
21 * @throws \FluentSupport\Framework\Validator\ValidationException
22 */
23 public function signup(Request $request)
24 {
25
26 if(Helper::getAuthProvider() !== 'fluent_support') {
27 return $this->sendError([
28 'message' => __('You are not allowed to signup using this form', 'fluent-support')
29 ]);
30 }
31
32 if (!wp_verify_nonce($request->getSafe('_fsupport_signup_nonce', 'sanitize_text_field'), 'fluent_support_signup_nonce')) {
33 return $this->sendError([
34 'message' => __('Security verification failed. Please try again', 'fluent-support')
35 ]);
36 }
37
38 $fields = AuthHandler::getSignupFields();
39
40 $rules = $this->getRules($fields);
41
42 $messages = $this->getMessages($rules);
43
44 /*
45 * Filter user signup form data
46 *
47 * @since v1.0.0
48 * @param array $formData
49 */
50 $formData = apply_filters('fluent_support/signup_form_data', $request->all());
51
52 /*
53 * Action before validate user signup
54 *
55 * @since v1.0.0
56 * @param array $formData
57 */
58 do_action('fluent_support/before_signup_validation', $formData);
59
60 $checkRecaptchaAvailability = $this->isRecaptchaApplicable('signup_form');
61 if ($checkRecaptchaAvailability && !$formData['_email_verification_hash']) {
62 $validateCaptcha = ReCaptchaHandler::validateRecaptcha($formData['g-recaptcha-response']);
63 if (!$validateCaptcha) {
64 return $this->response([
65 'message' => __('Your recaptcha is not verified', 'fluent-support')
66 ], 422);
67 }
68 }
69
70 $this->validate($formData, $rules, $messages);
71
72 if (empty($formData['_email_verification_token'])) {
73 $tokenHtml = EmailVerificationHandler::sendSignupEmailVerificationHtml($formData);
74
75 return $this->response([
76 'verification_html' => $tokenHtml
77 ]);
78 } else {
79 $token = $formData['_email_verification_token'];
80 $verificationHash = $formData['_email_verification_hash'];
81
82 $logHashMeta = Meta::where('object_type', 'fs_login_hashes',)
83 ->where('key', $verificationHash)
84 ->first();
85
86 if (!$logHashMeta) {
87 wp_send_json([
88 'message' => __('Please provide a valid verification code that was sent to your email address', 'fluent-support')
89 ], 422);
90 }
91
92 $logHash = Helper::safeUnserialize($logHashMeta->value);
93
94 if (!$logHash) {
95 wp_send_json([
96 'message' => __('Please provide a valid verification code that was sent to your email address', 'fluent-support')
97 ], 422);
98 }
99
100 // the code must still be unused and must not have been consumed by a prior request
101 if (($logHash['status'] ?? '') !== 'issued') {
102 wp_send_json([
103 'message' => __('Your verification code has already been used. Please try again', 'fluent-support')
104 ], 422);
105 }
106
107 // records created before the email-binding fix (or any other legacy/malformed record)
108 // have no bound email; treat them as invalid rather than proceeding with a null email
109 if (empty($logHash['email'])) {
110 wp_send_json([
111 'message' => __('Your verification code has expired. Please request a new one', 'fluent-support')
112 ], 422);
113 }
114
115 // check if it got expired or not
116 $validTill = $logHash['valid_till'] ?? '';
117 if (($logHash['used_count'] ?? 0) > 5 || ($validTill && strtotime($validTill) < current_time('timestamp'))) {
118 wp_send_json([
119 'message' => __('Your verification code has been expired. Please try again', 'fluent-support')
120 ], 422);
121 }
122
123 if (!wp_check_password($token, $logHash['two_fa_code_hash'])) {
124
125 $logHash['used_count'] += 1;
126 Meta::where('key', $logHash['login_hash'])->update([
127 'value' => maybe_serialize($logHash)
128 ]);
129
130 wp_send_json([
131 'message' => __('Please provide a valid verification code that was sent to your email address', 'fluent-support')
132 ], 422);
133 }
134
135 // atomically consume the code: only succeeds if the record is still in the exact
136 // state we just read, closing the race where two requests both pass the checks above
137 $consumed = Meta::where('key', $logHash['login_hash'])
138 ->where('object_type', 'fs_login_hashes')
139 ->where('value', $logHashMeta->value)
140 ->update([
141 'value' => maybe_serialize(array_merge($logHash, [
142 'used_count' => ($logHash['used_count'] ?? 0) + 1,
143 'status' => 'used',
144 ]))
145 ]);
146
147 if (!$consumed) {
148 wp_send_json([
149 'message' => __('Your verification code has already been used. Please try again', 'fluent-support')
150 ], 422);
151 }
152
153 // the email is now server-verified for this code; ignore whatever the client
154 // submitted and use the address the code was actually issued to, so the signup
155 // can never be completed against a different (e.g. victim's) email address
156 $formData['email'] = $logHash['email'];
157 }
158
159 /*
160 * Action After validate user signup validation success
161 *
162 * @since v1.0.0
163 * @param array $formData
164 */
165 do_action('fluent_support/after_signup_validation', $formData);
166
167 $userId = $this->createUser($formData);
168
169 if (is_wp_error($userId)) {
170 return $this->response(
171 apply_filters(
172 'fluent_support/signup_create_user_error',
173 ['error' => $userId->get_error_message()]
174 ), 423);
175 }
176
177 /*
178 * Action After creating WP user from ticket sign up form
179 *
180 * @since v1.0.0
181 * @param array $formData
182 */
183 do_action('fluent_support/after_creating_user');
184
185 $this->maybeUpdateUser($userId, $formData);
186 $this->addUserMetaData($userId, $formData);
187 $this->assignRole($userId);
188 $this->login($userId);
189
190 /*
191 * Filter for user signup complete message and redirect
192 *
193 * @since v1.0.0
194 * @param array $response
195 */
196 $response = apply_filters('fluent_support/signup_complete_response', [
197 'message' => __('Successfully registered to the site.', 'fluent-support'),
198 'redirect' => Arr::get($formData, '__redirect_to', Helper::getPortalBaseUrl())
199 ]);
200
201 return $this->response($response);
202 }
203
204 /**
205 * handleLogin method will perform login functionality and redirect
206 * @param Request $request
207 * @return \WP_REST_Response
208 */
209 public function handleLogin(Request $request)
210 {
211 if(Helper::getAuthProvider() !== 'fluent_support') {
212 return $this->sendError([
213 'message' => __('You are not allowed to login using this form', 'fluent-support')
214 ]);
215 }
216
217 if (!wp_verify_nonce($request->getSafe('_support_login_nonce', 'sanitize_text_field'), 'fsupport_login_nonce')) {
218 return $this->response([
219 'message' => __('Security verification failed', 'fluent-support')
220 ], 403);
221 }
222
223 $data = $request->all();
224
225 $checkRecaptchaAvailability = $this->isRecaptchaApplicable('login_form');
226 if ($checkRecaptchaAvailability) {
227 $validateCaptcha = ReCaptchaHandler::validateRecaptcha($data['g-recaptcha-response']);
228
229 if (!$validateCaptcha) {
230 return $this->response([
231 'message' => __('Your recaptcha is not verified', 'fluent-support')
232 ], 422);
233 }
234 }
235
236 if (empty($data['pwd']) || empty($data['log'])) {
237 return $this->response([
238 'message' => __('Email and Password is required', 'fluent-support')
239 ], 403);
240 }
241 $redirectUrl = Helper::getPortalBaseUrl();
242 if ($redirect = $request->getSafe('redirect_to', 'sanitize_text_field')) {
243 $redirectUrl = wp_validate_redirect($redirect, $redirectUrl);
244 }
245
246 if (get_current_user_id()) { // user already registered
247 return $this->sendSuccess([
248 'redirect' => $redirectUrl
249 ]);
250 }
251
252 $email = sanitize_user($data['log']);
253 $password = trim($data['pwd'] ?? '');
254
255 if (is_email($email)) {
256 $user = get_user_by('email', $email);
257 } else {
258 $user = get_user_by('login', $email);
259 }
260
261 // Rate limiting: per-IP bucket (5 attempts) + per-account bucket (20 attempts)
262 $ip = Helper::getIp();
263 $ipKey = $user
264 ? 'fs_login_ip_' . wp_hash($user->ID . '|' . $ip)
265 : 'fs_login_ip_' . wp_hash(strtolower($email) . '|' . $ip);
266 $accountKey = $user
267 ? 'fs_login_act_' . wp_hash($user->ID)
268 : 'fs_login_act_' . wp_hash(strtolower($email));
269
270 $ipAttempts = get_transient($ipKey);
271 $accountAttempts = get_transient($accountKey);
272
273 if (($ipAttempts !== false && $ipAttempts >= 5) || ($accountAttempts !== false && $accountAttempts >= 20)) {
274 return $this->sendError([
275 'message' => __('Too many login attempts. Please try again after 15 minutes.', 'fluent-support')
276 ], 429);
277 }
278
279 if (!$user) {
280 $user = new \WP_Error('authentication_failed', __('Invalid username, email address or incorrect password.', 'fluent-support'));
281
282 do_action('wp_login_failed', $email, $user);
283 $this->incrementLoginAttempts($ipKey);
284 $this->incrementLoginAttempts($accountKey);
285
286 return $this->response([
287 'message' => __('Email or Password is not valid. Please try again', 'fluent-support')
288 ], 403);
289
290 }
291
292 $twoFactorEnabled = Helper::getBusinessSettings('enable_two_fa');
293 if ('yes' === $twoFactorEnabled) {
294 if (!wp_check_password($password, $user->user_pass, $user->ID)) {
295 $this->incrementLoginAttempts($ipKey);
296 $this->incrementLoginAttempts($accountKey);
297
298 return $this->response([
299 'message' => __('Invalid username, email address or incorrect password.', 'fluent-support')
300 ], 403);
301 }
302
303 (new TwoFaHandler)->maybe2FaRedirect($user);
304 }
305
306 if (apply_filters('fluent_support_use_native_login', true)) {
307 $user = wp_signon();
308 if (is_wp_error($user)) {
309 $this->incrementLoginAttempts($ipKey);
310 $this->incrementLoginAttempts($accountKey);
311 return $this->response([
312 'message' => $user->get_error_message()
313 ], 403);
314 }
315
316 // Clear rate limits for the authenticated user
317 $authIpKey = 'fs_login_ip_' . wp_hash($user->ID . '|' . $ip);
318 $authAccountKey = 'fs_login_act_' . wp_hash($user->ID);
319 delete_transient($authIpKey);
320 delete_transient($authAccountKey);
321 return $this->sendSuccess([
322 'redirect' => $redirectUrl
323 ]);
324 }
325
326 if (wp_check_password($password, $user->user_pass, $user->ID)) {
327 delete_transient($ipKey);
328 delete_transient($accountKey);
329 $this->login($user->ID);
330 return $this->sendSuccess([
331 'redirect' => $redirectUrl
332 ]);
333 }
334
335 $this->incrementLoginAttempts($ipKey);
336 $this->incrementLoginAttempts($accountKey);
337
338 return $this->response([
339 'message' => __('Invalid username, email address or incorrect password.', 'fluent-support')
340 ], 403);
341 }
342
343 private function incrementLoginAttempts($rateLimitKey)
344 {
345 $attempts = get_transient($rateLimitKey);
346 if ($attempts === false) {
347 set_transient($rateLimitKey, 1, 15 * MINUTE_IN_SECONDS);
348 } else {
349 set_transient($rateLimitKey, $attempts + 1, 15 * MINUTE_IN_SECONDS);
350 }
351 }
352
353 public function isRecaptchaApplicable($formName)
354 {
355 $reCaptchaSettingsData = Meta::where('object_type', '_fs_recaptcha_settings')->first();
356 if(!isset($reCaptchaSettingsData->value)){
357 return false;
358 }
359 $reCaptchaData = Helper::safeUnserialize($reCaptchaSettingsData->value, []);
360 if(!isset($reCaptchaData['is_enabled']) || !isset($reCaptchaData['formContainingReCaptcha'])){
361 return false;
362 }
363 $isEnabled = filter_var($reCaptchaData['is_enabled'], FILTER_VALIDATE_BOOLEAN);
364 if (!$isEnabled) {
365 return false;
366 }
367 $formContainingReCaptcha = $reCaptchaData['formContainingReCaptcha'];
368 return 'yes' === $formContainingReCaptcha[$formName];
369 }
370
371 private function nativeLoginHandler($user, $info, $redirectUrl = '')
372 {
373 if (!$redirectUrl) {
374 $redirectUrl = Helper::getPortalBaseUrl();
375 }
376
377 $secure_cookie = is_ssl();
378 if (!$secure_cookie && !force_ssl_admin()) {
379 if (get_user_option('use_ssl', $user->ID)) {
380 $secure_cookie = true;
381 force_ssl_admin(true);
382 }
383 }
384
385 if (class_exists('\Limit_Login_Attempts')) {
386 global $limit_login_attempts_obj;
387 $limit_login_attempts_try = $limit_login_attempts_obj->wp_authenticate_user($user, false);
388 if (is_wp_error($limit_login_attempts_try)) {
389 return $this->response([
390 'message' => implode('<br/>', $limit_login_attempts_try->get_error_messages())
391 ], 403);
392 }
393 }
394
395 $user_signon = wp_signon($info, $secure_cookie);
396
397 // Note: No sanitization needed here as we're only checking emptiness, not using the cookie value
398 if (!is_wp_error($user_signon) && empty($_COOKIE[LOGGED_IN_COOKIE])) {
399 if (headers_sent()) {
400 return $this->response([
401 // translators: %1$s is the URL to WordPress cookies documentation, %2$s is the URL to WordPress support forums
402 'message' => sprintf(__('<strong>ERROR</strong>: Cookies are blocked due to unexpected output. For help, please see <a href="%1$s">this documentation</a> or try the <a href="%2$s">support forums</a>.', 'fluent-support'),
403 'https://codex.wordpress.org/Cookies', 'https://wordpress.org/support/')
404 ], 403);
405 }
406 }
407
408 if (is_wp_error($user_signon)) {
409 $errorMessage = __('Email or Password is not valid. Please try again', 'fluent-support');
410
411 if (class_exists('Limit_Login_Attempts')) {
412 global $limit_login_attempts_obj;
413 if ($limit_login_attempts_obj) {
414 $limit_login_attempts_obj->limit_login_failed($user->user_login);
415 $msg = $limit_login_attempts_obj->get_message();
416 if ($msg) {
417 $errorMessage = $msg;
418 }
419 }
420 }
421
422 return $this->response([
423 'message' => $errorMessage
424 ], 403);
425 }
426
427 // WP Last Login plugin compatibility
428 if (class_exists('\Obenland_Wp_Last_Login')) {
429 update_user_meta($user_signon->ID, 'wp-last-login', time());
430 }
431
432 return $this->sendSuccess([
433 'redirect' => $redirectUrl
434 ]);
435 }
436
437 /**
438 * getRules method will prepare the rules for the input field
439 * @param array $fields
440 * @return mixed
441 */
442 protected function getRules($fields = [])
443 {
444 $rules = [];
445
446 foreach ($fields as $fieldName => $field) {
447 if (array_key_exists('required', $field)) {
448 $rules[$fieldName] = 'required';
449 }
450
451 $pipe = array_key_exists($fieldName, $rules) ? '|' : '';
452
453 if ($field['type'] === 'email') {
454 $rules[$fieldName] = $rules[$fieldName] . $pipe . 'email';
455 } elseif ($field['type'] === 'password') {
456 $rules[$fieldName] = $rules[$fieldName] . $pipe . 'min:8';
457 }
458 }
459 /*
460 * Filter user signup validation rules
461 *
462 * @since v1.0.0
463 * @param array $rules
464 */
465 return apply_filters('fluent_support/signup_validation_rules', $rules);
466 }
467
468
469 public function resetPassword(Request $request)
470 {
471
472 if(Helper::getAuthProvider() !== 'fluent_support') {
473 return $this->sendError([
474 'message' => __('You are not allowed to reset password using this form', 'fluent-support')
475 ]);
476 }
477
478 $errors = new \WP_Error();
479
480 if (!wp_verify_nonce($request->getSafe('_fsupport_reset_pass_nonce', 'sanitize_text_field'), 'fluent_support_reset_pass_nonce')) {
481 return $this->sendError([
482 'message' => __('Security verification failed. Please try again', 'fluent-support')
483 ]);
484 }
485
486 $usernameOrEmail = trim(wp_unslash($request->getSafe('user_login', 'sanitize_text_field')));
487
488 if (!$usernameOrEmail) {
489 return $this->sendError([
490 'message' => 'Username or email is required'
491 ]);
492 }
493
494 // IP bucket is a generous volumetric backstop (shared office/NAT IPs can have many
495 // unrelated users). It runs before the account lookup so that probes for accounts
496 // that don't exist are throttled too. Keyed on the IP only, so a 429 here reveals
497 // nothing about whether any given account exists.
498 if (Helper::hitRateLimit('fs_reset_pass_ip_' . wp_hash(Helper::getIp()), 20)) {
499 return $this->sendError([
500 'message' => __('Too many password reset requests. Please try again after 15 minutes.', 'fluent-support')
501 ], 429);
502 }
503
504 $user_data = get_user_by('email', $usernameOrEmail);
505
506 if (!$user_data) {
507 $user_data = get_user_by('login', $usernameOrEmail);
508 }
509
510 if (!$user_data) {
511 return $this->sendError([
512 'message' => __('Invalid username or email', 'fluent-support')
513 ]);
514 }
515
516 $user_data = apply_filters('lostpassword_user_data', $user_data, $errors);
517
518 do_action('lostpassword_post', $errors, $user_data);
519
520 $errors = apply_filters('lostpassword_errors', $errors, $user_data);
521
522 if ($errors->has_errors()) {
523 return $this->sendError([
524 'message' => $errors->get_error_message()
525 ]);
526 }
527
528 if (!$user_data) {
529 return $this->sendError([
530 'message' => __('There is no account with that username or email address.', 'fluent-support')
531 ]);
532 }
533
534 if (is_multisite() && !is_user_member_of_blog($user_data->ID, get_current_blog_id())) {
535
536 return $this->sendError([
537 'message' => __('Invalid username or email', 'fluent-support')
538 ]);
539 }
540
541 // Redefining user_login ensures we return the right case in the email.
542 $user_login = $user_data->user_login;
543
544 do_action('retrieve_password', $user_login);
545
546 $allow = apply_filters('allow_password_reset', true, $user_data->ID);
547
548 if (!$allow) {
549 return $this->sendError([
550 'message' => __('Password reset is not allowed for this user', 'fluent-support')
551 ]);
552 }
553
554 if (is_wp_error($allow)) {
555 return $this->sendError([
556 'message' => $allow->get_error_message()
557 ]);
558 }
559
560
561 /*
562 * Filter reset password link text
563 *
564 * @since v1.5.7
565 * @param string $linkText
566 */
567 // translators: %s is the site name
568 $linkText = apply_filters("fluent_support/reset_password_link", sprintf(__('Reset your password for %s', 'fluent-support'), get_bloginfo('name')));
569
570 // Issuance cooldown. get_password_reset_key() rotates the stored key, invalidating
571 // any link already sitting in the account owner's inbox, so an unthrottled caller
572 // could deny password recovery indefinitely. Suppressing the duplicate issuance is
573 // safe: reset mail only ever goes to the account owner, so whoever triggered the
574 // first send has already put a working link in that inbox.
575 $cooldownKey = 'fs_reset_pass_sent_' . wp_hash($user_data->ID);
576
577 if (get_transient($cooldownKey)) {
578 return $this->sendError([
579 'message' => __('A password reset link was already sent to this account recently. Please check your email, including the spam folder, or try again in a few minutes.', 'fluent-support')
580 ], 429);
581 }
582
583 set_transient($cooldownKey, 1, 5 * MINUTE_IN_SECONDS);
584
585 $resetUrl = add_query_arg([
586 'action' => 'rp',
587 'key' => get_password_reset_key($user_data),
588 'login' => rawurlencode($user_data->user_login)
589 ], wp_login_url());
590
591 $resetLink = '<a href="' . $resetUrl . '">' . $linkText . '</a>';
592
593 /*
594 * Filter reset password email subject
595 *
596 * @since v1.5.7
597 * @param string $mailSubject
598 */
599 // translators: %s is the site name
600 $mailSubject = apply_filters("fluent_support/reset_password_mail_subject", sprintf(__('Reset your password for %s support portal', 'fluent-support'), get_bloginfo('name')));
601
602 // translators: %s is the user's first name
603 $message = '<p>' . sprintf(__('Hi %s,', 'fluent-support'), $user_data->first_name) . '</p>' .
604 '<p>' . __('Someone has requested a new password for the following account on WordPress:', 'fluent-support') . '</p>' .
605 // translators: %s is the username
606 '<p>' . sprintf(__('Username: %s', 'fluent-support'), $user_login) . '</p>' .
607 '<p>' . $resetLink . '</p>' .
608 '<p>' . __('If you did not request to reset your password, please ignore this email.', 'fluent-support') . '</p>';
609
610 /*
611 * Filter reset password email body text
612 *
613 * @since v1.5.7
614 * @param string $message
615 * @param object $user
616 * @param string $resetLink
617 */
618 $message = apply_filters('fluent_support/reset_password_message', $message, $user_data, $resetLink);
619
620 $headers = array('Content-Type: text/html; charset=UTF-8');
621
622 wp_mail($user_data->user_email, $mailSubject, $message, $headers);
623
624 return $this->sendSuccess([
625 'message' => __('Please check your email for the reset link', 'fluent-support')
626 ]);
627 }
628
629 /**
630 * getMessages message will return the validation message regarding sign up or sign in
631 * @param array $rules
632 * @return mixed
633 */
634 protected function getMessages($rules = [])
635 {
636 /*
637 * Filter user signup validation message
638 *
639 * @since v1.0.0
640 * @param array $arg
641 * @param array $rules
642 */
643 return apply_filters('fluent_support/signup_validation_messages', [], $rules);
644 }
645
646 /**
647 * createUser method will create new user
648 * @param array $formData
649 * @return mixed
650 */
651 public function createUser($formData = [])
652 {
653 /*
654 * Filter user signup email
655 *
656 * @since v1.0.0
657 * @param string $email
658 */
659 $email = apply_filters('fluent_support/signup_email', Arr::get($formData, 'email'));
660
661 /*
662 * Filter user signup username
663 *
664 * @since v1.0.0
665 * @param string $username
666 */
667 $userName = apply_filters('fluent_support/signup_username', Arr::get($formData, 'username'));
668
669 if (empty($formData['password'])) {
670 $password = wp_generate_password(16, true, true);
671 } else {
672 $password = $formData['password'];
673 }
674
675 /*
676 * Filter user signup password
677 *
678 * @since v1.0.0
679 * @param string $password
680 */
681 $password = apply_filters('fluent_support/signup_password', $password);
682
683 /*
684 * Action before creating WP user using Fluent Support signup form
685 *
686 * @since v1.0.0
687 * @param string $userName
688 * @param string $password
689 * @param string $email
690 */
691 do_action('fluent_support/before_creating_user', $userName, $password, $email);
692
693 $userId = wp_create_user($userName, $password, $email);
694
695 if (is_wp_error($userId)) {
696 return false;
697 }
698
699 return $userId;
700
701 }
702
703 /**
704 * maybeUpdateUser method will update user information if exists
705 * @param $userId
706 * @param $formData
707 */
708 public function maybeUpdateUser($userId, $formData)
709 {
710 $firstName = Arr::get($formData, 'first_name', '');
711 $lastName = Arr::get($formData, 'last_name', '');
712 $name = trim($firstName . ' ' . $lastName);
713
714 $data = array_filter([
715 'ID' => $userId,
716 'user_nicename' => $name,
717 'display_name' => $name,
718 'first_name' => $firstName,
719 'last_name' => $lastName,
720 ]);
721
722 if ($name) {
723 /*
724 * Action before updating a customer/user
725 *
726 * @since v1.0.0
727 * @param array $data
728 */
729 do_action('fluent_support/before_updating_user', $data);
730
731 /*
732 * Filter user updatable data
733 *
734 * @since v1.0.0
735 * @param $data
736 */
737 $updateUserData = apply_filters('fluent_support/update_user_data', $data);
738 wp_update_user($updateUserData);
739
740 /*
741 * Action after updating a customer/user
742 *
743 * @since v1.0.0
744 * @param array $data
745 */
746 do_action('fluent_support/after_updating_user', $data);
747 }
748 }
749
750 public function addUserMetaData($userId, $formData) {
751 $customFieldsKey = apply_filters('fluent_support/custom_registration_form_fields_key', Helper::getBusinessSettings('custom_registration_form_field'));
752
753 if (empty($customFieldsKey)) {
754 return;
755 }
756
757 foreach ($customFieldsKey as $key) {
758 if (isset($formData[$key])) {
759 $fieldValue = $formData[$key];
760 update_user_meta($userId, $key, $fieldValue);
761 }
762 }
763 }
764
765 /**
766 * assignRole method will assign role to a given user id
767 * @param $userId
768 */
769 protected function assignRole($userId)
770 {
771 $user = new \WP_User($userId);
772
773 /*
774 * Action before assigning role to registered user
775 *
776 * @since v1.0.0
777 * @param array $data
778 */
779 do_action('fluent_support/before_assigning_role', $user);
780 /*
781 * Filter user assignable role after signup
782 *
783 * @since v1.0.0
784 * @param string $setRole WordPress user role key
785 */
786 $setRole = apply_filters('fluent_support/user_role', 'subscriber');
787 $user->set_role($setRole);
788
789 /*
790 * Action after assigning role to registered user
791 *
792 * @since v1.0.0
793 * @param array $data
794 */
795 do_action('fluent_support/after_assigning_role', $user);
796 }
797
798
799 /**
800 * login method will clear existing cookies and set new cookie for a given user id
801 * @param $userId
802 */
803 protected function login($userId)
804 {
805 /*
806 * Action before login
807 *
808 * @since v1.0.0
809 * @param integer $userId
810 */
811 do_action('fluent_support/before_logging_in_user', $userId);
812
813 wp_clear_auth_cookie();
814 wp_set_current_user($userId);
815 wp_set_auth_cookie($userId);
816
817 /*
818 * Action after login
819 *
820 * @since v1.0.0
821 * @param integer $userId
822 */
823 do_action('fluent_support/after_logging_in_user', $userId);
824 }
825
826 }
827