more details

This commit is contained in:
David Nahodyl 2024-06-10 17:24:49 -04:00
parent b30c465a57
commit b97b4a083a
No known key found for this signature in database
1 changed files with 23 additions and 5 deletions

View File

@ -3,9 +3,11 @@ title: 'Sessions and Authentication'
description: "User registration and authentication is an extremely common requirement in web apps. This recipe will show you how to implement basic user registration and authentication in you Nuxt app."
---
## Introduction
In this recipe we'll be using [Drizzle](https://orm.drizzle.team/) with [db0](https://db0.unjs.io/) for database queries, but you can use any ORM or database connection strategy you prefer.
In this recipe we'll be setting up user registration, login, sessions, and authentication in a full-stack Nuxt app.
We'll be using [Nuxt Auth Utils](https://github.com/Atinux/nuxt-auth-utils) by [Altinux (Sébastien Chopin)](https://github.com/Atinux) which provides convenient utilities for managing front-end and back-end session data. We'll install and use this to get the core session management functionality we're going to need to manage user logins. For the database ORM we'll be using [Drizzle](https://orm.drizzle.team/) with [db0](https://db0.unjs.io/), but you can use any ORM or database connection strategy you prefer.
You'll need a `users` table in your database with the following columns:
- `id` (int, primary key, auto increment)
@ -18,6 +20,10 @@ Additionally, we'll use [nuxt-aut-utils](https://github.com/Atinux/nuxt-auth-uti
### 1. Install nuxt-auth-utils
Install the [auth-utils](https://github.com/Atinux/nuxt-auth-utils) module using the `nuxi` CLI.
```bash
npx nuxi@latest module add auth-utils
```
@ -32,7 +38,7 @@ NUXT_SESSION_PASSWORD=password-with-at-least-32-characters
### 2. Create a registration page
Create a new page in your Nuxt app for user registration. This page should have a form with fields for email and password. We'll intercept the form submission using `@submit.prevent` and use [`$fetch`](/docs/getting-started/data-fetching#fetch) to post the data to `/api/register`.
Create a new page in your Nuxt app for user registration. This page should have a form with fields for email and password. We'll intercept the form submission using `@submit.prevent` and use [`$fetch`](/docs/getting-started/data-fetching#fetch) to post the data to `/api/register`. Here's an example registration form for reference:
```vue [pages/register.vue]
<script setup lang="ts">
@ -116,9 +122,11 @@ Create a new page in your Nuxt app for user registration. This page should have
With the UI created we'll need to add a route to receive the registration form data. This route should accept a POST request with the email and password in the request body. It should hash the password and insert the user into the database. This route will only accept POST requests, so we'll follow the instructions for [API route methods](https://nuxt.com/docs/guide/directory-structure/server#matching-http-method) and name the file with `*.post.ts` to restrict the endpoint to only accept POST.
This is a very simple example of registration. You would probably want to add some error handling and nice response messages. Additionally, you could log the user in as part of the registration process rather than redirecting them to the login screen.
After we've successfully registered the user and stored the record in the database we can log them in by calling the `replaceUserSession` utility function from auth-utils. This utility function is automatically imported by the auth-utils module. We're using `replaceUserSession` here to make sure that any existing session data is cleared and replaced with the user login we're performing now.
```typescript [server/api/register.post.ts]
The example file below is a very simple example of registration. You would probably want to add some error handling and nice response messages.
```typescript [/server/api/register.post.ts]
import users from "~/database/schema/users";
import getDatabase from "~/database/database";
import bcrypt from "bcrypt";
@ -136,8 +144,18 @@ export default defineEventHandler(async (event) => {
password: passwordHash,
});
// log the user in as the user that was just created
// get the user record we just created
const user = (await db.select().from(users).where(eq(users.email, body.email)).limit(1))[0];
// log the user in as the user that was just created
await replaceUserSession(event, {
user: {
id: user.id,
name: user.name,
},
loggedInAt: new Date(),
});
await auth.login(event, user);
});
```