Skip to content

Commit

Permalink
MOdif config
Browse files Browse the repository at this point in the history
  • Loading branch information
kuukuuuruyuk committed Oct 1, 2022
1 parent 2dbd43c commit 1fb190d
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 6 deletions.
45 changes: 39 additions & 6 deletions src/tokenize/token-manager.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,28 @@
const Jwt = require('@hapi/jwt');
const {InvariantError} = require('../exception/invariant-error');

/**
* Token manager
*/
class TokenManager {
/**
* Token manager
*
* @param {any} jwt Hapi jwt
* @param {any} config Configurasi token key
*/
constructor(jwt, config) {
this._config = config.token;
this._jwt = jwt;
}
/**
* Token manager service
*
* @param {any} payload Hapi payload
* @return {string} Access token
*/
generateAccessToken(payload) {
return Jwt.token.generate(payload, process.env.ACCESS_TOKEN_KEY);
const ACCESS_TOKEN_KEY = this._config.accessToken;
return this._jwt.token.generate(payload, ACCESS_TOKEN_KEY);
}

/**
Expand All @@ -22,7 +32,28 @@ class TokenManager {
* @return {string} Refresh token
*/
generateRefreshToken(payload) {
return Jwt.token.generate(payload, process.env.REFRESH_TOKEN_KEY);
const REFRESH_TOKEN_KEY = this._config.refreshToken;
return this._jwt.token.generate(payload, REFRESH_TOKEN_KEY);
}

/**
* Verifikasi access token
*
* @param {string} accessToken Access token
* @return {any} Hapi jwt payload
*/
verifyAccessToken(accessToken) {
try {
const ACCESS_TOKEN_KEY = this._config.accessToken;
const artifacts = this._jwt.token.decode(accessToken);

this._jwt.token.verifySignature(artifacts, ACCESS_TOKEN_KEY);

const payload = artifacts.decoded.payload;
return payload;
} catch (error) {
throw new InvariantError('Access token tidak valid');
}
}

/**
Expand All @@ -33,11 +64,13 @@ class TokenManager {
*/
verifyRefreshToken(refreshToken) {
try {
const artifacts = Jwt.token.decode(refreshToken);
const REFRESH_TOKEN_KEY = this._config.refreshToken;
const artifacts = this._jwt.token.decode(refreshToken);

Jwt.token.verifySignature(artifacts, process.env.REFRESH_TOKEN_KEY);
this._jwt.token.verifySignature(artifacts, REFRESH_TOKEN_KEY);

return artifacts.decoded?.payload;
const payload = artifacts.decoded.payload;
return payload;
} catch (error) {
throw new InvariantError('Refresh token tidak valid');
}
Expand Down
1 change: 1 addition & 0 deletions src/utils/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ const config = {
},
token: {
accessToken: process.env.ACCESS_TOKEN_KEY,
refreshToken: process.env.REFRESH_TOKEN_KEY,
tokenAge: process.env.ACCESS_TOKEN_AGE,
},
};
Expand Down

0 comments on commit 1fb190d

Please sign in to comment.