M
M
Mikha Pankratov2015-03-11 01:37:33
JavaScript
Mikha Pankratov, 2015-03-11 01:37:33

How to implement Yii AJAX authorization?

Hi all!
So, I am doing authorization on the site ... There is a form, there is data that is sent.

AJAX request

var loginis = (function () { 
    var psw = $("#password2").val();
    var email = $("#mail2").val();
    
        $.ajax({
            type: 'POST',
            url: "site/loginis",
            data: {'password':psw, 'login':email},
            error: function(e) {
              console.log(e);
            }
        });
});


Controller - action
public function actionLoginis(){
        if (Yii::$app->request->isAjax) {
            //ищем пользователя с таким psw and login
            if($data = Users::findUserByAouth(Yii::$app->request->post())){
                //нашли авторизуемся...?? 
                return Users::findByEAuth($data);
//                return json_encode(array("data" => $data, "success" => true )); 
            }  else {
               echo json_encode(array('success'=>false));
            }
        }
    }

// сама функция findByEAuth
public static function findByEAuth($data) {
       if (empty($data)) {
                   throw new ErrorException('');
           }

           $id = 'servis-'.$data['id'];
           
           $attributes = array(
                   'id' => $data['id'],
                   'username' => $data['name'],
                   'authKey' => md5($data['id']),
           );
              
            $attributes['profile'] = $data;
            $attributes['profile']['service'] = 'servis';
            Yii::$app->getSession()->set('user-'.$id, $attributes);   
            return new self($attributes);
   }


I use authorization with vk and just authorization.
And I received the data, and recorded the session, but there is no authorization - the form is in place ....
Maybe I'm doing everything wrong in general? Tell me how to do it right and how to make it work? :)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rikcon, 2015-03-11
@Rikcon

You seem to have forgotten to login yourself
(This code was pulled from the default LoginForm.php model)
Here is the full code of the function if anything.

/**
     * Logs in a user using the provided username and password.
     * @return boolean whether the user is logged in successfully
     */
    public function login()
    {
        if ($this->validate()) {
            return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0);
        } else {
            return false;
        }
    }

The parameters that you pass to user-> login must be replaced with yours.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question