Skip to content

Commit

Permalink
refactor: auth redis session
Browse files Browse the repository at this point in the history
  • Loading branch information
rharkor committed Feb 17, 2024
1 parent 40713f3 commit 11512fc
Showing 1 changed file with 26 additions and 24 deletions.
50 changes: 26 additions & 24 deletions packages/app/src/lib/auth/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -190,37 +190,39 @@ export const nextAuthOptions: NextAuthOptions = {
return {} as Session
}
if (token.uuid) {
const res = await new Promise<Session | undefined>(async () => {
const getRedisSession = async () => {
const key = `session:${dbUser.id}:${token.uuid}`
const loginSession = await redis.get(key)
if (!loginSession) {
logger.debug("Session not found", token.uuid)
return {} as Session
} else {
//? Only if lastUsedAt is older than 1 minute (avoid spamming the redis server)
const data = JSON.parse(loginSession) as z.infer<ReturnType<typeof sessionsSchema>>
if (data.lastUsedAt) {
const lastUsedAt = new Date(data.lastUsedAt)
const now = new Date()
const diff = now.getTime() - lastUsedAt.getTime()
if (diff > 1000 * 60) {
return
}
}

//? Only if lastUsedAt is older than 1 minute (avoid spamming the redis server)
const data = JSON.parse(loginSession) as z.infer<ReturnType<typeof sessionsSchema>>
if (data.lastUsedAt) {
const lastUsedAt = new Date(data.lastUsedAt)
const now = new Date()
const diff = now.getTime() - lastUsedAt.getTime()
if (diff > 1000 * 60) {
return
}
//? Update session lastUsed
const remainingTtl = await redis.ttl(key)
//! Do not await to make the requests faster
redis.setex(
key,
remainingTtl,
JSON.stringify({
...(JSON.parse(loginSession) as object),
lastUsedAt: new Date(),
})
)
return
}
})
//? Update session lastUsed
const remainingTtl = await redis.ttl(key)
//! Do not await to make the requests faster
redis.setex(
key,
remainingTtl,
JSON.stringify({
...(JSON.parse(loginSession) as object),
lastUsedAt: new Date(),
})
)
return
}
const res = await getRedisSession()

if (res !== undefined) {
return res
}
Expand Down

0 comments on commit 11512fc

Please sign in to comment.