Skip to content

Commit

Permalink
Merge pull request #26 from aborn/nuxt_393
Browse files Browse the repository at this point in the history
feature: remove logger deps & upgrade nuxt to 3.9.3. fix issue:#25
  • Loading branch information
aborn authored Jan 30, 2024
2 parents e584d6b + 83cf1fe commit 816c239
Show file tree
Hide file tree
Showing 11 changed files with 3,307 additions and 1,786 deletions.
13 changes: 8 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "nuxt-openid-connect",
"version": "0.6.2",
"version": "0.7.0",
"description": "An nuxt 3 module with OpenID-Connect(OIDC) integration.",
"keywords": [
"nuxt",
Expand Down Expand Up @@ -30,23 +30,26 @@
"prepack": "nuxt-module-build",
"dev": "nuxi dev playground",
"dev:build": "nuxi build playground",
"dev:preview": "nuxi preview playground",
"dev:prepare": "nuxt-module-build --stub && nuxi prepare playground",
"release": "npm run lint && npm run test && npm run prepack && changelogen --release && npm publish && git push --follow-tags",
"lint": "eslint .",
"test": "vitest run",
"pub": "npm publish --access public"
},
"dependencies": {
"@nuxt/kit": "^3.2.2",
"@nuxt/kit": "^3.9.3",
"defu": "^6.0.0",
"openid-client": "^5.1.6",
"uuid": "^9.0.0"
},
"devDependencies": {
"@nuxt/module-builder": "latest",
"@nuxtjs/eslint-config-typescript": "latest",
"@types/node": "^18.14.2",
"@types/node": "^20.11.10",
"@types/uuid": "^8.3.4",
"eslint": "latest",
"nuxt": "^3.2.2"
"nuxt": "^3.9.3",
"typescript": "^5.3.3"
},
"bugs": {
"url": "https://github.com/aborn/nuxt-openid-connect/issues"
Expand Down
4 changes: 2 additions & 2 deletions playground/nuxt.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,10 @@ export default defineNuxtConfig({
openidConnect: {
addPlugin: true,
op: {
issuer: 'http://192.168.24.103:8080/realms/test', // change to your OP addrress
issuer: 'http://localhost:8080/realms/test', // change to your OP addrress
clientId: 'testClient',
clientSecret: 'cnuLA78epx8s8vMbRxcaiXbzlS4u8bSA',
callbackUrl: 'http://192.168.24.103:3000/oidc/callback', // optional
callbackUrl: 'http://localhost:3000/oidc/callback', // optional
scope: [
'email',
'profile',
Expand Down
6 changes: 2 additions & 4 deletions src/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { fileURLToPath } from 'url'
import { defineNuxtModule, addPlugin, resolveModule, createResolver } from '@nuxt/kit'
import { defu } from 'defu'
import { name, version } from '../package.json'
import { logger } from './runtime/utils/logger'

export type CookieSerializeOptions = {
domain?: string | undefined;
Expand Down Expand Up @@ -82,9 +81,8 @@ export default defineNuxtModule<ModuleOptions>({
}
},
setup(options, nuxt) {
logger.level = options.config.debug === true ? 5 : 0 // 4 = debug, 5 = trace
logger.info('[DEBUG MODE]: ', options.config.debug)
logger.debug('[WITHOUT ENV VARS] options:', options)
console.log('[DEBUG MODE]: ', options.config.debug)
console.debug('[WITHOUT ENV VARS] options:', options)

const { resolve } = createResolver(import.meta.url)
const resolveRuntimeModule = (path: string) => resolveModule(path, { paths: resolve('./runtime') })
Expand Down
21 changes: 10 additions & 11 deletions src/runtime/server/routes/oidc/callback.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,13 @@ import * as http from 'http'
import { defineEventHandler, getCookie, setCookie, deleteCookie } from 'h3'
import { initClient } from '../../../utils/issueclient'
import { encrypt } from '../../../utils/encrypt'
import { logger } from '../../../utils/logger'
import { getRedirectUrl, getCallbackUrl, getDefaultBackUrl, getResponseMode, setCookieInfo, setCookieTokenAndRefreshToken } from '../../../utils/utils'
import { useRuntimeConfig } from '#imports'

export default defineEventHandler(async (event) => {
const req = event.node.req
const res = event.node.res
logger.info('[CALLBACK]: oidc/callback calling, method:' + req.method)
console.log('[CALLBACK]: oidc/callback calling, method:' + req.method)

let request = req
if (req.method === 'POST') {
Expand All @@ -27,8 +26,8 @@ export default defineEventHandler(async (event) => {
const sessionid = getCookie(event, config.secret)
deleteCookie(event, config.secret)
const redirectUrl = getRedirectUrl(req.url)
// logger.info('---Callback. redirectUrl:' + redirectUrl)
// logger.info(' -- req.url:' + req.url + ' #method:' + req.method + ' #response_mode:' + responseMode)
// console.log('---Callback. redirectUrl:' + redirectUrl)
// console.log(' -- req.url:' + req.url + ' #method:' + req.method + ' #response_mode:' + responseMode)

const callbackUrl = getCallbackUrl(op.callbackUrl, redirectUrl, req.headers.host)
const defCallBackUrl = getDefaultBackUrl(redirectUrl, req.headers.host)
Expand All @@ -38,13 +37,13 @@ export default defineEventHandler(async (event) => {

if (params.access_token) {
// Implicit ID Token Flow: access_token
logger.debug('[CALLBACK]: has access_token in params, accessToken:' + params.access_token)
console.log('[CALLBACK]: has access_token in params, accessToken:' + params.access_token)
await processUserInfo(params.access_token, null, event)
res.writeHead(302, { Location: redirectUrl || '/' })
res.end()
} else if (params.code) {
// Authorization Code Flow: code -> access_token
logger.debug('[CALLBACK]: has code in params, code:' + params.code + ' ,sessionid=' + sessionid)
console.log('[CALLBACK]: has code in params, code:' + params.code + ' ,sessionid=' + sessionid)
const tokenSet = await issueClient.callback(callbackUrl, params, { nonce: sessionid })
if (tokenSet.access_token) {
await processUserInfo(tokenSet.access_token, tokenSet, event)
Expand All @@ -56,16 +55,16 @@ export default defineEventHandler(async (event) => {
// eslint-disable-next-line no-lonely-if
if (params.error) {
// redirct to auth failed error page.
logger.error('[CALLBACK]: error callback')
logger.error(params.error + ', error_description:' + params.error_description)
console.error('[CALLBACK]: error callback')
console.error(params.error + ', error_description:' + params.error_description)
res.writeHead(302, { Location: '/oidc/error' })
res.end()
} else if (responseMode === 'fragment') {
logger.warn('[CALLBACK]: callback redirect')
console.warn('[CALLBACK]: callback redirect')
res.writeHead(302, { Location: '/oidc/cbt?redirect=' + redirectUrl })
res.end()
} else {
logger.error('[CALLBACK]: error callback')
console.error('[CALLBACK]: error callback')
res.writeHead(302, { Location: redirectUrl || '/' })
res.end()
}
Expand All @@ -84,7 +83,7 @@ export default defineEventHandler(async (event) => {
// userinfo setting
await setCookieInfo(event, config, userinfo)
} catch (err) {
logger.error('[CALLBACK]: ' + err)
console.error('[CALLBACK]: ' + err)
}
}
})
3 changes: 1 addition & 2 deletions src/runtime/server/routes/oidc/cbt.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import { defineEventHandler, setCookie, getCookie } from 'h3'
import { logger } from '@nuxt/kit'
import { CBT_PAGE_TEMPATE } from '../../../utils/template'
import { useRuntimeConfig } from '#imports'

export default defineEventHandler((event) => {
logger.debug('[CBT]: oidc/cbt calling')
console.log('[CBT]: oidc/cbt calling')
const { config } = useRuntimeConfig().openidConnect
const res = event.node.res
const html = CBT_PAGE_TEMPATE
Expand Down
13 changes: 6 additions & 7 deletions src/runtime/server/routes/oidc/login.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,11 @@ import { defineEventHandler, setCookie, getCookie } from 'h3'
import { v4 as uuidv4 } from 'uuid'
import { generators } from 'openid-client'
import { initClient } from '../../../utils/issueclient'
import { logger } from '../../../utils/logger'
import { getRedirectUrl, getCallbackUrl, getDefaultBackUrl, getResponseMode } from '../../../utils/utils'
import { useRuntimeConfig } from '#imports'

export default defineEventHandler(async (event) => {
logger.info('[Login]: oidc/login calling')
console.log('[Login]: oidc/login calling')
const req = event.node.req
const res = event.node.res

Expand All @@ -21,15 +20,15 @@ export default defineEventHandler(async (event) => {
let sessionid = getCookie(event, config.secret)
if (!sessionid) {
sessionid = generators.nonce()
logger.info('[Login]: regenerate sessionid=' + sessionid)
console.log('[Login]: regenerate sessionid=' + sessionid)
} else {
logger.info('[Login]: cookie sessionid=' + sessionid)
console.log('[Login]: cookie sessionid=' + sessionid)
}

const responseMode = getResponseMode(config)
const scopes = op.scope.includes('openid') ? op.scope : [...op.scope, 'openid']
logger.info('[Login]: cabackurl & op.callbackUrl & redirecturl: ', callbackUrl, op.callbackUrl, redirectUrl)
logger.info(' response_mode:' + responseMode + ', response_type:' + config.response_type + ', scopes:' + scopes.join(' '))
console.log('[Login]: cabackurl & op.callbackUrl & redirecturl: ', callbackUrl, op.callbackUrl, redirectUrl)
console.log(' response_mode:' + responseMode + ', response_type:' + config.response_type + ', scopes:' + scopes.join(' '))

const parameters = {
redirect_uri: callbackUrl,
Expand All @@ -39,7 +38,7 @@ export default defineEventHandler(async (event) => {
scope: scopes.join(' ')
}
const authUrl = issueClient.authorizationUrl(parameters)
logger.info('[Login]: Auth Url: ' + authUrl + ', #sessionid:' + sessionid)
console.log('[Login]: Auth Url: ' + authUrl + ', #sessionid:' + sessionid)

if (sessionid) {
setCookie(event, sessionkey, sessionid, {
Expand Down
3 changes: 1 addition & 2 deletions src/runtime/server/routes/oidc/logout.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import { getCookie, deleteCookie, defineEventHandler } from 'h3'
import { logger } from '../../../utils/logger'
import { useRuntimeConfig } from '#imports'

export default defineEventHandler((event) => {
const res = event.node.res
logger.log('[LOGOUT]: oidc/logout calling')
console.log('[LOGOUT]: oidc/logout calling')

const { config } = useRuntimeConfig().openidConnect
deleteCookie(event, config.secret)
Expand Down
16 changes: 7 additions & 9 deletions src/runtime/server/routes/oidc/user.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
import { getCookie, deleteCookie, defineEventHandler } from 'h3'
import { initClient } from '../../../utils/issueclient'
import { encrypt, decrypt } from '../../../utils/encrypt'
import { logger } from '../../../utils/logger'
import { setCookieInfo, setCookieTokenAndRefreshToken } from '../../../utils/utils'
import { useRuntimeConfig } from '#imports'

export default defineEventHandler(async (event) => {
const { config, op } = useRuntimeConfig().openidConnect
logger.debug('[USER]: oidc/user calling')
logger.trace('[USER]: ' + event.req.headers.cookie)
console.log('[USER]: oidc/user calling')

const sessionid = getCookie(event, config.secret)
const accesstoken = getCookie(event, config.cookiePrefix + 'access_token')
Expand All @@ -17,19 +15,19 @@ export default defineEventHandler(async (event) => {
const issueClient = await initClient(op, event.node.req, [])

if (userinfoCookie) {
logger.info('userinfo:Cookie')
console.log('userinfo:Cookie')
const userInfoStr: string | undefined = await decrypt(userinfoCookie, config)
return JSON.parse(userInfoStr ?? '')
} else if (accesstoken) {
logger.info('userinfo:accesstoken')
console.log('userinfo:accesstoken')
try {
// load user info from oidc server.
const userinfo = await issueClient.userinfo(accesstoken)
// add encrypted userinfo to cookies.
await setCookieInfo(event, config, userinfo)
return userinfo
} catch (err) {
logger.error('[USER]: ' + err)
console.error('[USER]: ' + err)
deleteCookie(event, config.secret)
deleteCookie(event, config.cookiePrefix + 'access_token')
deleteCookie(event, config.cookiePrefix + 'user_info')
Expand All @@ -42,7 +40,7 @@ export default defineEventHandler(async (event) => {
return {}
}
} else if (refreshToken) {
logger.info('userinfo:refresh token')
console.log('userinfo:refresh token')
const tokenSet = await issueClient.refresh(refreshToken)
// console.log('refreshed and validated tokens %j', tokenSet)
// console.log('refreshed ID Token claims %j', tokenSet.claims())
Expand All @@ -54,9 +52,9 @@ export default defineEventHandler(async (event) => {
} else {
return {}
}
// logger.info('userinfo:' + userinfo)
// console.log('userinfo:' + userinfo)
} else {
logger.debug('[USER]: empty accesstoken for access userinfo')
console.log('[USER]: empty accesstoken for access userinfo')
return {}
}
})
3 changes: 1 addition & 2 deletions src/runtime/utils/issueclient.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import { Issuer } from 'openid-client'
import { OidcProvider } from '../../module'
import { logger } from './logger'
import { useRuntimeConfig } from '#imports'

export const initClient = async (op: OidcProvider, req: any, redirectUris: string[]) => {
const { config } = useRuntimeConfig().openidConnect
const issuer = await Issuer.discover(op.issuer)
logger.trace('Discovered issuer %s %O', issuer.issuer, issuer.metadata)
// console.log('Discovered issuer %s %O', issuer.issuer, issuer.metadata)
const client = new issuer.Client({
client_id: op.clientId,
client_secret: op.clientSecret,
Expand Down
20 changes: 0 additions & 20 deletions src/runtime/utils/logger.ts

This file was deleted.

Loading

0 comments on commit 816c239

Please sign in to comment.