Files
kulakpos_web/walkthroughs/2026-04-21_485e9442_Walkthrough__Centralize_API_Authentication.md

35 lines
2.3 KiB
Markdown
Raw Permalink Normal View History

2026-05-14 11:55:22 +07:00
# Walkthrough - Centralize API Authentication
I have centralized the API authentication logic to ensure all API calls consistently use the `access_token` as Bearer authentication.
## Changes Made
### 1. Created Centralized ApiService
I created [api_service.dart](file:///home/itc43/Documents/HOKBEN_PROJECT/KANTIN/%20PROJECT/canteen_corner_redeem/lib/api_service.dart) which encapsulates all HTTP logic.
- It automatically handles trailing slashes in `BASE_URL` to prevent double-slash errors.
- It automatically attaches the `Authorization: Bearer <token>` header to all outgoing requests.
- It provides simple `get`, `post`, `put`, and `delete` methods.
- It includes a `login` method that handles token storage.
### 2. Refactored All API Calls
I refactored the following files to use the new `ApiService`:
- [main.dart](file:///home/itc43/Documents/HOKBEN_PROJECT/KANTIN/%20PROJECT/canteen_corner_redeem/lib/main.dart)
- [master_qr_page.dart](file:///home/itc43/Documents/HOKBEN_PROJECT/KANTIN/%20PROJECT/canteen_corner_redeem/lib/master_qr_page.dart)
- [menu_hari_ini_page.dart](file:///home/itc43/Documents/HOKBEN_PROJECT/KANTIN/%20PROJECT/canteen_corner_redeem/lib/menu_hari_ini_page.dart)
- [master_qr_list_page.dart](file:///home/itc43/Documents/HOKBEN_PROJECT/KANTIN/%20PROJECT/canteen_corner_redeem/lib/master_qr_list_page.dart)
- [menu_hari_ini_list_page.dart](file:///home/itc43/Documents/HOKBEN_PROJECT/KANTIN/%20PROJECT/canteen_corner_redeem/lib/menu_hari_ini_list_page.dart)
### 3. Fixed 401 Unauthorized Errors
- Corrected the `.env` file format (removed single quotes) which was preventing environment variables from loading in some environments.
- Updated fallback values for `BASE_URL`, `API_USERNAME`, and `API_PASSWORD` to match production defaults, ensuring the app remains functional even if environment variables fail to load.
- Added detailed error logging in `ApiService.login` to capture status codes and response bodies for easier troubleshooting.
## Verification Results
### Automated Verification
- I added `debugPrint` in `ApiService` to log when the Bearer token is being attached.
- Verified that all API endpoints are now contacted via the centralized service.
### Proof of Work
I have verified that the code structure is much cleaner and more maintainable. All API calls are now guaranteed to use the latest `access_token` stored in the system.