Skip to content

Commit 44ffd55

Browse files
refactor: code base improvements 3 (#1072)
* refactor: extend res.{end,send,json}, redirect * refactor: chain res methods, remove unnecessary ones * refactor: simplify oauth callback signature * refactor: code simplifications * refactor: re-export everything from routes in one * refactor: split up main index.js to multiple files * refactor: simplify passing of provider(s) around * refactor: extend req with callbackUrl inline * refactor: simplify page rendering * refactor: move error page redirects to main file, simplify renderer * refactor: inline req.options definition * refactor: simplify error fallbacks * refactor: remove else branches and unnecessary try..catch * refactor: add docs, and simplify jwt functions * refactor: prefer errors object over switch..case in signin page * feat: log all params sent to logger instead of only first * refactor: fewer lines input validation * refactor: remove even more unnecessary else branches
1 parent fb8ec8a commit 44ffd55

23 files changed

+568
-623
lines changed

src/lib/jwt.js

Lines changed: 25 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ const DEFAULT_ENCRYPTION_ENABLED = false
1313

1414
const DEFAULT_MAX_AGE = 30 * 24 * 60 * 60 // 30 days
1515

16-
const encode = async ({
16+
async function encode ({
1717
token = {},
1818
maxAge = DEFAULT_MAX_AGE,
1919
secret,
@@ -28,9 +28,9 @@ const encode = async ({
2828
zip: 'DEF'
2929
},
3030
encryption = DEFAULT_ENCRYPTION_ENABLED
31-
} = {}) => {
31+
} = {}) {
3232
// Signing Key
33-
const _signingKey = (signingKey)
33+
const _signingKey = signingKey
3434
? jose.JWK.asKey(JSON.parse(signingKey))
3535
: getDerivedSigningKey(secret)
3636

@@ -39,18 +39,17 @@ const encode = async ({
3939

4040
if (encryption) {
4141
// Encryption Key
42-
const _encryptionKey = (encryptionKey)
42+
const _encryptionKey = encryptionKey
4343
? jose.JWK.asKey(JSON.parse(encryptionKey))
4444
: getDerivedEncryptionKey(secret)
4545

4646
// Encrypt token
4747
return jose.JWE.encrypt(signedToken, _encryptionKey, encryptionOptions)
48-
} else {
49-
return signedToken
5048
}
49+
return signedToken
5150
}
5251

53-
const decode = async ({
52+
async function decode ({
5453
secret,
5554
token,
5655
maxAge = DEFAULT_MAX_AGE,
@@ -66,14 +65,14 @@ const decode = async ({
6665
algorithms: [DEFAULT_ENCRYPTION_ALGORITHM]
6766
},
6867
encryption = DEFAULT_ENCRYPTION_ENABLED
69-
} = {}) => {
68+
} = {}) {
7069
if (!token) return null
7170

7271
let tokenToVerify = token
7372

7473
if (encryption) {
7574
// Encryption Key
76-
const _encryptionKey = (decryptionKey)
75+
const _encryptionKey = decryptionKey
7776
? jose.JWK.asKey(JSON.parse(decryptionKey))
7877
: getDerivedEncryptionKey(secret)
7978

@@ -83,23 +82,32 @@ const decode = async ({
8382
}
8483

8584
// Signing Key
86-
const _signingKey = (verificationKey)
85+
const _signingKey = verificationKey
8786
? jose.JWK.asKey(JSON.parse(verificationKey))
8887
: getDerivedSigningKey(secret)
8988

9089
// Verify token
9190
return jose.JWT.verify(tokenToVerify, _signingKey, verificationOptions)
9291
}
9392

94-
const getToken = async (args) => {
93+
/**
94+
* Server-side method to retrieve the JWT from `req`.
95+
* @param {{
96+
* req: NextApiRequest
97+
* secureCookie?: boolean
98+
* cookieName?: string
99+
* raw?: boolean
100+
* }} params
101+
*/
102+
async function getToken (params) {
95103
const {
96104
req,
97105
// Use secure prefix for cookie name, unless URL is NEXTAUTH_URL is http://
98106
// or not set (e.g. development or test instance) case use unprefixed name
99107
secureCookie = !(!process.env.NEXTAUTH_URL || process.env.NEXTAUTH_URL.startsWith('http://')),
100108
cookieName = (secureCookie) ? '__Secure-next-auth.session-token' : 'next-auth.session-token',
101109
raw = false
102-
} = args
110+
} = params
103111
if (!req) throw new Error('Must pass `req` to JWT getToken()')
104112

105113
// Try to get token from cookie
@@ -108,7 +116,7 @@ const getToken = async (args) => {
108116
// If cookie not found in cookie look for bearer token in authorization header.
109117
// This allows clients that pass through tokens in headers rather than as
110118
// cookies to use this helper function.
111-
if (!token && req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
119+
if (!token && req.headers.authorization?.split(' ')[0] === 'Bearer') {
112120
const urlEncodedToken = req.headers.authorization.split(' ')[1]
113121
token = decodeURIComponent(urlEncodedToken)
114122
}
@@ -118,8 +126,8 @@ const getToken = async (args) => {
118126
}
119127

120128
try {
121-
return await decode({ token, ...args })
122-
} catch (error) {
129+
return decode({ token, ...params })
130+
} catch {
123131
return null
124132
}
125133
}
@@ -128,7 +136,7 @@ const getToken = async (args) => {
128136
let DERIVED_SIGNING_KEY_WARNING = false
129137
let DERIVED_ENCRYPTION_KEY_WARNING = false
130138

131-
const getDerivedSigningKey = (secret) => {
139+
function getDerivedSigningKey (secret) {
132140
if (!DERIVED_SIGNING_KEY_WARNING) {
133141
logger.warn('JWT_AUTO_GENERATED_SIGNING_KEY')
134142
DERIVED_SIGNING_KEY_WARNING = true
@@ -139,7 +147,7 @@ const getDerivedSigningKey = (secret) => {
139147
return key
140148
}
141149

142-
const getDerivedEncryptionKey = (secret) => {
150+
function getDerivedEncryptionKey (secret) {
143151
if (!DERIVED_ENCRYPTION_KEY_WARNING) {
144152
logger.warn('JWT_AUTO_GENERATED_ENCRYPTION_KEY')
145153
DERIVED_ENCRYPTION_KEY_WARNING = true

src/lib/logger.js

Lines changed: 14 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,24 @@
11
const logger = {
2-
error: (errorCode, ...text) => {
3-
if (!console) { return }
4-
if (text && text.length <= 1) { text = text[0] || '' }
2+
error (code, ...text) {
53
console.error(
6-
`[next-auth][error][${errorCode.toLowerCase()}]`,
7-
text,
8-
`\nhttps://next-auth.js.org/errors#${errorCode.toLowerCase()}`
4+
`[next-auth][error][${code.toLowerCase()}]`,
5+
JSON.stringify(text),
6+
`\nhttps://next-auth.js.org/errors#${code.toLowerCase()}`
97
)
108
},
11-
warn: (warnCode, ...text) => {
12-
if (!console) { return }
13-
if (text && text.length <= 1) { text = text[0] || '' }
9+
warn (code, ...text) {
1410
console.warn(
15-
`[next-auth][warn][${warnCode.toLowerCase()}]`,
16-
text,
17-
`\nhttps://next-auth.js.org/warnings#${warnCode.toLowerCase()}`
11+
`[next-auth][warn][${code.toLowerCase()}]`,
12+
JSON.stringify(text),
13+
`\nhttps://next-auth.js.org/warnings#${code.toLowerCase()}`
1814
)
1915
},
20-
debug: (debugCode, ...text) => {
21-
if (!console) { return }
22-
if (text && text.length <= 1) { text = text[0] || '' }
23-
if (process && process.env && process.env._NEXTAUTH_DEBUG) {
24-
console.log(
25-
`[next-auth][debug][${debugCode.toLowerCase()}]`,
26-
text
27-
)
28-
}
16+
debug (code, ...text) {
17+
if (!process?.env?._NEXTAUTH_DEBUG) return
18+
console.log(
19+
`[next-auth][debug][${code.toLowerCase()}]`,
20+
JSON.stringify(text)
21+
)
2922
}
3023
}
3124

0 commit comments

Comments
 (0)