Answer the question
In order to leave comments, you need to log in
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);
}
});
});
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);
}
Answer the question
In order to leave comments, you need to log in
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;
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question