Skip to content

Commit

Permalink
sign up function to return data, test written
Browse files Browse the repository at this point in the history
  • Loading branch information
iamKiNG-Fr committed Sep 8, 2024
1 parent 7a4ed34 commit e3bf0fc
Show file tree
Hide file tree
Showing 5 changed files with 115 additions and 1 deletion.
3 changes: 2 additions & 1 deletion playground-local/nuxt.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ export default defineNuxtConfig({
provider: {
type: 'local',
endpoints: {
getSession: { path: '/user' }
getSession: { path: '/user' },
signUp:{path:'/signup', method: 'post'}
},
pages: {
login: '/'
Expand Down
4 changes: 4 additions & 0 deletions playground-local/pages/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ definePageMeta({ auth: false })
-> manual login, logout, refresh button
</nuxt-link>
<br>
<nuxt-link to="/register">
-> Click to signup
</nuxt-link>
<br>
<nuxt-link to="/protected/globally">
-> globally protected page
</nuxt-link>
Expand Down
43 changes: 43 additions & 0 deletions playground-local/pages/register.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<script setup>
import { ref } from "vue";
import { definePageMeta, useAuth } from "#imports";
const { signUp } = useAuth();
const username = ref("");
const password = ref("");
const response = ref()
const register = async () => {
try {
const signUpResponse = await signUp({username: username.value, password: password.value}, undefined, { preventLoginFlow: true })
response.value = signUpResponse
} catch (error) {
response.value = { error: "Failed to sign up" };
}
}
definePageMeta({
auth: {
unauthenticatedOnly: true,
navigateAuthenticatedTo: "/",
},
});
</script>

<template>
<div>
<form @submit.prevent="register">
<p><i>*password should have at least 6 characters</i></p>
<input v-model="username" type="text" placeholder="Username" data-testid="regUsername">
<input v-model="password" type="password" placeholder="Password" data-testid="regPassword">
<button type="submit" data-testid="regSubmit">
sign up
</button>
</form>
<div v-if="response">
<h2>Response</h2>
<pre data-testid="regResponse">{{ response }}</pre>
</div>
</div>
</template>
40 changes: 40 additions & 0 deletions playground-local/server/api/auth/signup.post.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { createError, eventHandler, readBody } from 'h3'
import { z } from 'zod'
import { sign } from 'jsonwebtoken'

export const SECRET = 'dummy'

export default eventHandler(async (event) => {
// Define the schema for validating the incoming data
const result = z.object({
username: z.string(),
password: z.string().min(6)
}).safeParse(await readBody(event))

// If validation fails, return an error
if (!result.success) {
throw createError({
statusCode: 400,
statusMessage: 'Invalid input, please provide a valid email and a password of at least 6 characters.'
})
}

const { username, password } = result.data

const expiresIn = '1h' //token expiry (1 hour)
const user = { username } // Payload for the token, includes the email

// Sign the JWT with the user payload and secret
const accessToken = sign(user, SECRET, { expiresIn })

// Return a success response with the email and the token
return {
message: 'Signup successful!',
user: {
username
},
token: {
accessToken
}
}
})
26 changes: 26 additions & 0 deletions playground-local/tests/local.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,4 +59,30 @@ describe('local Provider', async () => {
await signoutButton.click()
await playwrightExpect(status).toHaveText(STATUS_UNAUTHENTICATED)
})

it('should sign up and return signup data when preventLoginFlow: true', async () => {
const page = await createPage('/register') // Navigate to signup page

const [
usernameInput,
passwordInput,
submitButton,
] = await Promise.all([
page.getByTestId('regUsername'),
page.getByTestId('regPassword'),
page.getByTestId('regSubmit')
])

await usernameInput.fill('newuser')
await passwordInput.fill('hunter2')

// Click button and wait for API to finish
const responsePromise = page.waitForResponse(/\/api\/auth\/signup/)
await submitButton.click()
const response = await responsePromise

// Expect the response to return signup data
const responseBody = await response.json() // Parse response
playwrightExpect(responseBody).toBeDefined() // Ensure data is returned
})
})

0 comments on commit e3bf0fc

Please sign in to comment.