-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(auth): add JWT
/refresh
endpoint
- Loading branch information
Showing
3 changed files
with
116 additions
and
0 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,63 @@ | ||
import jwt from "jsonwebtoken"; | ||
import { v4 } from "uuid"; | ||
import { z } from "zod"; | ||
|
||
const schema = z.object({ | ||
refreshToken: z.string(), | ||
}); | ||
|
||
export default defineEventHandler(async (event) => { | ||
const result = await readValidatedBody(event, (body) => | ||
schema.safeParse(body), | ||
); | ||
|
||
// eslint-disable-next-line @typescript-eslint/no-throw-literal | ||
if (!result.success) throw result.error.issues; | ||
|
||
const runtimeConfig = useRuntimeConfig(); | ||
|
||
const payload = jwt.verify( | ||
result.data.refreshToken, | ||
runtimeConfig.jwtRefreshSecret, | ||
) as jwt.JwtPayload; | ||
|
||
const savedRefreshToken = await findRefreshTokenById(payload.jti!); | ||
|
||
if (!savedRefreshToken || savedRefreshToken.revoked) | ||
throw createError({ | ||
statusCode: 401, | ||
statusMessage: "Unauthorized", | ||
}); | ||
|
||
const hashedToken = hashToken(result.data.refreshToken); | ||
if (hashedToken !== savedRefreshToken.hashedToken) | ||
throw createError({ | ||
statusCode: 401, | ||
statusMessage: "Unauthorized", | ||
}); | ||
|
||
const user = await db.user.findFirst({ | ||
where: { | ||
id: payload.userId, | ||
}, | ||
}); | ||
|
||
if (!user) | ||
throw createError({ | ||
statusCode: 401, | ||
statusMessage: "Unauthorized", | ||
}); | ||
|
||
await deleteRefreshToken(savedRefreshToken.id); | ||
const jti = v4(); | ||
const { accessToken, refreshToken: newRefreshToken } = generateTokens( | ||
user, | ||
jti, | ||
); | ||
await addRefreshToken(jti, newRefreshToken, user); | ||
|
||
return { | ||
accessToken, | ||
refreshToken: newRefreshToken, | ||
}; | ||
}); |
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