Git Product home page Git Product logo

elysia-oauth2's Introduction

@bogeychan/elysia-oauth2

A plugin for Elysia.js for server-side OAuth 2.0 Authorization Code Flow

Installation

bun add @bogeychan/elysia-oauth2

Usage

import { Elysia } from 'elysia';
import oauth2, { github } from '@bogeychan/elysia-oauth2';

import { randomBytes } from 'crypto';

const globalState = randomBytes(8).toString('hex');
let globalToken = null;

const app = new Elysia();

const auth = oauth2({
  profiles: {
    // define multiple OAuth 2.0 profiles
    github: {
      provider: github(),
      scope: ['user']
    }
  },
  state: {
    // custom state verification between requests
    check(req, name, state) {
      return state === globalState;
    },
    generate(req, name) {
      return globalState;
    }
  },
  storage: {
    // storage of users' access tokens is up to you
    async get(req, name) {
      return globalToken;
    },
    async set(req, name, token) {
      globalToken = token;
    },
    async delete(req, name) {
      globalToken = null;
    }
  }
});

function userPage(user: {}, logout: string) {
  const html = `<!DOCTYPE html>
    <html lang="en">
    <body>
      User:
      <pre>${JSON.stringify(user, null, '\t')}</pre>
      <a href="${logout}">Logout</a>
    </body>
    </html>`;

  return new Response(html, { headers: { 'Content-Type': 'text/html' } });
}

app
  .use(auth)
  .get('/', async (ctx) => {
    // get login, callback, logout urls for one or more OAuth 2.0 profiles
    const profiles = ctx.profiles('github');

    // check if one or more OAuth 2.0 profiles are authorized
    if (await ctx.authorized('github')) {
      const user = await fetch('https://api.github.com/user', {
        // ... and use the Authorization header afterwards
        headers: await ctx.tokenHeaders('github')
      });

      return userPage(await user.json(), profiles.github.logout);
    }

    // Render login page
    const html = `<!DOCTYPE html>
    <html lang="en">
    <body>
      <h2>Login with <a href="${profiles.github.login}">Github</a></h2>
    </body>
    </html>`;

    return new Response(html, { headers: { 'Content-Type': 'text/html' } });
  })
  .listen(3000);

console.log('Listening on http://localhost:3000');

Where are the client credentials?

  1. Generate a client id and client secret for an OAuth app on Github
  2. Use http://localhost:3000/login/github/authorized as your Authorization callback URL
  3. Create an .env file based on the previously generated client credentials:
    GITHUB_OAUTH_CLIENT_ID=client id
    GITHUB_OAUTH_CLIENT_SECRET=client secret
  4. Bun automatically loads environment variables from .env files

If you are unsure which URL should be used as Authorization callback URL call ctx.profiles() without an argument to get all URLs of all registered OAuth 2.0 Profiles:

app
  .use(auth)
  .get('/', (ctx) => {
    return ctx.profiles();
  })
  .listen(3000);

Use predefined OAuth 2.0 providers

import { azure, discord, github, ... } from '@bogeychan/elysia-oauth2';

Define your own OAuth 2.0 provider

import oauth2, { TOAuth2Provider } from '@bogeychan/elysia-oauth2';

function myGithub(): TOAuth2Provider {
  return {
    clientId: 'YOUR_CLIENT_ID',
    clientSecret: 'YOUR_CLIENT_SECRET',

    auth: {
      url: 'https://github.com/login/oauth/authorize',
      params: {
        allow_signup: true
      }
    },

    token: {
      url: 'https://github.com/login/oauth/access_token',
      params: {}
    }
  };
}

const auth = oauth2({
  profiles: {
    github: {
      provider: myGithub(),
      scope: ['user']
    }
  }
  // ...
});

Author

bogeychan

License

MIT

elysia-oauth2's People

Contributors

bogeychan avatar

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.