Skip to content

Commit

Permalink
refactor: code base improvements 3 (nextauthjs#1072)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
mnphpexpert committed Feb 1, 2021
1 parent 4ae4a37 commit 5add95a
Show file tree
Hide file tree
Showing 23 changed files with 568 additions and 623 deletions.
42 changes: 25 additions & 17 deletions src/lib/jwt.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ const DEFAULT_ENCRYPTION_ENABLED = false

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

const encode = async ({
async function encode ({
token = {},
maxAge = DEFAULT_MAX_AGE,
secret,
Expand All @@ -28,9 +28,9 @@ const encode = async ({
zip: 'DEF'
},
encryption = DEFAULT_ENCRYPTION_ENABLED
} = {}) => {
} = {}) {
// Signing Key
const _signingKey = (signingKey)
const _signingKey = signingKey
? jose.JWK.asKey(JSON.parse(signingKey))
: getDerivedSigningKey(secret)

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

if (encryption) {
// Encryption Key
const _encryptionKey = (encryptionKey)
const _encryptionKey = encryptionKey
? jose.JWK.asKey(JSON.parse(encryptionKey))
: getDerivedEncryptionKey(secret)

// Encrypt token
return jose.JWE.encrypt(signedToken, _encryptionKey, encryptionOptions)
} else {
return signedToken
}
return signedToken
}

const decode = async ({
async function decode ({
secret,
token,
maxAge = DEFAULT_MAX_AGE,
Expand All @@ -66,14 +65,14 @@ const decode = async ({
algorithms: [DEFAULT_ENCRYPTION_ALGORITHM]
},
encryption = DEFAULT_ENCRYPTION_ENABLED
} = {}) => {
} = {}) {
if (!token) return null

let tokenToVerify = token

if (encryption) {
// Encryption Key
const _encryptionKey = (decryptionKey)
const _encryptionKey = decryptionKey
? jose.JWK.asKey(JSON.parse(decryptionKey))
: getDerivedEncryptionKey(secret)

Expand All @@ -83,23 +82,32 @@ const decode = async ({
}

// Signing Key
const _signingKey = (verificationKey)
const _signingKey = verificationKey
? jose.JWK.asKey(JSON.parse(verificationKey))
: getDerivedSigningKey(secret)

// Verify token
return jose.JWT.verify(tokenToVerify, _signingKey, verificationOptions)
}

const getToken = async (args) => {
/**
* Server-side method to retrieve the JWT from `req`.
* @param {{
* req: NextApiRequest
* secureCookie?: boolean
* cookieName?: string
* raw?: boolean
* }} params
*/
async function getToken (params) {
const {
req,
// Use secure prefix for cookie name, unless URL is NEXTAUTH_URL is http://
// or not set (e.g. development or test instance) case use unprefixed name
secureCookie = !(!process.env.NEXTAUTH_URL || process.env.NEXTAUTH_URL.startsWith('http://')),
cookieName = (secureCookie) ? '__Secure-next-auth.session-token' : 'next-auth.session-token',
raw = false
} = args
} = params
if (!req) throw new Error('Must pass `req` to JWT getToken()')

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

try {
return await decode({ token, ...args })
} catch (error) {
return decode({ token, ...params })
} catch {
return null
}
}
Expand All @@ -128,7 +136,7 @@ const getToken = async (args) => {
let DERIVED_SIGNING_KEY_WARNING = false
let DERIVED_ENCRYPTION_KEY_WARNING = false

const getDerivedSigningKey = (secret) => {
function getDerivedSigningKey (secret) {
if (!DERIVED_SIGNING_KEY_WARNING) {
logger.warn('JWT_AUTO_GENERATED_SIGNING_KEY')
DERIVED_SIGNING_KEY_WARNING = true
Expand All @@ -139,7 +147,7 @@ const getDerivedSigningKey = (secret) => {
return key
}

const getDerivedEncryptionKey = (secret) => {
function getDerivedEncryptionKey (secret) {
if (!DERIVED_ENCRYPTION_KEY_WARNING) {
logger.warn('JWT_AUTO_GENERATED_ENCRYPTION_KEY')
DERIVED_ENCRYPTION_KEY_WARNING = true
Expand Down
35 changes: 14 additions & 21 deletions src/lib/logger.js
Original file line number Diff line number Diff line change
@@ -1,31 +1,24 @@
const logger = {
error: (errorCode, ...text) => {
if (!console) { return }
if (text && text.length <= 1) { text = text[0] || '' }
error (code, ...text) {
console.error(
`[next-auth][error][${errorCode.toLowerCase()}]`,
text,
`\nhttps://next-auth.js.org/errors#${errorCode.toLowerCase()}`
`[next-auth][error][${code.toLowerCase()}]`,
JSON.stringify(text),
`\nhttps://next-auth.js.org/errors#${code.toLowerCase()}`
)
},
warn: (warnCode, ...text) => {
if (!console) { return }
if (text && text.length <= 1) { text = text[0] || '' }
warn (code, ...text) {
console.warn(
`[next-auth][warn][${warnCode.toLowerCase()}]`,
text,
`\nhttps://next-auth.js.org/warnings#${warnCode.toLowerCase()}`
`[next-auth][warn][${code.toLowerCase()}]`,
JSON.stringify(text),
`\nhttps://next-auth.js.org/warnings#${code.toLowerCase()}`
)
},
debug: (debugCode, ...text) => {
if (!console) { return }
if (text && text.length <= 1) { text = text[0] || '' }
if (process && process.env && process.env._NEXTAUTH_DEBUG) {
console.log(
`[next-auth][debug][${debugCode.toLowerCase()}]`,
text
)
}
debug (code, ...text) {
if (!process?.env?._NEXTAUTH_DEBUG) return
console.log(
`[next-auth][debug][${code.toLowerCase()}]`,
JSON.stringify(text)
)
}
}

Expand Down
Loading

0 comments on commit 5add95a

Please sign in to comment.