# fluent-support/1.5.5/app/Http/Controllers/AuthController.php

Fluent Support – Helpdesk &amp; Customer Support Ticket System, version 1.5.5. 430 lines.

- Page: https://pluginprobe.com/plugins/fluent-support/1.5.5/code/app/Http/Controllers/AuthController.php
- Raw: https://pluginprobe.com/plugins/fluent-support/1.5.5/raw/app/Http/Controllers/AuthController.php
- Modified: 2022-03-02T14:22:44+00:00

Line numbers below start at 1. Link to a line or a range by appending a fragment to the
page URL, for example `https://pluginprobe.com/plugins/fluent-support/1.5.5/code/app/Http/Controllers/AuthController.php#L10-L20`.

```php
<?php

namespace FluentSupport\App\Http\Controllers;

use FluentSupport\App\Services\Helper;
use FluentSupport\Framework\Support\Arr;
use FluentSupport\Framework\Request\Request;
use FluentSupport\App\Hooks\Handlers\AuthHandler;

class AuthController extends Controller
{
    /**
     * signUp method will create new user submitted data from sign up form
     * @param Request $request
     * @return \WP_REST_Response
     * @throws \FluentSupport\Framework\Validator\ValidationException
     */
    public function signup(Request $request)
    {

        if (!wp_verify_nonce($request->get('_fsupport_signup_nonce'), 'fluent_support_signup_nonce')) {
            return $this->sendError([
                'message' => __('Security verification failed. Please try again', 'fluent-support')
            ]);
        }

        $fields = AuthHandler::getSignupFields();

        $rules = $this->getRules($fields);

        $messages = $this->getMessages($rules);

        /*
         * Filter user signup form data
         *
         * @since v1.0.0
         * @param array $formData
         */
        $formData = apply_filters('fluent_support/signup_form_data', $request->all());

        /*
         * Action before validate user signup
         *
         * @since v1.0.0
         * @param array $formData
         */
        do_action('fluent_support/before_signup_validation', $formData);

        $this->validate($formData, $rules, $messages);

        /*
         * Action After validate user signup validation success
         *
         * @since v1.0.0
         * @param array $formData
         */
        do_action('fluent_support/after_signup_validation', $formData);

        $userId = $this->createUser($formData);

        if (is_wp_error($userId)) {
            return $this->response(
                apply_filters(
                    'fluent_support/signup_create_user_error',
                    ['error' => $userId->get_error_message()]
                ), 423);
        }

        /*
         * Action After creating WP user from ticket sign up form
         *
         * @since v1.0.0
         * @param array $formData
         */
        do_action('fluent_support/after_creating_user');

        $this->maybeUpdateUser($userId, $formData);
        $this->assignRole($userId);
        $this->login($userId);

        /*
         * Filter for user signup complete message and redirect
         *
         * @since v1.0.0
         * @param array $response
         */
        $response = apply_filters('fluent_support/signup_complete_response', [
            'message'  => __('Successfully registered to the site.', 'fluent-support'),
            'redirect' => Arr::get($formData, '__redirect_to', Helper::getPortalBaseUrl())
        ]);

        return $this->response($response);
    }

    /**
     * handleLogin method will perform login functionality and redirect
     * @param Request $request
     * @return \WP_REST_Response
     */
    public function handleLogin(Request $request)
    {
        if (!wp_verify_nonce($request->get('_support_login_nonce'), 'fsupport_login_nonce')) {
            return $this->response([
                'message' => __('Security verification failed', 'fluent-support')
            ], 403);
        }

        $data = $request->all();

        if (empty($data['pwd']) || empty($data['log'])) {
            return $this->response([
                'message' => __('Email and Password is required', 'fluent-support')
            ], 403);
        }

        $redirectUrl = Helper::getPortalBaseUrl();

        if (get_current_user_id()) { // user already registered
            return $this->sendSuccess([
                'redirect' => $redirectUrl
            ]);
        }

        $email = $data['log'];
        $password = $data['pwd'];

        if (is_email($email)) {
            $user = get_user_by('email', $email);
        } else {
            $user = get_user_by('login', $email);
        }

        if (!$user) {
            return $this->response([
                'message' => __('Email or Password is not valid. Please try again', 'fluent-support')
            ], 403);
        }

        $info = array(
            'user_login'    => sanitize_text_field(trim($_POST['log'])),
            'user_password' => trim($_POST['pwd']),
            'remember'      => isset($_POST['rememberme']),
        );

        if (apply_filters('fluent_support_use_native_login', true)) {
            return $this->nativeLoginHandler($user, $info, $redirectUrl);
        }

        if (wp_check_password($password, $user->user_pass, $user->ID)) {
            $this->login($user->ID);
            return $this->sendSuccess([
                'redirect' => $redirectUrl
            ]);
        }

        return $this->response([
            'message' => __('Email or Password is not valid. Please try again', 'fluent-support')
        ], 403);
    }

    private function nativeLoginHandler($user, $info, $redirectUrl = '')
    {
        if (!$redirectUrl) {
            $redirectUrl = Helper::getPortalBaseUrl();
        }

        $secure_cookie = is_ssl();
        if (!$secure_cookie && !force_ssl_admin()) {
            if (get_user_option('use_ssl', $user->ID)) {
                $secure_cookie = true;
                force_ssl_admin(true);
            }
        }

        if (class_exists('\Limit_Login_Attempts')) {
            global $limit_login_attempts_obj;
            $limit_login_attempts_try = $limit_login_attempts_obj->wp_authenticate_user($user, false);
            if (is_wp_error($limit_login_attempts_try)) {
                return $this->response([
                    'message' => implode('<br/>', $limit_login_attempts_try->get_error_messages())
                ], 403);
            }
        }

        $user_signon = wp_signon($info, $secure_cookie);

        if (!is_wp_error($user_signon) && empty($_COOKIE[LOGGED_IN_COOKIE])) {
            if (headers_sent()) {
                return $this->response([
                    '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>.'),
                        __('https://codex.wordpress.org/Cookies'), __('https://wordpress.org/support/'))
                ], 403);
            }
        }

        if (is_wp_error($user_signon)) {
            $errorMessage = __('Email or Password is not valid. Please try again', 'fluent-support');

            if (class_exists('Limit_Login_Attempts')) {
                global $limit_login_attempts_obj;
                if ($limit_login_attempts_obj) {
                    $limit_login_attempts_obj->limit_login_failed($user->user_login);
                    $msg = $limit_login_attempts_obj->get_message();
                    if ($msg) {
                        $errorMessage = $msg;
                    }
                }
            }

            return $this->response([
                'message' => $errorMessage
            ], 403);
        }

        // WP Last Login plugin compatibility
        if (class_exists('\Obenland_Wp_Last_Login')) {
            update_user_meta($user_signon->ID, 'wp-last-login', time());
        }

        return $this->sendSuccess([
            'redirect' => $redirectUrl
        ]);
    }

    /**
     * getRules method will prepare the rules for the input field
     * @param array $fields
     * @return mixed
     */
    protected function getRules($fields = [])
    {
        $rules = [];

        foreach ($fields as $fieldName => $field) {
            if (array_key_exists('required', $field)) {
                $rules[$fieldName] = 'required';
            }

            $pipe = array_key_exists($fieldName, $rules) ? '|' : '';

            if ($field['type'] === 'email') {
                $rules[$fieldName] = $rules[$fieldName] . $pipe . 'email';
            } elseif ($field['type'] === 'password') {
                $rules[$fieldName] = $rules[$fieldName] . $pipe . 'min:8';
            }
        }
        /*
         * Filter user signup validation rules
         *
         * @since v1.0.0
         * @param array $rules
         */
        return apply_filters('fluent_support/signup_validation_rules', $rules);
    }


    /**
     * getMessages message will return the validation message regarding sign up or sign in
     * @param array $rules
     * @return mixed
     */
    protected function getMessages($rules = [])
    {
        /*
         * Filter user signup validation message
         *
         * @since v1.0.0
         * @param array $arg
         * @param array $rules
         */
        return apply_filters('fluent_support/signup_validation_messages', [], $rules);
    }

    /**
     * createUser method will create new user
     * @param array $formData
     * @return mixed
     */
    public function createUser($formData = [])
    {
        /*
         * Filter user signup email
         *
         * @since v1.0.0
         * @param string $email
         */
        $email = apply_filters('fluent_support/signup_email', Arr::get($formData, 'email'));

        /*
         * Filter user signup username
         *
         * @since v1.0.0
         * @param string $username
         */
        $userName = apply_filters('fluent_support/signup_username', Arr::get($formData, 'username'));

        if (empty($formData['password'])) {
            $password = wp_generate_password(8);
        } else {
            $password = $formData['password'];
        }

        /*
         * Filter user signup password
         *
         * @since v1.0.0
         * @param string $password
         */
        $password = apply_filters('fluent_support/signup_password', $password);

        /*
         * Action before creating WP user using Fluent Support signup form
         *
         * @since v1.0.0
         * @param string $userName
         * @param string $password
         * @param string $email
         */
        do_action('fluent_support/before_creating_user', $userName, $password, $email);

        return wp_create_user($userName, $password, $email);
    }

    /**
     * maybeUpdateUser method will update user information if exists
     * @param $userId
     * @param $formData
     */
    public function maybeUpdateUser($userId, $formData)
    {
        $name = trim(Arr::get($formData, 'first_name') . ' ' . Arr::get($formData, 'last_name'));

        $data = array_filter([
            'ID'            => $userId,
            'user_nicename' => $name,
            'display_name'  => $name,
            'first_name'    => Arr::get($formData, 'first_name'),
            'last_name'     => Arr::get($formData, 'last_name'),
        ]);

        if ($name) {
            /*
             * Action before updating a customer/user
             *
             * @since v1.0.0
             * @param array $data
             */
            do_action('fluent_support/before_updating_user', $data);

            /*
             * Filter user updatable data
             *
             * @since v1.0.0
             * @param $data
             */
            $updateUserData = apply_filters('fluent_support/update_user_data', $data);
            wp_update_user($updateUserData);

            /*
             * Action after updating a customer/user
             *
             * @since v1.0.0
             * @param array $data
             */
            do_action('fluent_support/after_updating_user', $data);
        }
    }

    /**
     * assignRole method will assign role to a given user id
     * @param $userId
     */
    protected function assignRole($userId)
    {
        $user = new \WP_User($userId);

        /*
         * Action before assigning role to registered user
         *
         * @since v1.0.0
         * @param array $data
         */
        do_action('fluent_support/before_assigning_role', $user);
        /*
         * Filter user assignable role after signup
         *
         * @since v1.0.0
         * @param string $setRole WordPress user role key
         */
        $setRole = apply_filters('fluent_support/user_role', 'subscriber');
        $user->set_role($setRole);

        /*
         * Action after assigning role to registered user
         *
         * @since v1.0.0
         * @param array $data
         */
        do_action('fluent_support/after_assigning_role', $user);
    }


    /**
     * login method will clear existing cookies and set new cookie for a given user id
     * @param $userId
     */
    protected function login($userId)
    {
        /*
         * Action before login
         *
         * @since v1.0.0
         * @param integer $userId
         */
        do_action('fluent_support/before_logging_in_user', $userId);

        wp_clear_auth_cookie();
        wp_set_current_user($userId);
        wp_set_auth_cookie($userId);

        /*
         * Action after login
         *
         * @since v1.0.0
         * @param integer $userId
         */
        do_action('fluent_support/after_logging_in_user', $userId);
    }
}

```
