4
4
4sadly2020-04-28 10:38:21
PHP
4sadly, 2020-04-28 10:38:21

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

3 answer(s)
I
Ilya, 2020-04-28
@4sadly

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.

R
Roman Sarvarov, 2020-04-28
@megakor

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');
}

N
Northern Lights, 2020-04-28
@php666

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
}

authentication:
$auth = new Authorization(/* передаем объект запроса или _REQUEST */);
$current_user = $auth->processAuthentication(); // или null если не аутентифицировались

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question