...
This commit is contained in:
parent
a9e7afd13a
commit
ba3de1ae99
31 changed files with 329 additions and 5 deletions
|
|
@ -0,0 +1,115 @@
|
|||
```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" => []
|
||||
]);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
|
@ -0,0 +1,71 @@
|
|||
https://www.youtube.com/watch?v=_ZRHt-fWJpc&list=PLT9miexWCpPW6Z_OXNv2d78cqCrZaPrVG&index=29
|
||||
|
||||
app/Config/Routes.php
|
||||
|
||||
Remember: Shield added =>
|
||||
```php
|
||||
service('auth')->routes($routes)
|
||||
```
|
||||
|
||||
```php
|
||||
// API routes (put below service('auth'))
|
||||
$routes->group("api", ["namespace" => "App\Controller\Api"], function($routes) {
|
||||
$routes->post("register", "AuthController::register");
|
||||
$routes->post("login", "AuthController::login");
|
||||
$routes->get("profile", "AuthController::profile");
|
||||
$routes->get("logout", "AuthController::logout", ["filter"=>"apiauth"]);
|
||||
|
||||
//$routes->post("add-project", "ProjectController::addProject");
|
||||
//$routes->get("list-projects", "ProjectController::listProjects");
|
||||
//$routes->delete("delete-project/(:num)", "ProjectController::deleteProject/$1");
|
||||
});
|
||||
```
|
||||
|
||||
$routes->get("logout", "AuthController::logout", ["filter" => "apiauth"]);
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
```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" => []
|
||||
]);
|
||||
}
|
||||
|
||||
}
|
||||
```
|
||||
|
|
@ -0,0 +1,41 @@
|
|||
```bash
|
||||
php spark make:model Board --suffix
|
||||
php spark make:controller Api/Board --suffix --restful
|
||||
```
|
||||
|
||||
|
||||
Add allowed fields to model:
|
||||
(BoardModel.php)
|
||||
```php
|
||||
$allowedFields = ["name"];
|
||||
```
|
||||
|
||||
|
||||
|
||||
```php
|
||||
php spark make:migration create_boards
|
||||
```
|
||||
|
||||
Migration file:
|
||||
|
||||
```php
|
||||
//up:
|
||||
$this->forge->addField([
|
||||
"id" => [ "type"=>"INT", "constraint"=>5, "auto increment" => true, "unsigned" => true ],
|
||||
"name" => [ "type"=>"VARCHAR", "constraint" => 120, "null" => false ]
|
||||
]);
|
||||
$this->forge->addPrimaryKey("id);
|
||||
$this->forge->createTable("boards");
|
||||
|
||||
//down:
|
||||
$this->forge->dropTable("boards");
|
||||
```
|
||||
|
||||
|
||||
```bash
|
||||
php spark migrate:status
|
||||
|
||||
php spark migrate
|
||||
```
|
||||
|
||||
Create seeder ?
|
||||
|
|
@ -0,0 +1,40 @@
|
|||
Inside Devilbox container:
|
||||
```bash
|
||||
devilbox@php-8.1.14 in /shared/httpd $ pwd
|
||||
/shared/httpd
|
||||
|
||||
|
||||
mkdir myproject
|
||||
cd myproject
|
||||
composer create-project codeigniter4/appstarter myprojectapp
|
||||
ln -s myprojectapp/public htdocs
|
||||
```
|
||||
|
||||
|
||||
Add shield:
|
||||
```bash
|
||||
composer require codeigniter4/shield
|
||||
```
|
||||
|
||||
In case of issues, see installation.
|
||||
```bash
|
||||
composer config minimum-stability dev
|
||||
composer config prefer-stable true
|
||||
```
|
||||
|
||||
```bash
|
||||
php spark shield:setup
|
||||
```
|
||||
|
||||
####
|
||||
|
||||
SET DEFAULT LOCALE
|
||||
|
||||
|
||||
Config/App.php
|
||||
```php
|
||||
|
||||
public bool $negotiateLocale = true;
|
||||
public string $defaultLocale = 'en';
|
||||
public array $supportedLocales = ['en', 'de'];
|
||||
```
|
||||
|
|
@ -6,7 +6,7 @@ Creates Controller, Model, Migration, Seeder
|
|||
```php
|
||||
//up:
|
||||
$this->forge->addField((["id"=>
|
||||
["type"=>"INT,
|
||||
["type"=>"INT",
|
||||
"constraint"=>5,
|
||||
"auto increment" => true,
|
||||
"unsigned" => true
|
||||
|
|
@ -51,7 +51,6 @@ https://onlinewebtutorblog.com/codeigniter-4-restful-api-using-shield-authentica
|
|||
|
||||
My version:
|
||||
```php
|
||||
|
||||
use CodeIgniter\Restful\ResourceController;
|
||||
use CodeIgniter\Shield\Models\UserModel;
|
||||
use CodeIgniter\Shield\Entities\User;
|
||||
|
|
@ -8,7 +8,6 @@ In AuthController::login:
|
|||
|
||||
|
||||
```php
|
||||
|
||||
// Post
|
||||
public function login()
|
||||
{
|
||||
|
|
@ -66,10 +65,8 @@ In AuthController::login:
|
|||
];
|
||||
}
|
||||
}
|
||||
|
||||
return $this->respondCreated($response);
|
||||
}
|
||||
|
||||
```
|
||||
https://shield.codeigniter.com/references/authentication/tokens/
|
||||
|
||||
|
|
@ -0,0 +1,61 @@
|
|||
https://www.youtube.com/watch?v=USqOc-GCA4s&list=PLT9miexWCpPW6Z_OXNv2d78cqCrZaPrVG&index=32
|
||||
|
||||
Create AuthFilter.php
|
||||
```bash
|
||||
php spark make:filter Auth --suffix
|
||||
```
|
||||
|
||||
Define before method in AuthFilter.php
|
||||
```php
|
||||
public function before(RequestInterface $request, $arguments = null)
|
||||
{
|
||||
helper("auth");
|
||||
|
||||
if (!auth("tokens")->loggedIn()) {
|
||||
return redirect()->to(base_url("api/ invalid-access")); // need to create invalid-access route
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
Routes.php
|
||||
```php
|
||||
// API ROUTES
|
||||
$routes->group("api",["namespace]=> "App\Controllers\Api"], function($routes) {
|
||||
...
|
||||
$routes->get("invalid-access", "AuthController::accessDenied");
|
||||
§routes->get('demo-method", "AuthController::demoMethod",["filter" => "apiauth"]); // Filter Name is defined in aliases array in Filters.php below.
|
||||
...
|
||||
```
|
||||
|
||||
Define accessDenied method in app/Controllers/Api/AuthController.php
|
||||
```php
|
||||
...
|
||||
public function accessDenied()
|
||||
{
|
||||
return $this->respondCreated([
|
||||
"status" => false,
|
||||
"message" => "Invalid access",
|
||||
"data" => []
|
||||
]);
|
||||
}
|
||||
...
|
||||
```
|
||||
|
||||
Add filter to app/Config/Filters.php
|
||||
```php
|
||||
use App\Filters\AuthFilter;
|
||||
|
||||
|
||||
public array $aliases = [
|
||||
'csrf' => CSRF::class,
|
||||
'toolbar' => DebugToolbar::class,
|
||||
'honeypot' => Honeypot::class,
|
||||
'invalidchars' => InvalidChars::class,
|
||||
'secureheaders' => SecureHeaders::class,
|
||||
'apiauth' => AuthFilter::class
|
||||
]
|
||||
```
|
||||
|
||||
Authorize request by adding field "Authorization" with value "Bearer xxxxxx" in Request Header:
|
||||
![[Pasted image 20241127140801.png]]
|
||||
Loading…
Add table
Add a link
Reference in a new issue