Skip to content

Commit

Permalink
- fix jwt verification
Browse files Browse the repository at this point in the history
  • Loading branch information
palkan committed Sep 22, 2023
1 parent 97b7dc1 commit 356411e
Showing 1 changed file with 17 additions and 14 deletions.
31 changes: 17 additions & 14 deletions jwt/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,31 +3,33 @@ import * as jose from "jose";
export type IdentifiersMap = Record<string, any>;

export interface IIdentificator<I extends IdentifiersMap = {}> {
verify: (token: string | undefined) => boolean;
verifyAndFetch(token: string | undefined): Promise<I | null>;
verify: (token: string) => Promise<true>;
verifyAndFetch(token: string): Promise<I | null>;
generateToken: (identifiers: I) => Promise<string>;
}

export const identificator = <I extends IdentifiersMap>(
secret: string,
exp: string | number,
exp: string | number
) => {
const secretEncoder = new TextEncoder().encode(secret);
const alg = "HS256";

return {
verify: (token: string | undefined) => {
if (token) return !!jose.jwtVerify(token, secretEncoder);
verify: async (token: string) => {
await jose.jwtVerify(token, secretEncoder, {
maxTokenAge: exp,
});

return true;
},
verifyAndFetch: async (token: string | undefined) => {
if (token) {
const { payload } = await jose.jwtVerify(token, secretEncoder, {
algorithms: [alg],
});

if (typeof payload.ext == "string") {
return JSON.parse(payload.ext) as I;
}
verifyAndFetch: async (token: string) => {
const { payload } = await jose.jwtVerify(token, secretEncoder, {
algorithms: [alg],
});

if (typeof payload.ext == "string") {
return JSON.parse(payload.ext) as I;
}

return null;
Expand All @@ -36,6 +38,7 @@ export const identificator = <I extends IdentifiersMap>(
const token = await new jose.SignJWT({ ext: JSON.stringify(identifiers) })
.setProtectedHeader({ alg })
.setExpirationTime(exp)
.setIssuedAt()
.sign(secretEncoder);

return token;
Expand Down

0 comments on commit 356411e

Please sign in to comment.