Skip to content
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

feat: added cookie provider #495

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
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
31 changes: 29 additions & 2 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -67,8 +67,6 @@ jobs:
# start prod-app and curl from it
- run: "timeout 60 pnpm start & (sleep 45 && curl --fail localhost:3000)"



test-playground-authjs:
runs-on: ubuntu-latest
defaults:
Expand Down Expand Up @@ -99,3 +97,32 @@ jobs:
env:
AUTH_ORIGIN: 'http://localhost:3001'
PORT: 3001

test-playground-cookie:
runs-on: ubuntu-latest
defaults:
run:
working-directory: ./playground-cookie

steps:
- uses: actions/checkout@v3

- name: Use Node.js 16.14.2
uses: actions/setup-node@v3
with:
node-version: 16.14.2

- uses: pnpm/action-setup@v2
name: Install pnpm
id: pnpm-install
with:
version: 8

# Install deps
- run: pnpm i

# Check building
- run: pnpm build

# start prod-app and curl from it
- run: "timeout 60 pnpm start & (sleep 45 && curl --fail localhost:3000)"
45 changes: 45 additions & 0 deletions playground-cookie/app.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<script lang="ts" setup>
import { ref } from 'vue'
import { useAuth } from '#imports'

const { signIn, data, status, lastRefreshedAt, signOut, getSession } = useAuth()

const username = ref('')
const password = ref('')
</script>

<template>
<div>
<pre>Status: {{ status }}</pre>
<pre>Data: {{ data || 'no session data present, are you logged in?' }}</pre>
<pre>Last refreshed at: {{ lastRefreshedAt || 'no refresh happened' }}</pre>
<form @submit.prevent="signIn({ username, password })">
<input v-model="username" type="text" placeholder="Username">
<input v-model="password" type="password" placeholder="Password">
<button type="submit">
sign in
</button>
</form>
<br>
<button @click="signIn({ username, password }, { callbackUrl: '/protected/globally' })">
sign in (with redirect to protected page)
</button>
<br>
<button @click="signOut({ callbackUrl: '/signout' })">
sign out
</button>
<br>
<button @click="getSession({ required: false })">
refresh session (required: false)
</button>
<br>
<button @click="getSession({ required: true, callbackUrl: '/' })">
refresh session (required: true)
</button>
<br>
<NuxtLink to="/login">
navigate to Login Page
</NuxtLink>
<NuxtPage />
</div>
</template>
31 changes: 31 additions & 0 deletions playground-cookie/nuxt.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
export default defineNuxtConfig({
modules: ['../src/module.ts'],
build: {
transpile: ['jsonwebtoken']
},
auth: {
provider: {
type: 'cookie',
cookie: {
name: 'ApplicationAuth'
},
endpoints: {
getSession: { path: '/user' }
},
pages: {
login: '/'
},
sessionDataType: { id: 'string', email: 'string', name: 'string', role: 'admin | guest | account', subscriptions: "{ id: number, status: 'ACTIVE' | 'INACTIVE' }[]" }
},
session: {
// Whether to refresh the session every time the browser window is refocused.
enableRefreshOnWindowFocus: true,

// Whether to refresh the session every `X` milliseconds. Set this to `false` to turn it off. The session will only be refreshed if a session already exists.
enableRefreshPeriodically: 5000
},
globalAppMiddleware: {
isEnabled: true
}
}
})
24 changes: 24 additions & 0 deletions playground-cookie/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"private": true,
"name": "nuxt-auth-playground-cookie",
"scripts": {
"typecheck": "tsc --noEmit",
"lint": "eslint . --max-warnings=0",
"dev": "nuxi prepare && nuxi dev",
"build": "nuxi build",
"start": "nuxi preview",
"generate": "nuxi generate",
"postinstall": "nuxt prepare"
},
"dependencies": {
"jsonwebtoken": "^9.0.0",
"zod": "^3.21.4"
},
"devDependencies": {
"@types/jsonwebtoken": "^9.0.1",
"eslint": "^8.37.0",
"nuxt": "^3.4.2",
"typescript": "^5.0.3",
"vue-tsc": "^1.2.0"
}
}
11 changes: 11 additions & 0 deletions playground-cookie/pages/always-unprotected.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<template>
<div>I'm always public, even when the global auth middleware is enabled!</div>
</template>

<script setup lang="ts">
import { definePageMeta } from '#imports'

definePageMeta({
auth: false
})
</script>
16 changes: 16 additions & 0 deletions playground-cookie/pages/guest.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<script setup lang="ts">
import { definePageMeta } from '#imports'

definePageMeta({
auth: {
unauthenticatedOnly: true,
navigateAuthenticatedTo: '/protected/globally'
}
})
</script>

<template>
<div>
<p>Hey!</p>
</div>
</template>
31 changes: 31 additions & 0 deletions playground-cookie/pages/index.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<script setup lang="ts">
import { definePageMeta } from '#imports'

definePageMeta({ auth: false })
</script>

<template>
<div>
<nuxt-link to="/">
-> manual login, logout, refresh button
</nuxt-link>
<br>
<nuxt-link to="/protected/globally">
-> globally protected page
</nuxt-link>
<br>
<nuxt-link to="/protected/locally">
-> locally protected page (only works if global middleware disabled)
</nuxt-link>
<br>
<nuxt-link to="/always-unprotected">
-> page that is always unprotected
</nuxt-link>
<br>
<nuxt-link to="/guest">
-> guest mode
</nuxt-link>
<br>
<div>select one of the above actions to get started.</div>
</div>
</template>
33 changes: 33 additions & 0 deletions playground-cookie/pages/login.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<script lang="ts" setup>
import { ref } from 'vue'
import { definePageMeta, useAuth } from '#imports'

const { signIn, token, data, status, lastRefreshedAt } = useAuth()

const username = ref('')
const password = ref('')

definePageMeta({
auth: {
unauthenticatedOnly: true,
navigateAuthenticatedTo: '/'
}
})
</script>

<template>
<div>
<h1>Login Page</h1>
<pre>Status: {{ status }}</pre>
<pre>Data: {{ data || 'no session data present, are you logged in?' }}</pre>
<pre>Last refreshed at: {{ lastRefreshedAt || 'no refresh happened' }}</pre>
<pre>JWT token: {{ token || 'no token present, are you logged in?' }}</pre>
<form @submit.prevent="signIn({ username, password })">
<input v-model="username" type="text" placeholder="Username">
<input v-model="password" type="password" placeholder="Password">
<button type="submit">
sign in
</button>
</form>
</div>
</template>
3 changes: 3 additions & 0 deletions playground-cookie/pages/protected/globally.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
<template>
<div>I'm a secret! My protection works via a global middleware. If you turned off the global middleware, then I'll also be visible without authentication :(</div>
</template>
12 changes: 12 additions & 0 deletions playground-cookie/pages/protected/locally.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<template>
<div>I'm a secret! My protection works via the named `nuxt-auth` module middleware.</div>
</template>

<script setup lang="ts">
import { definePageMeta } from '#imports'

// Note: This is only for testing, it does not make sense to do this with `globalAppMiddleware` turned on
definePageMeta({
middleware: 'auth'
})
</script>
11 changes: 11 additions & 0 deletions playground-cookie/pages/signout.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<template>
<div>
You just signed out!
</div>
</template>

<script setup lang="ts">
import { definePageMeta } from '#imports'

definePageMeta({ auth: false })
</script>
Binary file added playground-cookie/public/favicon.ico
Binary file not shown.
26 changes: 26 additions & 0 deletions playground-cookie/server/api/auth/login.post.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import z from 'zod'
import { sign } from 'jsonwebtoken'

export const SECRET = 'dummy'

export default eventHandler(async (event) => {
const result = z.object({ username: z.string().min(1), password: z.literal('1') }).safeParse(await readBody(event))
if (!result.success) {
throw createError({ statusCode: 403, statusMessage: 'Unauthorized, hint: try `hunter2` as password' })
}

const expiresIn = 1500
const { username } = result.data
const user = {
username,
picture: 'https://github.com/nuxt.png',
name: 'User ' + username
}

const cookieValue = sign({ ...user, scope: ['test', 'user'] }, SECRET, { expiresIn }) // We just use `sign` here to create a payload. The cookie provider does not actually use JWTs. Any user info must come from GetSession

setCookie(event, 'ApplicationAuth', cookieValue, { httpOnly: true, sameSite: 'lax', secure: true })

setResponseStatus(event, 200)
return null
})
4 changes: 4 additions & 0 deletions playground-cookie/server/api/auth/logout.post.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export default eventHandler((event) => {
deleteCookie(event, 'ApplicationAuth')
return { status: 'OK' }
})
22 changes: 22 additions & 0 deletions playground-cookie/server/api/auth/user.get.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { H3Event } from 'h3'
import { verify } from 'jsonwebtoken'
import { SECRET } from '~/server/api/auth/login.post'

const ensureAuth = (event: H3Event) => {
const cookieValue = getCookie(event, 'ApplicationAuth')

if (typeof cookieValue === 'undefined') {
throw createError({ statusCode: 403, statusMessage: 'no cookie found' })
}

try {
return verify(cookieValue, SECRET) // This is just a sample page. The cookie provider does not actually use JWTs.
} catch (error) {
console.error('Login failed. Here\'s the raw error:', error)
throw createError({ statusCode: 403, statusMessage: 'You must be logged in to use this endpoint' })
}
}

export default eventHandler((event) => {
return ensureAuth(event)
})
4 changes: 4 additions & 0 deletions playground-cookie/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"extends": "./.nuxt/tsconfig.json",
"exclude": ["../docs"]
}
Loading