Skip to content

Commit 544f640

Browse files
committed
chore(blog): updated snippet
1 parent 311f819 commit 544f640

1 file changed

Lines changed: 16 additions & 16 deletions

File tree

apps/blog/src/assets/snippets/jwt-for-beginners.ts

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -3,38 +3,38 @@ import crypto from 'crypto'
33
import bcrypt from 'bcryptjs'
44
import { jwtVerify, SignJWT } from 'jose'
55

6-
// In production, use something like process.env.JWT_SECRET instead.
6+
// Use an environment variable or a vault in production
77
const DEMO_JWT_SECRET = 'super_secret_jwt_key_1234567890'
88

9-
export type Payload = {
9+
type Payload = {
1010
uid: string // User ID stored in JWT payload
1111
iat: number // Issued at timestamp (seconds since epoch)
1212
exp: number // Expiration timestamp (seconds since epoch)
1313
}
1414

1515
// Hash a plaintext password with bcrypt using salt rounds = 10
16-
export async function hash(password: string) {
16+
async function hash(password: string) {
1717
const salt = await bcrypt.genSalt(10)
1818
return await bcrypt.hash(password, salt)
1919
}
2020

2121
// Compare plaintext password with stored bcrypt hash
22-
export async function compare(password: string, hash: string) {
22+
async function compare(password: string, hash: string) {
2323
return await bcrypt.compare(password, hash)
2424
}
2525

2626
// Convert string secret into Uint8Array required by jose library
27-
export function getSecretKey(secret: string) {
27+
function getSecretKey(secret: string) {
2828
return new TextEncoder().encode(secret)
2929
}
3030

3131
// Generate a cryptographically secure random hex string of given byte size
32-
export function generateRandomString(size = 32) {
32+
function generateRandomString(size = 32) {
3333
return crypto.randomBytes(size).toString('hex')
3434
}
3535

3636
// Create a JWT signed with HS256 including uid, issued at, and expiration claims
37-
export async function sign(uid: string, key: string) {
37+
async function sign(uid: string, key: string) {
3838
const iat = Math.floor(Date.now() / 1000) // Current time in seconds
3939
const exp = iat + 60 * 15 // Token expires in 15 minutes
4040
return await new SignJWT({ uid }) // Payload with user ID
@@ -45,7 +45,7 @@ export async function sign(uid: string, key: string) {
4545
}
4646

4747
// Verify a JWT and return the payload if valid, otherwise null
48-
export async function verify(token: string, key: string) {
48+
async function verify(token: string, key: string) {
4949
try {
5050
const { payload } = await jwtVerify(token, getSecretKey(key))
5151
return payload as Payload
@@ -55,20 +55,20 @@ export async function verify(token: string, key: string) {
5555
}
5656

5757
async function main() {
58-
const password = 'Som3_Cra2y-Pa55w0rd^@)!'
59-
console.log('Password:', password)
58+
const password = 'user_password_1234567890'
59+
console.log('User Password:', password)
6060

6161
// Hash the password
6262
const hashedPassword = await hash(password)
6363
console.log('Hashed Password:', hashedPassword)
6464

6565
// Verify password matches the hash
6666
const isMatch = await compare(password, hashedPassword)
67-
console.log('Password Match:', isMatch) // true
67+
console.log('Passwords Match?', isMatch) // true
6868

6969
// Check wrong password against hash to demonstrate failed auth
7070
const isNotMatch = await compare('wrongpassword', hashedPassword)
71-
console.log('Password Match:', isNotMatch) // false
71+
console.log('Passwords Match?', isNotMatch) // false
7272

7373
const uid = crypto.randomUUID() // Generate a unique user ID
7474
console.log('User ID:', uid)
@@ -81,15 +81,15 @@ async function main() {
8181
console.log('JWT Token:', token)
8282

8383
// Create token signed with a random key (invalid for current secret)
84-
const otherToken = await sign(uid, generateRandomString(32))
84+
const invalidToken = await sign(uid, generateRandomString(32))
8585

8686
// Attempt to verify invalid token with correct secret (should fail)
87-
const invalidToken = await verify(otherToken, key)
88-
console.log('Invalid Payload:', invalidToken) // null
87+
const invalidPayload = await verify(invalidToken, key)
88+
console.log('Invalid Token:', invalidPayload) // null
8989

9090
// Verify JWT token and decode payload
9191
const decoded = await verify(token, key)
92-
console.log('Valid Payload:', decoded) // Should show uid, iat, exp
92+
console.log('Decoded Token:', decoded) // Should show uid, iat, exp
9393
}
9494

9595
main()

0 commit comments

Comments
 (0)