2.3 KiB
2.3 KiB
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 which encapsulates all HTTP logic.
- It automatically handles trailing slashes in
BASE_URLto prevent double-slash errors. - It automatically attaches the
Authorization: Bearer <token>header to all outgoing requests. - It provides simple
get,post,put, anddeletemethods. - It includes a
loginmethod that handles token storage.
2. Refactored All API Calls
I refactored the following files to use the new ApiService:
- main.dart
- master_qr_page.dart
- menu_hari_ini_page.dart
- master_qr_list_page.dart
- menu_hari_ini_list_page.dart
3. Fixed 401 Unauthorized Errors
- Corrected the
.envfile format (removed single quotes) which was preventing environment variables from loading in some environments. - Updated fallback values for
BASE_URL,API_USERNAME, andAPI_PASSWORDto match production defaults, ensuring the app remains functional even if environment variables fail to load. - Added detailed error logging in
ApiService.loginto capture status codes and response bodies for easier troubleshooting.
Verification Results
Automated Verification
- I added
debugPrintinApiServiceto 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.