115 lines
No EOL
2.6 KiB
Markdown
115 lines
No EOL
2.6 KiB
Markdown
```bash
|
|
php spark make:controller Api/Auth --suffix --restful
|
|
```
|
|
|
|
|
|
Routes.php
|
|
```php
|
|
//Get
|
|
$routes->get("logout", "AuthController::logout", ["filter" => "apiauth"]);
|
|
```
|
|
|
|
|
|
Api/AuthController.php
|
|
```php
|
|
use CodeIgniter\Restful\ResourceController;
|
|
use CodeIgniter\Shield\Models\UserModel;
|
|
use CodeIgniter\Shield\Entities\User;
|
|
|
|
class AuthController extends ResourceController
|
|
{
|
|
//Post
|
|
public function register()
|
|
{
|
|
$rules = [
|
|
"username" => "required|is_unique[users.username]",
|
|
"email" => "required|valid_email|is_unique[auth_identities.secret]", // gets written to secret field in user table
|
|
"password" => "required" // gets written to secret 2 field in user table
|
|
];
|
|
|
|
if (!$this->validate($rules)) {
|
|
return $this->respondCreated([
|
|
"status" => false,
|
|
"message" => $this->validator->getErrors(),
|
|
"data" => []
|
|
]
|
|
);
|
|
|
|
$um = new UserModel(); // coming from Shield
|
|
$userEntity = new User([
|
|
"username" => $this->request->getVar("username"),
|
|
"email" => $this->request->getVar("email"),
|
|
"password" => $this->request->getVar("password")
|
|
]);
|
|
$um->save($userEntity);
|
|
|
|
return $this->respondCreated( [
|
|
"status" => true,
|
|
"message" => "User saved successfully",
|
|
"data" => []
|
|
]);
|
|
}
|
|
|
|
//////////////////////////////////////
|
|
|
|
// Post
|
|
public function login()
|
|
{
|
|
if(auth()->loggedIn()){
|
|
auth()->logout();
|
|
}
|
|
|
|
$rules = [
|
|
"email" => "required|valid_email",
|
|
"password" => "required"
|
|
];
|
|
|
|
if (!$this->validate($rules)) {
|
|
return $this->respondCreated([
|
|
"status" => false,
|
|
"message" => $this->validator->getErrors(),
|
|
"data" => []
|
|
]);
|
|
|
|
// success
|
|
$credentials = [
|
|
"email" => $this->request->getVar("email"),
|
|
"password" => $this->request->getVar("password")
|
|
];
|
|
|
|
$loginAttempt = auth()->attempt($credentials);
|
|
if (!$loginAttempt->isOK()) {
|
|
return $this->respondCreated([
|
|
"status" => false,
|
|
"message" => "Invalid login details",
|
|
"data" => []
|
|
]);
|
|
|
|
// We have a valid data set
|
|
$um = new UserModel();
|
|
$userData = $um->findById(auth()->id());
|
|
$token = $userData->generateAccessToken("thisismysecretkey");
|
|
$auth_token = $token->raw_token; // Only available after generation
|
|
|
|
return $this->respondCreated( [
|
|
"status" => true,
|
|
"message" => "User logged in successfully",
|
|
"data" => [
|
|
"token" => $auth_token
|
|
] );
|
|
}
|
|
|
|
////////////////////////
|
|
|
|
public function logout() {
|
|
auth()->logout();
|
|
auth()->user()->revokeAllAccessTokens();
|
|
|
|
return $this->respondCreated([
|
|
"status" => true,
|
|
"message" => "User logged out successfully",
|
|
"data" => []
|
|
]);
|
|
}
|
|
}
|
|
``` |