Refactor code structure for improved readability and maintainability
Co-authored-by: Copilot <copilot@github.com>
This commit is contained in:
@@ -0,0 +1,26 @@
|
||||
import 'dart:convert';
|
||||
|
||||
/// Decodes a JWT token payload without verifying signature.
|
||||
/// Returns the decoded claims or an empty map on failure.
|
||||
Map<String, dynamic> decodeJwtPayload(String token) {
|
||||
try {
|
||||
final parts = token.split('.');
|
||||
if (parts.length != 3) return {};
|
||||
// Normalize base64url to standard base64.
|
||||
final payload = base64Url.normalize(parts[1]);
|
||||
final decoded = utf8.decode(base64Url.decode(payload));
|
||||
return json.decode(decoded) as Map<String, dynamic>;
|
||||
} catch (_) {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the role claim from a JWT token. Defaults to 'user'.
|
||||
String jwtRole(String? token) {
|
||||
if (token == null || token.isEmpty) return 'user';
|
||||
final claims = decodeJwtPayload(token);
|
||||
return claims['role'] as String? ?? 'user';
|
||||
}
|
||||
|
||||
/// Returns true if the JWT token contains role == 'admin'.
|
||||
bool jwtIsAdmin(String? token) => jwtRole(token) == 'admin';
|
||||
Reference in New Issue
Block a user