All files / src/Authentication Token.ts

100% Statements 20/20
100% Branches 3/3
100% Functions 12/12
100% Lines 19/19
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110                1x     418x 418x   360x                         214x 214x 214x             5x             1x             200x             13x             198x 198x             1x               72x                     75x 71x                     179x     250x      
/**
 * @module Authentication
 */ /** */
import { ITokenPayload } from './';
 
/**
 * This class represents a sense NET JWT Token instance.
 */
export class Token {
 
    private get _tokenPayload(): ITokenPayload {
        try {
            return JSON.parse(Buffer.from(this._payloadEncoded, 'base64').toString()) as ITokenPayload;
        } catch (err) {
            return {
                aud: '',
                exp: 0,
                iat: 0,
                iss: '',
                name: '',
                nbf: 0,
                sub: '',
            };
        }
    }
 
    private fromEpoch(epoch: number): Date {
        const d = new Date(0);
        d.setUTCSeconds(epoch);
        return d;
    }
 
    /**
     * The Username from the current Token payload
     */
    public get Username(): string {
        return this._tokenPayload.name;
    }
 
    /**
     * The current Token full Payload
     */
    public GetPayload(): ITokenPayload {
        return this._tokenPayload;
    }
 
    /**
     * The Date when the token will expire
     */
    public get ExpirationTime(): Date {
        return this.fromEpoch(this._tokenPayload.exp);
    }
 
    /**
     * The token will be valid only after this date
     */
    public get NotBefore(): Date {
        return this.fromEpoch(this._tokenPayload.nbf);
    }
 
    /**
     * Indicates if the Token is valid based on it's ExpirationTime and NotBefore values.
     */
    public IsValid(): boolean {
        const now = new Date();
        return this._tokenPayload && this.ExpirationTime > now && this.NotBefore < now;
    }
 
    /**
     * The date when the Token was issued
     */
    public get IssuedDate() {
        return this.fromEpoch(this._tokenPayload.iat);
    }
 
    /**
     * Returns the Token in string format (in a base64 encoded, dot separated header and payload)
     */
    // tslint:disable-next-line:naming-convention
    public toString() {
        return `${this._headerEncoded}.${this._payloadEncoded}`;
    }
 
    /**
     * Factory method to create a token from a sense NET specific base64 encoded header and payload string, e.g.:
     * ```
     * const myToken = Token.FromHeadAndPayload("e30=.eyJhdWQiOiIiLCJleHAiOjE0OTQ1NzkwOTUuMTIsImlhdCI6MCwiaXNzIjoiIiwibmFtZSI6IiIsIm5iZiI6MSwic3ViIjoiIn0=");
     * ```
     * @constructs Token
     */
    public static FromHeadAndPayload(headAndPayload: string): Token {
        const [head, payload] = headAndPayload.split('.');
        return new Token(head, payload);
    }
 
    /**
     * Factory method for creating empty (invalid) tokens
     * ```
     * const invalidToken = Token.CreateEmpty();
     * ```
     * @constructs Token
     */
    public static CreateEmpty(): Token {
        return new Token('', '');
    }
 
    private constructor(private readonly _headerEncoded: string, private readonly _payloadEncoded: string) {
    }
}