npm package: @mcdba/auth
Description: Easy email-password authentication lib for sveltekit
Latest version: 0.0.7

# Authentication library for sveltekit



sample on github https://github.com/mcdba/sample_mcdba_auth


Lib entry point 
```svelte
import { authHandle } from "@mcdba/auth";
const handle: Handle = authHandle({
	dbPath: string;  // path to sqlite database like data/sqlite.db
	siteUrl?: string; // url for site (for registration mail) if skip used current url
 	emailServer: string; // options for nodemailer transport
	emailFrom: string; //from email nodemailer
	jwtSecret: string; // jwt secrets for 
})
```

this handle insert two locals 
event.local.user - current user object or null
and
event.locals.auth - auth class with metods:

- logIn(email: string, password: string, event: RequestEvent)
- logOut(event: RequestEvent)
- signIn(email: string, password: string) 



## Creating a sveltekit project

```bash
# create a new project in my-app
npm create svelte@latest my-app
cd my-app
npm install
```

 add @mcdba/auth

```bash
npm install @mcdba/auth
```
and create .env file 

```
DB_PATH=data/sqlite.db
EMAIL_FROM=noreplay@example.com
EMAIL_SERVER=smtp://username:password@smtp.example.com:578
JWT_SECRET=jwtSecret
SITE_URL=http://localhost:5173/
```

### create hooks.server.ts file in src directory

```svelte
import { redirect, type Handle } from "@sveltejs/kit";
import { sequence } from "@sveltejs/kit/hooks";
import { authHandle } from "@mcdba/auth";
import { DB_PATH, EMAIL_FROM, EMAIL_SERVER, JWT_SECRET, SITE_URL } from "$env/static/private";

const protectedRoute: Handle = async ({ event, resolve }) => {
	if (event.route.id?.startsWith("/(protected)")) {
		if (!event.locals.user) {
			const message = "Вы должны авторизоваться для доступа к этой странице";
			const redirectTo = event.url.pathname + event.url.search;
			throw redirect(303, `/login?redirectTo=${redirectTo}&message=${message}`);
		}
	}
	return await resolve(event);
};

export const handle = sequence(
	authHandle({
		dbPath: DB_PATH,
		siteUrl: SITE_URL,
		jwtSecret: JWT_SECRET,
		emailFrom: EMAIL_FROM,
		emailServer: EMAIL_SERVER,
	}),
	protectedRoute
);
```

### make registration page 
src/routes/registration/+page.svelte
```svelte
<form method="post">
	<input type="email" class="input" name="email" placeholder="email..." />
	<input type="password" class="input" name="password" placeholder="password.." />
	<button class="btn" type="submit">register</button>
</form>
```
src/routes/registration/+page.server.ts
```svelte
import type { Actions } from "./$types";
import { fail, redirect } from "@sveltejs/kit";
export const actions = {
	default: async ({ request, locals }) => {
		const data = await request.formData();
		const email = data.get("email")?.toString();
		const password = data.get("password")?.toString() || "";
		if (!email) {
			return fail(400, { email, missing: true });
		}
		await locals.auth.signIn(email, password);
		throw redirect(303, "/");
	},
} satisfies Actions;
```

### login page
src/routes/login/+page.svelte
```svelte
<form method="post" class="card">
	<input type="email" class="input" name="email" placeholder="email..." />
	<input type="password" class="input" name="password" placeholder="password.." />
	<button class="btn" type="submit">login</button>
</form>
```
src/routes/login/+page.server.ts
```svelte
import type { Actions } from "./$types";
import { fail, redirect } from "@sveltejs/kit";
export const actions = {
	default: async (event) => {
		const { cookies, request, locals } = event;
		try {
			const data = await request.formData();
			const email = data.get("email")?.toString() || "";
			const password = data.get("password")?.toString() || "";
			await locals.auth.logIn(email, password, event);
		} catch (err) {
			return fail(400, { message: "Counld not login user" });
		}
		throw redirect(302, "/");
	},
} satisfies Actions;
```

### make activation route
src/routes/activation/[activationLink]/+server.ts
```svelte
import { error, redirect } from "@sveltejs/kit";

import type { RequestHandler } from "../$types";

export const GET = (async ({ locals, params }) => {
	try {
		await locals.auth.activate(params.activationLink);
	} catch (err) {
		throw error(404, { message: "activation link not exist" });
	}
	throw redirect(303, "/login");
}) satisfies RequestHandler;
```
### make logout route
src/route/logout/+server.ts
```svelte
import { error, redirect, type RequestHandler } from "@sveltejs/kit";

export const GET = (async (event) => {
	try {
		await event.locals.auth.logOut(event);
	} catch (err) {
		throw error(403, { message: "server err" });
	}
	throw redirect(303, "/");
}) satisfies RequestHandler;
```

# done
all protected routes placed in 
src/routes/(protected) path like

```bash
src/routes/(protected)/userprofile/+page.svelte
```
only logined user can acess to page