Giter Club home page Giter Club logo

svelte-auth's Introduction

Logo

@svelte-dev/auth

github npm npm npm Maintainability Test Coverage

Simple Authentication for Svlelte.

Features

  • Full Server-Side Authentication
  • Complete TypeScript Support
  • Strategy-based Authentication
  • Easily handle success and failure
  • Implement custom strategies
  • Supports persistent sessions

Overview

Svelte Auth is a complete open-source authentication solution for Svelte applications.

Heavily inspired by Passport.js and Remix-Auth, but completely rewrote it from scratch to work on top of the Web Fetch API. Svelte Auth can be dropped in to any Svelte-based application with minimal setup.

As with Passport.js, it uses the strategy pattern to support the different authentication flows. Each strategy is published individually as a separate npm package.

Installation

To use it, install it from npm (yarn or bun):

npm install @svelte-dev/auth @svelte-dev/session

Usage

API Specification: Documentation

Here's an simple Example:

// hooks.server.ts
import { env } from '$env/dynamic/private';
import { sequence } from '@sveltejs/kit/hooks';
import { handleSession } from '@svelte-dev/session';
import { Auth } from '@svelte-dev/auth';
import { OAuth2Strategy } from '@svelte-dev/auth-oauth2';

export const handle = sequence(
  handleSession({
    adapter: {
      name: 'cookie',
      options: {
        chunk: true
      }
    },
    session: {
      secrets: ['s3cr3t']
    },
    cookie: {
      secure: !!env.SSO_CALLBACK_URL,
      sameSite: 'lax',
      path: '/',
      httpOnly: !!env.SSO_CALLBACK_URL
    }
  }),
  async function handle({ event, resolve }) {
    const auth = new Auth(event);
    const oauthStrategy = new OAuth2Strategy(
      {
        clientID: env.SSO_ID,
        clientSecret: env.SSO_SECRET,
        callbackURL: env.SSO_CALLBACK_URL || 'http://localhost:8788/auth/sso/callback'
      },
      async ({ profile }) => {
        // Get the user data from your DB or API using the tokens and profile
        return profile;
      }
    );
    auth.use(oauthStrategy);
    event.locals.auth = auth;
    event.locals.user = event.locals.session.get(
      // replace your session key, AuthOptions.sessionKey
      'user'
    );
    const response = await resolve(event);

    return response;
  }
);

Then, add a login handler src/routes/auth/[provider]/+server.ts:

import { redirect, type RequestEvent } from '@sveltejs/kit';

export const GET = async (event: RequestEvent) => {
  const { request } = event;
  const provider = event.params.provider ?? 'github';
  return await event.locals.auth.authenticate(event, provider, {
    successRedirect: '/dashboard',
    failureRedirect: '/error'
  });
};

Finally, add a callback handler src/routes/auth/[provider]/callback/+server.ts.ts:

// same as before...
import type { RequestEvent } from '@sveltejs/kit';

export const GET = async (event: RequestEvent) => {
  const provider = event.params.provider ?? 'github';

  return await event.locals.auth.authenticate(event, provider, {
    successRedirect: '/dashboard',
    failureRedirect: '/error'
  });
};

Advanced Usage

Typescript

Modify app.d.ts, here is an example:

// See https://kit.svelte.dev/docs/types#app
// for information about these interfaces
declare global {
  namespace App {
    // interface Error {}
    interface Locals {
      auth: Auth;
      session: SessionStorage<{ user: any }>;
      user:
        | {
            invalid?: boolean;
            [key: string]: unknown;
          }
        | unknown;
    }
    // interface PageData {}
    interface Platform {
      env: {
        SSO_ID: string;
        SSO_SECRET: string;
      };
      context: {
        waitUntil(promise: Promise<unknown>): void;
      };
      caches: CacheStorage & { default: Cache };
    }
  }
}

export {};

赞助 Sponsor

维护者 Owner: Willin Wang

如果您对本项目感兴趣,可以通过以下方式支持我:

Donation ways:

许可证 License

Apache-2.0

svelte-auth's People

Contributors

willin avatar

Stargazers

 avatar

Watchers

 avatar  avatar

Forkers

svelte-dev

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.