2019-10-01 16:04:43 +00:00
|
|
|
import * as plugins from './smartjwt.plugins';
|
|
|
|
|
2019-10-01 17:58:53 +00:00
|
|
|
export interface ISmartJWTJSONKeypair {
|
|
|
|
privatePem: string;
|
|
|
|
publicPem: string;
|
|
|
|
}
|
|
|
|
|
2019-10-01 16:04:43 +00:00
|
|
|
/**
|
2019-10-01 17:58:53 +00:00
|
|
|
* A class to create and validate JWTs and their keys
|
2019-10-01 16:04:43 +00:00
|
|
|
*/
|
|
|
|
export class SmartJwt {
|
|
|
|
public smartcryptoInstance = new plugins.smartcrypto.Smartcrypto();
|
|
|
|
public publicKey: plugins.smartcrypto.PublicKey;
|
|
|
|
public privateKey: plugins.smartcrypto.PrivateKey;
|
|
|
|
|
|
|
|
constructor() {};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* creates a JWT
|
|
|
|
*/
|
|
|
|
public async createJWT(payloadArg: any) {
|
2019-10-01 17:07:59 +00:00
|
|
|
return plugins.jsonwebtoken.sign(payloadArg, this.privateKey.toPemString(), {
|
|
|
|
algorithm: 'RS256'
|
|
|
|
});
|
2019-10-01 16:04:43 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* checks a JWT
|
|
|
|
*/
|
|
|
|
public async verifyJWTAndGetData(jwtArg: string) {
|
2019-10-01 17:07:59 +00:00
|
|
|
return plugins.jsonwebtoken.verify(jwtArg, this.publicKey.toPemString(), {
|
|
|
|
algorithms: ['RS256']
|
|
|
|
});
|
|
|
|
}
|
2019-10-01 16:04:43 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* sets a private key to create jwts with
|
|
|
|
*/
|
|
|
|
public async setPrivateKey(privateKey: plugins.smartcrypto.PrivateKey) {
|
|
|
|
this.privateKey = privateKey;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* sets a public key
|
|
|
|
*/
|
|
|
|
public async setPublicKey(publicKey: plugins.smartcrypto.PublicKey) {
|
|
|
|
this.publicKey = publicKey;
|
|
|
|
}
|
|
|
|
|
2019-10-01 17:58:53 +00:00
|
|
|
/**
|
|
|
|
* gets the currently set kaypair as json
|
|
|
|
*/
|
|
|
|
public getKeyPairAsJson(): ISmartJWTJSONKeypair {
|
|
|
|
return {
|
|
|
|
privatePem: this.privateKey.toPemString(),
|
|
|
|
publicPem: this.publicKey.toPemString()
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* sets the currently set keypair as json
|
|
|
|
*/
|
|
|
|
public setKeyPairAsJson(jsonKeyPair: ISmartJWTJSONKeypair) {
|
|
|
|
this.privateKey = plugins.smartcrypto.PrivateKey.fromPemString(jsonKeyPair.privatePem);
|
|
|
|
this.publicKey = plugins.smartcrypto.PublicKey.fromPemString(jsonKeyPair.publicPem);
|
|
|
|
}
|
|
|
|
|
2019-10-01 16:04:43 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* creates a new keypair
|
|
|
|
*/
|
|
|
|
public async createNewKeyPair() {
|
|
|
|
const keypair = await this.smartcryptoInstance.createKeyPair();
|
|
|
|
this.setPrivateKey(keypair.privateKey);
|
|
|
|
this.setPublicKey(keypair.publicKey);
|
|
|
|
}
|
|
|
|
}
|