Answer the question
In order to leave comments, you need to log in
How to properly authenticate a user?
I want to make authentication in the user class, how best to do it?
I think the login method should return a user instance if successful, am I right?
What about the password verification method? Is it better to make it static or not?
Answer the question
In order to leave comments, you need to log in
If you are using ActiveRecord, then make a static login() method that will return the user data. The password check method is also static (it does not depend on the context).
-
And it’s better to move operations ABOVE the user (which do not work with a user instance) into a separate class (for example, UserService), and leave the operations INSIDE the user (which work with user data) in the model.
Something like:
$user = User::where('login', $postData['login'])->first(); // На примере ORM Eloquent, тут ищется и возвращается экземпляр класса-модели пользователя с этим логином.
if (!$user || !password_verify($postData['password'], $user->password)) {
throw new UserLoginException('Неверный логин или пароль!');
} else {
$_SESSION['user_id'] = $user->id;
Http::redirect('/profile');
}
authentication is not the scope of the user class
authentication is the scope of the Authorization class (or whatever you want to call it)
authorization:
$auth = new Authorization(/* передаем объект запроса или _REQUEST */);
if ($auth->processAuthorization('login', 'password') { // set cookies/sessions and redirect
// redirect to other
}
$auth = new Authorization(/* передаем объект запроса или _REQUEST */);
$current_user = $auth->processAuthentication(); // или null если не аутентифицировались
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question