Hi, does anyone have an example of how to implement a login system in Yii3?
I tried using the documentation, but I got lost.
Hi, does anyone have an example of how to implement a login system in Yii3?
I tried using the documentation, but I got lost.
composer require yiisoft/auth yiisoft/user
// 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; }}
$passwordHash = password_hash('123456', PASSWORD_DEFAULT);
Save $passwordHash in database.
<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>
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";}
Route::post('/login', [LoginController::class, 'login']);
Open:
http://localhost/login
Login with:
username: adminpassword: 123456
$this->auth->logout();
if ($this->auth->isAuthenticated()) { echo "Logged In";}