74 lines
1.9 KiB
Markdown
74 lines
1.9 KiB
Markdown
https://www.youtube.com/watch?v=XJHFtfQQmRs&list=PLT9miexWCpPW6Z_OXNv2d78cqCrZaPrVG&index=31
|
|
|
|
https://onlinewebtutorblog.com/codeigniter-4-restful-api-using-shield-authentication/
|
|
|
|
In AuthController::login:
|
|
|
|
|
|
|
|
|
|
```php
|
|
|
|
// Post
|
|
public function login()
|
|
{
|
|
|
|
if(auth()->loggedIn()){
|
|
auth()->logout();
|
|
}
|
|
|
|
$rules = [
|
|
"email" => "required|valid_email",
|
|
"password" => "required"
|
|
];
|
|
|
|
if (!$this->validate($rules)) {
|
|
|
|
$response = [
|
|
"status" => false,
|
|
"message" => $this->validator->getErrors(),
|
|
"data" => []
|
|
];
|
|
} else {
|
|
|
|
// success
|
|
$credentials = [
|
|
"email" => $this->request->getVar("email"),
|
|
"password" => $this->request->getVar("password")
|
|
];
|
|
|
|
$loginAttempt = auth()->attempt($credentials);
|
|
|
|
if (!$loginAttempt->isOK()) {
|
|
|
|
$response = [
|
|
"status" => false,
|
|
"message" => "Invalid login details",
|
|
"data" => []
|
|
];
|
|
} else {
|
|
|
|
// We have a valid data set
|
|
$userObject = new UserModel();
|
|
|
|
$userData = $userObject->findById(auth()->id());
|
|
|
|
$token = $userData->generateAccessToken("thisismysecretkey");
|
|
|
|
$auth_token = $token->raw_token; // Only available after generation
|
|
|
|
$response = [
|
|
"status" => true,
|
|
"message" => "User logged in successfully",
|
|
"data" => [
|
|
"token" => $auth_token
|
|
]
|
|
];
|
|
}
|
|
}
|
|
|
|
return $this->respondCreated($response);
|
|
}
|
|
|
|
```
|
|
https://shield.codeigniter.com/references/authentication/tokens/
|