49 lines
2.1 KiB
JavaScript
49 lines
2.1 KiB
JavaScript
|
|
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
||
|
|
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
||
|
|
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
||
|
|
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
||
|
|
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
||
|
|
};
|
||
|
|
import { Injectable } from '@angular/core';
|
||
|
|
/**
|
||
|
|
* Client-side JWT *decoding* only - never verification. The signature is
|
||
|
|
* meaningless to check here because the frontend has no trusted key to check
|
||
|
|
* it against; verifying a JWT's signature is the backend's job on every
|
||
|
|
* request. This service exists purely so the UI can read `role`/`exp` for
|
||
|
|
* display and route-gating UX (e.g. "session expires in 4m").
|
||
|
|
*/
|
||
|
|
let JwtService = class JwtService {
|
||
|
|
decode(token) {
|
||
|
|
const parts = token.split('.');
|
||
|
|
if (parts.length !== 3) {
|
||
|
|
return null;
|
||
|
|
}
|
||
|
|
try {
|
||
|
|
const payload = this.base64UrlDecode(parts[1]);
|
||
|
|
const claims = JSON.parse(payload);
|
||
|
|
return this.isJwtClaims(claims) ? claims : null;
|
||
|
|
}
|
||
|
|
catch {
|
||
|
|
return null;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
isExpired(claims, skewSeconds = 0) {
|
||
|
|
return claims.exp * 1000 <= Date.now() + skewSeconds * 1000;
|
||
|
|
}
|
||
|
|
isJwtClaims(value) {
|
||
|
|
if (!value || typeof value !== 'object') {
|
||
|
|
return false;
|
||
|
|
}
|
||
|
|
const claims = value;
|
||
|
|
return typeof claims.sub === 'string' && typeof claims.role === 'string' && typeof claims.exp === 'number';
|
||
|
|
}
|
||
|
|
base64UrlDecode(input) {
|
||
|
|
const base64 = input.replace(/-/g, '+').replace(/_/g, '/').padEnd(input.length + ((4 - (input.length % 4)) % 4), '=');
|
||
|
|
return decodeURIComponent(escape(atob(base64)));
|
||
|
|
}
|
||
|
|
};
|
||
|
|
JwtService = __decorate([
|
||
|
|
Injectable({ providedIn: 'root' })
|
||
|
|
], JwtService);
|
||
|
|
export { JwtService };
|