Skip to content

Commit 3b9dba8

Browse files
chore: adds session helper exports (#13367)
Creates/exports `addSessionToUser` helper and also exports the `removeExpiredSessions` helper.
1 parent 1d70d4d commit 3b9dba8

File tree

5 files changed

+78
-41
lines changed

5 files changed

+78
-41
lines changed

packages/payload/src/auth/operations/login.ts

Lines changed: 9 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
import { v4 as uuid } from 'uuid'
2-
31
import type {
42
AuthOperationsFromCollectionSlug,
53
Collection,
@@ -24,7 +22,7 @@ import { getFieldsToSign } from '../getFieldsToSign.js'
2422
import { getLoginOptions } from '../getLoginOptions.js'
2523
import { isUserLocked } from '../isUserLocked.js'
2624
import { jwtSign } from '../jwt.js'
27-
import { removeExpiredSessions } from '../removeExpiredSessions.js'
25+
import { addSessionToUser } from '../sessions.js'
2826
import { authenticateLocalStrategy } from '../strategies/local/authenticate.js'
2927
import { incrementLoginAttempts } from '../strategies/local/incrementLoginAttempts.js'
3028
import { resetLoginAttempts } from '../strategies/local/resetLoginAttempts.js'
@@ -285,34 +283,15 @@ export const loginOperation = async <TSlug extends CollectionSlug>(
285283
user,
286284
}
287285

288-
if (collectionConfig.auth.useSessions) {
289-
// Add session to user
290-
const newSessionID = uuid()
291-
const now = new Date()
292-
const tokenExpInMs = collectionConfig.auth.tokenExpiration * 1000
293-
const expiresAt = new Date(now.getTime() + tokenExpInMs)
294-
295-
const session = { id: newSessionID, createdAt: now, expiresAt }
296-
297-
if (!user.sessions?.length) {
298-
user.sessions = [session]
299-
} else {
300-
user.sessions = removeExpiredSessions(user.sessions)
301-
user.sessions.push(session)
302-
}
303-
304-
await payload.db.updateOne({
305-
id: user.id,
306-
collection: collectionConfig.slug,
307-
data: user,
308-
req,
309-
returning: false,
310-
})
311-
312-
user.collection = collectionConfig.slug
313-
user._strategy = 'local-jwt'
286+
const { sid } = await addSessionToUser({
287+
collectionConfig,
288+
payload,
289+
req,
290+
user,
291+
})
314292

315-
fieldsToSignArgs.sid = newSessionID
293+
if (sid) {
294+
fieldsToSignArgs.sid = sid
316295
}
317296

318297
const fieldsToSign = getFieldsToSign(fieldsToSignArgs)

packages/payload/src/auth/operations/refresh.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import { initTransaction } from '../../utilities/initTransaction.js'
1010
import { killTransaction } from '../../utilities/killTransaction.js'
1111
import { getFieldsToSign } from '../getFieldsToSign.js'
1212
import { jwtSign } from '../jwt.js'
13-
import { removeExpiredSessions } from '../removeExpiredSessions.js'
13+
import { removeExpiredSessions } from '../sessions.js'
1414

1515
export type Result = {
1616
exp: number

packages/payload/src/auth/removeExpiredSessions.ts

Lines changed: 0 additions & 10 deletions
This file was deleted.

packages/payload/src/auth/sessions.ts

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
import { v4 as uuid } from 'uuid'
2+
3+
import type { SanitizedCollectionConfig } from '../collections/config/types.js'
4+
import type { TypedUser } from '../index.js'
5+
import type { Payload, PayloadRequest } from '../types/index.js'
6+
import type { UserSession } from './types.js'
7+
8+
/**
9+
* Removes expired sessions from an array of sessions
10+
*/
11+
export const removeExpiredSessions = (sessions: UserSession[]) => {
12+
const now = new Date()
13+
14+
return sessions.filter(({ expiresAt }) => {
15+
const expiry = expiresAt instanceof Date ? expiresAt : new Date(expiresAt)
16+
return expiry > now
17+
})
18+
}
19+
20+
/**
21+
* Adds a session to the user and removes expired sessions
22+
* @returns The session ID (sid) if sessions are used
23+
*/
24+
export const addSessionToUser = async ({
25+
collectionConfig,
26+
payload,
27+
req,
28+
user,
29+
}: {
30+
collectionConfig: SanitizedCollectionConfig
31+
payload: Payload
32+
req: PayloadRequest
33+
user: TypedUser
34+
}): Promise<{ sid?: string }> => {
35+
let sid: string | undefined
36+
if (collectionConfig.auth.useSessions) {
37+
// Add session to user
38+
sid = uuid()
39+
const now = new Date()
40+
const tokenExpInMs = collectionConfig.auth.tokenExpiration * 1000
41+
const expiresAt = new Date(now.getTime() + tokenExpInMs)
42+
43+
const session = { id: sid, createdAt: now, expiresAt }
44+
45+
if (!user.sessions?.length) {
46+
user.sessions = [session]
47+
} else {
48+
user.sessions = removeExpiredSessions(user.sessions)
49+
user.sessions.push(session)
50+
}
51+
52+
await payload.db.updateOne({
53+
id: user.id,
54+
collection: collectionConfig.slug,
55+
data: user,
56+
req,
57+
returning: false,
58+
})
59+
60+
user.collection = collectionConfig.slug
61+
user._strategy = 'local-jwt'
62+
}
63+
64+
return {
65+
sid,
66+
}
67+
}

packages/payload/src/exports/shared.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ export {
66
parseCookies,
77
} from '../auth/cookies.js'
88
export { getLoginOptions } from '../auth/getLoginOptions.js'
9+
export { addSessionToUser, removeExpiredSessions } from '../auth/sessions.js'
910
export { getFromImportMap } from '../bin/generateImportMap/utilities/getFromImportMap.js'
1011
export { parsePayloadComponent } from '../bin/generateImportMap/utilities/parsePayloadComponent.js'
1112
export { defaults as collectionDefaults } from '../collections/config/defaults.js'

0 commit comments

Comments
 (0)