npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@mcdba/auth

v0.0.7

Published

Easy email-password authentication lib for sveltekit

Downloads

3

Readme

Authentication library for sveltekit

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

Lib entry point

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

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

add @mcdba/auth

npm install @mcdba/auth

and create .env file

DB_PATH=data/sqlite.db
[email protected]
EMAIL_SERVER=smtp://username:[email protected]:578
JWT_SECRET=jwtSecret
SITE_URL=http://localhost:5173/

create hooks.server.ts file in src directory

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

<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

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

<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

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

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

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

src/routes/(protected)/userprofile/+page.svelte

only logined user can acess to page