91 lines
1.8 KiB
Markdown
91 lines
1.8 KiB
Markdown
|
|
https://www.youtube.com/watch?v=f0NifEgwh30&list=PLT9miexWCpPW6Z_OXNv2d78cqCrZaPrVG&index=33
|
||
|
|
|
||
|
|
|
||
|
|
```php
|
||
|
|
auth()->user()
|
||
|
|
```
|
||
|
|
|
||
|
|
|
||
|
|
```php
|
||
|
|
$userId = auth()->id();
|
||
|
|
```
|
||
|
|
|
||
|
|
![[Pasted image 20241129092837.png]]
|
||
|
|
|
||
|
|
|
||
|
|
|
||
|
|
|
||
|
|
|
||
|
|
|
||
|
|
|
||
|
|
|
||
|
|
|
||
|
|
AuthController
|
||
|
|
```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 {
|
||
|
|
|
||
|
|
// to test: directly getting $userObject via auth()->user()
|
||
|
|
|
||
|
|
// We have a valid data set
|
||
|
|
$userObject = new UserModel();
|
||
|
|
|
||
|
|
$userData = $userObject->findById(auth()->id());
|
||
|
|
|
||
|
|
$token = $userData->generateAccessToken("thisismysecretkey");
|
||
|
|
|
||
|
|
$auth_token = $token->raw_token;
|
||
|
|
|
||
|
|
$response = [
|
||
|
|
"status" => true,
|
||
|
|
"message" => "User logged in successfully",
|
||
|
|
"data" => [
|
||
|
|
"token" => $auth_token
|
||
|
|
]
|
||
|
|
];
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
return $this->respondCreated($response);
|
||
|
|
}
|
||
|
|
|
||
|
|
//...
|
||
|
|
```
|