-
Notifications
You must be signed in to change notification settings - Fork 24
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
86d6ca8
commit 977dd98
Showing
4 changed files
with
19 additions
and
27 deletions.
There are no files selected for viewing
This file contains 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
This file contains 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
This file contains 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
This file contains 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 |
---|---|---|
@@ -1,37 +1,28 @@ | ||
import jwt from 'jsonwebtoken'; | ||
|
||
interface TokenPayload { | ||
export interface TokenPayload { | ||
userId: string; | ||
} | ||
|
||
export class JWTHelper { | ||
private secretKey: string; | ||
|
||
constructor(secretKey: string) { | ||
this.secretKey = secretKey; | ||
} | ||
constructor(private readonly secretKey: string) {} | ||
|
||
createToken(token: TokenPayload, expiresIn: string = '1h'): string { | ||
return jwt.sign(token, this.secretKey, { expiresIn }); | ||
} | ||
|
||
parseToken(token: string): null | TokenPayload { | ||
parseToken(token: string): Error | TokenPayload { | ||
try { | ||
const payload = jwt.verify(token, this.secretKey) as TokenPayload; | ||
return payload; | ||
} catch { | ||
return null; | ||
return new Error('Invalid token'); | ||
} | ||
} | ||
|
||
refreshToken(token: string): Error | string { | ||
try { | ||
const payload = this.parseToken(token); | ||
if (!payload) return 'invalid token'; | ||
return this.createToken(payload); | ||
} catch { | ||
const message = new Error('error creating token'); | ||
return message; | ||
} | ||
refreshToken(token: string): string { | ||
const payload = this.parseToken(token); | ||
if (payload instanceof Error) return 'invalid token'; | ||
return jwt.sign(payload, this.secretKey); | ||
} | ||
} |