Update JWT Success
This commit is contained in:
parent
8709788114
commit
37816b8b7b
@ -35,6 +35,7 @@ class Filters extends BaseFilters
|
|||||||
'forcehttps' => ForceHTTPS::class,
|
'forcehttps' => ForceHTTPS::class,
|
||||||
'pagecache' => PageCache::class,
|
'pagecache' => PageCache::class,
|
||||||
'performance' => PerformanceMetrics::class,
|
'performance' => PerformanceMetrics::class,
|
||||||
|
'auth' => \App\Filters\AuthFilter::class,
|
||||||
];
|
];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -70,10 +71,11 @@ class Filters extends BaseFilters
|
|||||||
*/
|
*/
|
||||||
public array $globals = [
|
public array $globals = [
|
||||||
'before' => [
|
'before' => [
|
||||||
'cors'
|
// 'auth',
|
||||||
// 'honeypot',
|
'cors',
|
||||||
// 'csrf',
|
'honeypot',
|
||||||
// 'invalidchars',
|
'csrf',
|
||||||
|
'invalidchars',
|
||||||
],
|
],
|
||||||
'after' => [
|
'after' => [
|
||||||
// 'honeypot',
|
// 'honeypot',
|
||||||
|
|||||||
@ -16,11 +16,15 @@ $routes->post('/api/v1/emr/lab/insert', 'NUHATEMP::create');
|
|||||||
$routes->post('/api/v1/emr/lab/update-validasi', 'NUHATEMP::update');
|
$routes->post('/api/v1/emr/lab/update-validasi', 'NUHATEMP::update');
|
||||||
$routes->post('/api/v1/emr/lab/detail', 'NUHATEMP::detail');
|
$routes->post('/api/v1/emr/lab/detail', 'NUHATEMP::detail');
|
||||||
|
|
||||||
$routes->post('/api/auth/login/', 'Auth::login');
|
// $routes->group('api', ['filter' => 'auth'], function($routes) {
|
||||||
$routes->post('/api/auth/change_pass/', 'Auth::change_pass');
|
$routes->post('/api/coba-auth', 'Auth::coba');
|
||||||
$routes->post('/api/auth/register/', 'Auth::register');
|
|
||||||
$routes->get('/api/auth/check/', 'Auth::checkAuth');
|
$routes->post('/api/auth/login', 'Auth::login');
|
||||||
$routes->post('/api/auth/logout/', 'Auth::logout');
|
$routes->post('/api/auth/change_pass', 'Auth::change_pass');
|
||||||
|
$routes->post('/api/auth/register', 'Auth::register');
|
||||||
|
$routes->get('/api/auth/check', 'Auth::checkAuth');
|
||||||
|
$routes->post('/api/auth/logout', 'Auth::logout');
|
||||||
|
// });
|
||||||
|
|
||||||
$routes->get('/api/patient', 'Patient::index');
|
$routes->get('/api/patient', 'Patient::index');
|
||||||
$routes->post('/api/patient', 'Patient::create');
|
$routes->post('/api/patient', 'Patient::create');
|
||||||
|
|||||||
@ -4,62 +4,79 @@ namespace App\Controllers;
|
|||||||
|
|
||||||
use CodeIgniter\API\ResponseTrait;
|
use CodeIgniter\API\ResponseTrait;
|
||||||
use CodeIgniter\Controller;
|
use CodeIgniter\Controller;
|
||||||
use \Firebase\JWT\JWT;
|
|
||||||
|
use Firebase\JWT\JWT;
|
||||||
|
use Firebase\JWT\Key;
|
||||||
|
use Firebase\JWT\ExpiredException;
|
||||||
|
use Firebase\JWT\SignatureInvalidException;
|
||||||
|
use Firebase\JWT\BeforeValidException;
|
||||||
use CodeIgniter\Cookie\Cookie;
|
use CodeIgniter\Cookie\Cookie;
|
||||||
|
|
||||||
class Auth extends Controller {
|
class Auth extends Controller {
|
||||||
use ResponseTrait;
|
use ResponseTrait;
|
||||||
|
|
||||||
|
// ok
|
||||||
public function __construct() {
|
public function __construct() {
|
||||||
$this->db = \Config\Database::connect();
|
$this->db = \Config\Database::connect();
|
||||||
}
|
}
|
||||||
|
|
||||||
// public function login() {
|
// ok
|
||||||
// $username = $this->request->getVar('username');
|
public function checkAuth() {
|
||||||
// $password = $this->request->getVar('password');
|
$token = $this->request->getCookie('token');
|
||||||
// $key = getenv('JWT_SECRET');
|
$key = getenv('JWT_SECRET');
|
||||||
|
|
||||||
// if (!$username) {
|
// Jika token FE tidak ada langsung kabarkan failed
|
||||||
// return $this->fail('Username required.', 400);
|
if (!$token) {
|
||||||
// }
|
return $this->respond([
|
||||||
|
'status' => 'failed',
|
||||||
|
'message' => 'No token found'
|
||||||
|
], 401);
|
||||||
|
}
|
||||||
|
|
||||||
// $sql = "SELECT * FROM users WHERE username=".$this->db->escape($username);
|
try {
|
||||||
// $query = $this->db->query($sql);
|
// Decode Token dengan Key yg ada di .env
|
||||||
// $row = $query->getRowArray();
|
$decodedPayload = JWT::decode($token, new Key($key, 'HS256'));
|
||||||
|
|
||||||
// if (!$row) {
|
return $this->respond([
|
||||||
// return $this->fail('User not found.', 401); // Use 401 for authentication failures
|
'status' => 'success',
|
||||||
// }
|
'message' => 'Authenticated',
|
||||||
|
'data' => $decodedPayload
|
||||||
|
], 200);
|
||||||
|
|
||||||
// if (!password_verify($password, $row['password'])) {
|
} catch (ExpiredException $e) {
|
||||||
// return $this->fail('Invalid password.', 401);
|
return $this->respond([
|
||||||
// }
|
'status' => 'failed',
|
||||||
|
'message' => 'Token expired',
|
||||||
|
'data' => []
|
||||||
|
], 401);
|
||||||
|
|
||||||
// // JWT payload
|
} catch (SignatureInvalidException $e) {
|
||||||
// $payload = [
|
return $this->respond([
|
||||||
// 'userid' => $row['id'],
|
'status' => 'failed',
|
||||||
// 'username' => $row['username'],
|
'message' => 'Invalid token signature',
|
||||||
// 'exp' => time() + 3600
|
'data' => []
|
||||||
// ];
|
], 401);
|
||||||
|
|
||||||
// try {
|
} catch (BeforeValidException $e) {
|
||||||
// $jwt = JWT::encode($payload, $key, 'HS256');
|
return $this->respond([
|
||||||
// } catch (Exception $e) {
|
'status' => 'failed',
|
||||||
// return $this->fail('Error generating JWT: ' . $e->getMessage(), 500);
|
'message' => 'Token not valid yet',
|
||||||
// }
|
'data' => []
|
||||||
|
], 401);
|
||||||
|
|
||||||
// // Update last_login
|
} catch (\Exception $e) {
|
||||||
// //$this->userModel->update($user['id'], ['lastlogin' => date('Y-m-d H:i:s')]);
|
return $this->respond([
|
||||||
|
'status' => 'failed',
|
||||||
|
'message' => 'Invalid token: ' . $e->getMessage(),
|
||||||
|
'data' => []
|
||||||
|
], 401);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// $response = [
|
// ok
|
||||||
// 'status' => 'success',
|
|
||||||
// 'message' => 'Login successful',
|
|
||||||
// 'token' => $jwt,
|
|
||||||
// ];
|
|
||||||
// return $this->respond($response);
|
|
||||||
// }
|
|
||||||
public function login() {
|
public function login() {
|
||||||
|
|
||||||
|
// Ambil dari JSON Form dan Key .env
|
||||||
$username = $this->request->getVar('username');
|
$username = $this->request->getVar('username');
|
||||||
$password = $this->request->getVar('password');
|
$password = $this->request->getVar('password');
|
||||||
$key = getenv('JWT_SECRET');
|
$key = getenv('JWT_SECRET');
|
||||||
@ -80,104 +97,105 @@ class Auth extends Controller {
|
|||||||
return $this->fail('Invalid password.', 401);
|
return $this->fail('Invalid password.', 401);
|
||||||
}
|
}
|
||||||
|
|
||||||
// JWT payload
|
// Buat JWT payload
|
||||||
$payload = [
|
$payload = [
|
||||||
'userid' => $row['id'],
|
'userid' => $row['id'],
|
||||||
'username' => $row['username'],
|
'username' => $row['username'],
|
||||||
'exp' => time() + 3600
|
'exp' => time() + 86400 // 1 hari
|
||||||
];
|
];
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
// Melakukan Hash terhadap Payload dengan Kunci .env menggunakan Algortima HMAC + SHA-256
|
||||||
$jwt = JWT::encode($payload, $key, 'HS256');
|
$jwt = JWT::encode($payload, $key, 'HS256');
|
||||||
} catch (Exception $e) {
|
} catch (Exception $e) {
|
||||||
return $this->fail('Error generating JWT: ' . $e->getMessage(), 500);
|
return $this->fail('Error generating JWT: ' . $e->getMessage(), 500);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Set cookie (HttpOnly + Secure + SameSite=Strict)
|
// Kirim Respon ke HttpOnly yg akan disimpan di browser dan tidak akan dapat diakses oleh siapapun
|
||||||
$this->response->setCookie([
|
$this->response->setCookie([
|
||||||
'name' => 'token',
|
'name' => 'token', // nama token
|
||||||
'value' => $jwt,
|
'value' => $jwt, // value dari jwt yg sudah di hash
|
||||||
'expire' => 3600, // 1 jam
|
'expire' => 86400, // 1 hari
|
||||||
'path' => '/',
|
'path' => '/', // valid untuk semua path
|
||||||
'secure' => true, // set true kalau sudah HTTPS
|
'secure' => true, // set true kalau sudah HTTPS
|
||||||
'httponly' => true,
|
'httponly' => true, // dipakai agar cookie berikut tidak dapat diakses oleh javascript
|
||||||
'samesite' => Cookie::SAMESITE_NONE // set true kalau sudah HTTPS
|
'samesite' => Cookie::SAMESITE_NONE
|
||||||
// 'samesite' => Cookie::SAMESITE_STRICT
|
|
||||||
]);
|
]);
|
||||||
|
|
||||||
// Response tanpa token di body
|
// Response tanpa token di body
|
||||||
return $this->respond([
|
return $this->respond([
|
||||||
'status' => 'success',
|
'status' => 'success',
|
||||||
'message' => 'Login successful'
|
'message' => 'Login successful'
|
||||||
]);
|
], 200);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function change_pass() {
|
// ok
|
||||||
$db = \Config\Database::connect();
|
public function logout() {
|
||||||
$username = $this->request->getJsonVar('username');
|
// Definisikan ini pada cookies browser, harus sama dengan cookies login
|
||||||
$password = $this->request->getJsonVar('password');
|
return $this->response->setCookie([
|
||||||
$password = password_hash($password, PASSWORD_DEFAULT);
|
'name' => 'token',
|
||||||
|
'value' => '',
|
||||||
|
'expire' => time() - 3600,
|
||||||
|
'path' => '/',
|
||||||
|
'secure' => true,
|
||||||
|
'httponly' => true,
|
||||||
|
'samesite' => Cookie::SAMESITE_NONE
|
||||||
|
|
||||||
$master = $this->request->getJsonVar('master');
|
])->setJSON([
|
||||||
$masterkey = getenv('masterkey');
|
'status' => 'success',
|
||||||
|
'message' => 'Logout successful'
|
||||||
if($master != $masterkey) {
|
], 200);
|
||||||
return $this->fail('Invalid master key.', 401);
|
|
||||||
}
|
|
||||||
|
|
||||||
$sql = "update users set password='$password' where username='$username'";
|
|
||||||
$query = $db->query($sql);
|
|
||||||
$response = [
|
|
||||||
'message' => "Password Changed for $username"
|
|
||||||
];
|
|
||||||
return $this->respond($response);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ok
|
||||||
public function register() {
|
public function register() {
|
||||||
|
|
||||||
$username = $this->request->getJsonVar('username');
|
$username = $this->request->getJsonVar('username');
|
||||||
$password = $this->request->getJsonVar('password');
|
$password = $this->request->getJsonVar('password');
|
||||||
$password = password_hash($password, PASSWORD_DEFAULT);
|
|
||||||
|
|
||||||
// $master = $this->request->getJsonVar('master');
|
// Validasi
|
||||||
// $masterkey = getenv('MASTERKEY');
|
if (empty($username) || empty($password)) {
|
||||||
|
|
||||||
// if($master != $masterkey) {
|
|
||||||
// return $this->fail('Invalid master key.', 401);
|
|
||||||
// }
|
|
||||||
|
|
||||||
$sql = "INSERT INTO users(username, password) values('$username', '$password')";
|
|
||||||
$this->db->query($sql);
|
|
||||||
$response = [
|
|
||||||
'message' => "User $username created"
|
|
||||||
];
|
|
||||||
return $this->respondCreated($response);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function checkAuth() {
|
|
||||||
$token = $this->request->getCookie('token');
|
|
||||||
$key = getenv('JWT_SECRET');
|
|
||||||
|
|
||||||
if (!$token) {
|
|
||||||
return $this->fail('No token found', 401);
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
$decoded = JWT::decode($token, new Key($key, 'HS256'));
|
|
||||||
return $this->respond([
|
return $this->respond([
|
||||||
'status' => 'success',
|
'status' => 'failed',
|
||||||
'message' => 'Authenticated',
|
'message' => 'Username and password are required'
|
||||||
'data' => $decoded
|
], 400); // Gunakan 400 Bad Request
|
||||||
]);
|
|
||||||
} catch (\Exception $e) {
|
|
||||||
return $this->fail('Invalid or expired token: ' . $e->getMessage(), 401);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
$password = password_hash($password, PASSWORD_DEFAULT);
|
||||||
|
$sql = "INSERT INTO users(username, password) values('$username', '$password')";
|
||||||
|
|
||||||
|
return $this->respond([
|
||||||
|
'status' => 'success',
|
||||||
|
'message' => 'User '.$username.' created'
|
||||||
|
], 201);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function logout() {
|
// public function change_pass() {
|
||||||
return $this->response
|
// $db = \Config\Database::connect();
|
||||||
->deleteCookie('token')
|
// $username = $this->request->getJsonVar('username');
|
||||||
->setJSON(['message' => 'Logout successful']);
|
// $password = $this->request->getJsonVar('password');
|
||||||
|
// $password = password_hash($password, PASSWORD_DEFAULT);
|
||||||
|
|
||||||
|
// $master = $this->request->getJsonVar('master');
|
||||||
|
// $masterkey = getenv('masterkey');
|
||||||
|
|
||||||
|
// if($master != $masterkey) {
|
||||||
|
// return $this->fail('Invalid master key.', 401);
|
||||||
|
// }
|
||||||
|
|
||||||
|
// $sql = "update users set password='$password' where username='$username'";
|
||||||
|
// $query = $db->query($sql);
|
||||||
|
// $response = [
|
||||||
|
// 'message' => "Password Changed for $username"
|
||||||
|
// ];
|
||||||
|
// return $this->respond($response);
|
||||||
|
// }
|
||||||
|
|
||||||
|
public function coba() {
|
||||||
|
return $this->respond([
|
||||||
|
'status' => 'success',
|
||||||
|
'message' => 'Already Login'
|
||||||
|
],200);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
50
app/Filters/AuthFilter.php
Normal file
50
app/Filters/AuthFilter.php
Normal file
@ -0,0 +1,50 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Filters;
|
||||||
|
|
||||||
|
use CodeIgniter\HTTP\RequestInterface;
|
||||||
|
use CodeIgniter\HTTP\ResponseInterface;
|
||||||
|
use CodeIgniter\Filters\FilterInterface;
|
||||||
|
use Config\Services;
|
||||||
|
use Firebase\JWT\JWT;
|
||||||
|
use Firebase\JWT\Key;
|
||||||
|
|
||||||
|
class AuthFilter implements FilterInterface
|
||||||
|
{
|
||||||
|
public function before(RequestInterface $request, $arguments = null)
|
||||||
|
{
|
||||||
|
$key = getenv('JWT_SECRET');
|
||||||
|
$token = $request->getCookie('token'); // ambil dari cookie
|
||||||
|
|
||||||
|
// Kalau tidak ada token
|
||||||
|
if (!$token) {
|
||||||
|
return Services::response()
|
||||||
|
->setStatusCode(401)
|
||||||
|
->setJSON([
|
||||||
|
'status' => 'failed',
|
||||||
|
'message' => 'Unauthorized: Token not found'
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Decode JWT : jika error maka akan mentrigger catch
|
||||||
|
$decoded = JWT::decode($token, new Key($key, 'HS256'));
|
||||||
|
|
||||||
|
// Kalau mau, bisa inject user info ke request
|
||||||
|
// $request->userData = $decoded;
|
||||||
|
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
return Services::response()
|
||||||
|
->setStatusCode(401)
|
||||||
|
->setJSON([
|
||||||
|
'status' => 'failed',
|
||||||
|
'message' => 'Unauthorized: ' . $e->getMessage()
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
|
||||||
|
{
|
||||||
|
// Tidak perlu apa-apa
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
x
Reference in New Issue
Block a user