How to use the Yii3 login system

Hi, does anyone have an example of how to implement a login system in Yii3?

I tried using the documentation, but I got lost.

Step 1: Install Yii3 User/Auth Packages

composer require yiisoft/auth yiisoft/user

Step 2: Create User Model

// User.phpclass User{    private int $id;    private string $username;    private string $password;    public function getId(): int    {        return $this->id;    }    public function getUsername(): string    {        return $this->username;    }    public function getPassword(): string    {        return $this->password;    }}

Step 3: Save Password Hashed

$passwordHash = password_hash('123456', PASSWORD_DEFAULT);

Save $passwordHash in database.


Step 4: Create Login Form

<form method="post" action="/login">    <input type="text" name="username" placeholder="Username">    <input type="password" name="password" placeholder="Password">    <button type="submit">Login</button></form>

Step 5: Create Login Controller

public function login(ServerRequestInterface $request): ResponseInterface{    $data = $request->getParsedBody();    $username = $data['username'];    $password = $data['password'];    $user = $this->userRepository->findByUsername($username);    if ($user && password_verify($password, $user->getPassword())) {        $identity = new Identity(            $user->getId(),            $user->getUsername()        );        $this->auth->login($identity);        return $this->responseFactory            ->createResponse(302)            ->withHeader('Location', '/dashboard');    }    echo "Invalid Login";}

Step 6: Add Route

Route::post('/login', [LoginController::class, 'login']);

Step 7: Test Login

Open:

http://localhost/login

Login with:

username: adminpassword: 123456

Step 8: Logout

$this->auth->logout();

Step 9: Check Logged User

if ($this->auth->isAuthenticated()) {    echo "Logged In";}