Authentication
Table of contents
The first step to setting up the Authentication feature in the Puko Framework is to run the following command in your terminal:
php puko setup auth <auth_name>
You can choose any name relevant to the entity, such as StudentAuth or GuestAuth. You may implement multiple authentication features within a single project.
Example command:
php puko setup auth StudentAuth
After executing the command, a new class file will be automatically generated in the plugins/auth directory:
- plugins/
- auth/
- StudentAuth.php
If you open this file, you will find the following boilerplate methods:
public function Login($username, $password)
{
// TODO: Implement your custom login logic here
}
public function Logout()
{
// TODO: Implement logout logic (e.g., clearing database logs)
}
public function GetLoginData($id)
{
// TODO: Return your user data here
}
These methods should be customized to fit your specific authentication requirements.
Login($username, $password)
In the login function, you can validate the credentials received via the parameters using models, cURL requests, or other methods.
public function Login($username, $password)
{
$student = model\primary\StudentModel::GetByUsernamePassword($username, $password);
$dataToSecure = [
"id" => $student['id'],
"username" => $student['user'],
"class" => $student['class']
];
$permissions = ["STUDENT"];
return new PukoAuth($dataToSecure, $permissions);
}
Note: The login function must return a PukoAuth object.
To invoke the login process within a controller, use the following syntax:
$login = Session::Get(StudentAuth::Instance())->Login($username, $password);
StudentAuth::Instance() is a singleton object automatically managed by Puko to handle authentication.
- Session/Cookies: If the login is successful,
$loginwill betrue; otherwise, it will befalse. - Bearer Tokens: If successful,
$loginwill contain the encrypted token string. If it fails, it will befalse.
Logout()
This is the logout callback. You can add any necessary cleanup logic here.
public function Logout()
{
// Cleanup logic here
return true;
}
GetLoginData($id)
To validate authentication, Puko decodes the encrypted string generated during login. This process is simplified via the GetLoginData callback, which receives the decoded information.
The callback receives two parameters: $secure (containing the original $dataToSecure) and $permission (containing the permission codes).
public function GetLoginData($secure, $permission)
{
return [
"data" => $secure,
"authorization" => $permission
];
}
To protect a controller function from unauthenticated access, use the following doc tag:
/**
* #Auth session true
*/
public function create() {}