-
-
Notifications
You must be signed in to change notification settings - Fork 141
WIP : @accounts/token-manager Adds a package to manage jwt's #179
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
980211d
@accounts/token-manager : create empty package
Aetherall 73e2e1d
@accounts/token-manager : added default configuration and configurati…
Aetherall 6735d65
@accounts/token-manager : class initialisation and configuration vali…
Aetherall 910ebdf
@accounts/token-manager : added class methods
Aetherall 435a24f
@accounts/token-manager : added tests
Aetherall File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
import TokenManager from '../src'; | ||
|
||
describe('TokenManager entry', () => { | ||
it('should have default export TokenManager', () => { | ||
expect(typeof TokenManager).toBe('function'); | ||
}); | ||
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,84 @@ | ||
import TokenManager from '../src'; | ||
|
||
const TM = new TokenManager({ | ||
secret: 'test', | ||
emailTokenExpiration: 60_000, | ||
}); | ||
|
||
describe('TokenManager', () => { | ||
describe('validateConfiguration', () => { | ||
it('should throw if no configuration provided', () => { | ||
expect(() => new TokenManager()).toThrow(); | ||
}); | ||
|
||
it('should throw if configuration does not provide secret property', () => { | ||
expect(() => new TokenManager({})).toThrow(); | ||
}); | ||
}); | ||
|
||
describe('generateRandomToken', () => { | ||
it('should return a 86 char (43 bytes to hex) long random string when no parameters provided', () => { | ||
expect(typeof TM.generateRandomToken()).toBe('string'); | ||
expect(TM.generateRandomToken().length).toBe(86); | ||
}); | ||
|
||
it('should return random string with the first parameter as length', () => { | ||
expect(typeof TM.generateRandomToken(10)).toBe('string'); | ||
expect(TM.generateRandomToken(10).length).toBe(20); | ||
}); | ||
}); | ||
|
||
describe('generateAccessToken', () => { | ||
it('should throw when no parameters provided', () => { | ||
expect(() => { | ||
TM.generateAccessToken(); | ||
}).toThrow(); | ||
}); | ||
|
||
it('should return a string when first parameter provided', () => { | ||
expect(typeof TM.generateAccessToken({ sessionId: 'test' })).toBe('string'); | ||
}); | ||
}); | ||
|
||
describe('generateRefreshToken', () => { | ||
it('should return a string', () => { | ||
expect(typeof TM.generateRefreshToken()).toBe('string'); | ||
expect(typeof TM.generateRefreshToken({ sessionId: 'test' })).toBe('string'); | ||
}); | ||
}); | ||
|
||
describe('isEmailTokenExpired', () => { | ||
it('should return true if the token provided is expired', () => { | ||
const token = ''; | ||
const tokenRecord = { when: 0 }; | ||
expect(TM.isEmailTokenExpired(token, tokenRecord)).toBe(true); | ||
}); | ||
|
||
it('should return false if the token provided is not expired', () => { | ||
const token = ''; | ||
const tokenRecord = { when: Date.now() + 100_000 }; | ||
expect(TM.isEmailTokenExpired(token, tokenRecord)).toBe(false); | ||
}); | ||
|
||
}); | ||
|
||
describe('decodeToken', () => { | ||
const TMdecode = new TokenManager({ | ||
secret: 'test', | ||
access: { | ||
expiresIn: '0s' | ||
} | ||
}) | ||
|
||
it('should not ignore expiration by default', () => { | ||
const tokenData = { user: 'test' }; | ||
const token = TMdecode.generateAccessToken(tokenData); | ||
expect(()=>{TMdecode.decodeToken(token)}).toThrow(); | ||
}); | ||
it('should return the decoded token anyway when ignoreExpiration is true', () => { | ||
const tokenData = { user: 'test' }; | ||
const token = TMdecode.generateAccessToken(tokenData); | ||
expect(TMdecode.decodeToken(token, true).user).toBe('test'); | ||
}); | ||
}); | ||
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
{ | ||
"name": "@accounts/token-manager", | ||
"version": "0.1.0-beta.3", | ||
"license": "MIT", | ||
"main": "lib/index.js", | ||
"typings": "lib/index.d.ts", | ||
"scripts": { | ||
"start": "tsc --watch", | ||
"compile": "tsc", | ||
"testonly": "jest", | ||
"test:watch": "jest --watch", | ||
"coverage": "jest --coverage", | ||
"prepublishOnly": "yarn compile" | ||
}, | ||
"jest": { | ||
"transform": { | ||
".(ts|tsx)": "<rootDir>/../../node_modules/ts-jest/preprocessor.js" | ||
}, | ||
"testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx)$", | ||
"moduleFileExtensions": [ | ||
"ts", | ||
"js" | ||
], | ||
"mapCoverage": true | ||
}, | ||
"dependencies": { | ||
"bcryptjs": "^2.4.0", | ||
"jsonwebtoken": "^8.0.0", | ||
"jwt-decode": "^2.1.0" | ||
}, | ||
"devDependencies": { | ||
"@accounts/common": "^0.1.0-beta.3", | ||
"@types/jsonwebtoken": "7.2.5", | ||
"@types/jwt-decode": "2.2.1", | ||
"rimraf": "2.6.2" | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
export { default } from './token-manager'; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,68 @@ | ||
import { TokenRecord } from '@accounts/common'; | ||
|
||
import { randomBytes } from 'crypto'; | ||
import * as jwt from 'jsonwebtoken'; | ||
import { error } from 'util'; | ||
|
||
import { Configuration } from './types/configuration'; | ||
import { TokenGenerationConfiguration } from './types/token-generation-configuration'; | ||
|
||
const defaultTokenConfig: TokenGenerationConfiguration = { | ||
algorithm: 'HS256', | ||
}; | ||
|
||
const defaultAccessTokenConfig: TokenGenerationConfiguration = { | ||
expiresIn: '90m', | ||
}; | ||
|
||
const defaultRefreshTokenConfig: TokenGenerationConfiguration = { | ||
expiresIn: '7d', | ||
}; | ||
|
||
export default class TokenManager { | ||
|
||
private secret: string; | ||
|
||
private emailTokenExpiration: number; | ||
|
||
private accessTokenConfig: TokenGenerationConfiguration; | ||
|
||
private refreshTokenConfig: TokenGenerationConfiguration; | ||
|
||
constructor(config: Configuration) { | ||
this.validateConfiguration(config); | ||
this.secret = config.secret; | ||
this.emailTokenExpiration = config.emailTokenExpiration || 1000 * 60; | ||
this.accessTokenConfig = { ...defaultTokenConfig, ...defaultAccessTokenConfig, ...config.access }; | ||
this.refreshTokenConfig = { ...defaultTokenConfig, ...defaultRefreshTokenConfig, ...config.refresh }; | ||
} | ||
|
||
public generateRandomToken(length: number | undefined): string { | ||
return randomBytes(length || 43).toString('hex'); | ||
} | ||
|
||
public generateAccessToken(data): string { | ||
return jwt.sign(data, this.secret, this.accessTokenConfig); | ||
} | ||
|
||
public generateRefreshToken(data = {}): string { | ||
return jwt.sign(data, this.secret, this.refreshTokenConfig); | ||
} | ||
|
||
public isEmailTokenExpired(token: string, tokenRecord?: TokenRecord): boolean { | ||
return !tokenRecord || Number(tokenRecord.when) + this.emailTokenExpiration < Date.now(); | ||
} | ||
|
||
public decodeToken(token: string, ignoreExpiration: boolean = false): string | object { | ||
return jwt.verify(token, this.secret, { ignoreExpiration }); | ||
} | ||
|
||
private validateConfiguration(config: Configuration): void { | ||
if (!config) { | ||
throw new Error('[ Accounts - TokenManager ] configuration : A configuration object is needed'); | ||
} | ||
if (typeof config.secret !== 'string') { | ||
throw new Error('[ Accounts - TokenManager ] configuration : A string secret property is needed'); | ||
} | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
import { TokenGenerationConfiguration } from './token-generation-configuration'; | ||
|
||
export interface Configuration { | ||
|
||
secret: string; | ||
|
||
emailTokenExpiration?: number; | ||
|
||
access?: TokenGenerationConfiguration; | ||
|
||
refresh?: TokenGenerationConfiguration; | ||
|
||
} |
25 changes: 25 additions & 0 deletions
25
packages/token-manager/src/types/token-generation-configuration.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
export interface TokenGenerationConfiguration { | ||
|
||
algorithm?: string; | ||
|
||
expiresIn?: string; | ||
|
||
// TODO : explore jwt configuration | ||
/* | ||
|
||
notBefore?: string; | ||
|
||
audience?: string | string[] | RegExp | RegExp[]; | ||
|
||
To complete | ||
|
||
jwtid: | ||
|
||
subject:null, | ||
|
||
noTimestamp:null, | ||
|
||
header:null, | ||
|
||
keyid:null,*/ | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
{ | ||
"extends": "../../tsconfig", | ||
"compilerOptions": { | ||
"rootDir": "./src", | ||
"outDir": "./lib" | ||
}, | ||
"exclude": [ | ||
"node_modules", | ||
"__tests__", | ||
"lib" | ||
] | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
what are your thoughts on just defining and exporting
Configuration
interface within this file and eliminating./types
entirely?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I want to enforce a pattern which has to be respected by all the packages of the suite, so if a potential contributor need to add a package, he will apply the pattern to his package naturally
I agree It is not needed everywhere but seeing that we at accounts-JS do apply it everywhere, the potential contributor will tend to adopt the pattern
Also, I like when the only different thing between two things is what actually make them different