Skip to content

refactor: code base improvements 3 #1072

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 18 commits into from
Jan 10, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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