Giter VIP home page Giter VIP logo

subhendukundu / worker-auth-providers Goto Github PK

View Code? Open in Web Editor NEW
257.0 7.0 27.0 837 KB

worker-auth-providers is an open-source providers to make authentication easy with workers. Very lightweight script which doesn't need a lot of dependencies. Plug it with any framework or template of workers.

Home Page: https://authc1.com

JavaScript 1.18% TypeScript 95.19% HTML 1.03% CSS 1.76% MDX 0.84%
authentication oauth2 cloudflare-workers cloudflare google-login github-login spotify auth worker-discord-login discord-login

worker-auth-providers's Introduction

worker-auth-providers

worker-auth-providers

An open-source auth providers for Cloudflare workers

Repo Size Issues Pull Requests Last Commit

worker-auth-providers is an open-source providers to make authentication easy with workers. Very lightweight script which doesn't need a lot of dependencies. Plug it with any framework or template of workers.

πŸš€ Demo

Try now

🧐 Features

  • Open Source
  • Fast & Lightweight
  • Easy

πŸ› οΈ Installation

Step 1: Install the dependencies

npm install worker-auth-providers

Step 2: Import the dependencies

import {
  github, google,
  twilio, facebook, discord,
  spotify
} from "worker-auth-providers";

Step 3: Redirect users

const githubLoginUrl = await github.redirect({
    options: {
        clientId,
    },
});
return {
    status: 302,
    headers: {
        location: githubLoginUrl,
    },
};

// or send otp

const res = await awsSNS.send({
  options: {
    phone,
    region: 'ap-south-1',
    kvProvider: WORKER_AUTH_PROVIDERS_STORE,
  },
})

Step 4: Get user

const { user: providerUser, tokens } = await github.users({
    options: { clientSecret, clientId },
    request,
});
console.log("[providerUser]", providerUser);

// or verify otp
const res = await awsSNS.verify({
  options: {
    phone,
    otp,
    kvProvider: WORKER_AUTH_PROVIDERS_STORE,
    secret: 'eyJhbGciOiJIUzI1NiJ9.ew0KICAic3ViIjogIjE2Mjc4MTE1MDEiLA0KICAibmFtZSI6ICJoYWFsLmluIiwNCiAgImlhdCI6ICIwMTA4MjAyMCINCn0.aNr18szvBz3Db3HAsJ-2KHYbnnHwHfK65CiZ_AWwpc0',
  },
})

πŸ“ƒ Documentation

Coming soon

πŸ‘©β€πŸ’» Tech

🍰 Contributing

Contributions are always welcome! See contributing.md for ways to get started. Please adhere to this project's code of conduct.

Roadmap

  • Docs.
  • Apple.
  • Azure (Microsoft)
  • Google.
  • Github
  • OTP Twilio
  • Mailgun Email
  • Sendgrid Email
  • Facebook
  • Discord
  • Instagram
  • Amazon
  • Twitter
  • Spotify
  • Auth0

##FAQs

How to persist login?

Use cookie. Setting a cookie to indicate that they’re authorized for future requests

const cookieKey = "worker-auth-providers"
const persistAuth = async exchange => {
    const date = new Date()  date.setDate(date.getDate() + 1)
    const headers = { 
      Location: "/",
      "Set-cookie": `${cookieKey}=${id}; Secure; HttpOnly; SameSite=Lax; Expires=${date.toUTCString()}`,
    }
    return { headers, status: 302 }
}

How to logout?

Easy, delete the cookie

export const logout = event => {
  const cookieHeader = event.request.headers.get('Cookie')
  if (cookieHeader && cookieHeader.includes(cookieKey)) {
    return {
      headers: {
        'Set-cookie': `${cookieKey}=""; HttpOnly; Secure; SameSite=Lax;`,
      },
    }
  }
  return {}
}

Feedback

If you have any feedback, please reach out to me at [email protected]

✍️ Authors

πŸ’Ό License

MIT

worker-auth-providers's People

Contributors

cometkim avatar da7a90-backup avatar hellodword avatar m0o0scar avatar nathanclevenger avatar subhendukundu avatar walshydev avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

worker-auth-providers's Issues

Redirect Options inconsistency with facebook

Every other redirect options looks like:

  const location = await github.redirect({
    options: {
    }
  })

Facebooks looks like:

  const location = await facebook.redirect({

  })

Can we make this consistent please

Webpack 5 breaking changes

I`m using webpack and unable to compile this.

Errors are:

ERROR in ./node_modules/worker-auth-providers/src/index.js 1:0-45
Module not found: Error: Can't resolve './providers/github' in '/.../node_modules/worker-auth-providers/src'
Did you mean 'index.js'?
BREAKING CHANGE: The request './providers/github' failed to resolve only because it was resolved as fully specified
(probably because the origin is strict EcmaScript Module, e. g. a module with javascript mimetype, a '*.mjs' file, or a '*.js' file where the package.json contains '"type": "module"').
The extension in the request is mandatory for it to be fully specified.
Add the extension to the request.
 @ ./src/worker.ts 10:32-64
 @ ./src/index.ts 3:17-36

ERROR in ./node_modules/worker-auth-providers/src/index.js 2:0-45
Module not found: Error: Can't resolve './providers/google' in '/.../node_modules/worker-auth-providers/src'
Did you mean 'index.js'?
BREAKING CHANGE: The request './providers/google' failed to resolve only because it was resolved as fully specified
(probably because the origin is strict EcmaScript Module, e. g. a module with javascript mimetype, a '*.mjs' file, or a '*.js' file where the package.json contains '"type": "module"').
The extension in the request is mandatory for it to be fully specified.
Add the extension to the request.
 @ ./src/worker.ts 10:32-64
 @ ./src/index.ts 3:17-36

ERROR in ./node_modules/worker-auth-providers/src/index.js 3:0-46
Module not found: Error: Can't resolve './providers/aws-sns' in '/.../node_modules/worker-auth-providers/src'
Did you mean 'index.js'?
BREAKING CHANGE: The request './providers/aws-sns' failed to resolve only because it was resolved as fully specified
(probably because the origin is strict EcmaScript Module, e. g. a module with javascript mimetype, a '*.mjs' file, or a '*.js' file where the package.json contains '"type": "module"').
The extension in the request is mandatory for it to be fully specified.
Add the extension to the request.
 @ ./src/worker.ts 10:32-64
 @ ./src/index.ts 3:17-36

ERROR in ./node_modules/worker-auth-providers/src/index.js 4:0-45
Module not found: Error: Can't resolve './providers/twilio' in '/.../node_modules/worker-auth-providers/src'
Did you mean 'index.js'?
BREAKING CHANGE: The request './providers/twilio' failed to resolve only because it was resolved as fully specified
(probably because the origin is strict EcmaScript Module, e. g. a module with javascript mimetype, a '*.mjs' file, or a '*.js' file where the package.json contains '"type": "module"').
The extension in the request is mandatory for it to be fully specified.
Add the extension to the request.
 @ ./src/worker.ts 10:32-64
 @ ./src/index.ts 3:17-36

ERROR in ./node_modules/worker-auth-providers/src/index.js 5:0-49
Module not found: Error: Can't resolve './providers/facebook' in '/.../node_modules/worker-auth-providers/src'
Did you mean 'index.js'?
BREAKING CHANGE: The request './providers/facebook' failed to resolve only because it was resolved as fully specified
(probably because the origin is strict EcmaScript Module, e. g. a module with javascript mimetype, a '*.mjs' file, or a '*.js' file where the package.json contains '"type": "module"').
The extension in the request is mandatory for it to be fully specified.
Add the extension to the request.
 @ ./src/worker.ts 10:32-64
 @ ./src/index.ts 3:17-36

ERROR in ./node_modules/worker-auth-providers/src/index.js 6:0-47
Module not found: Error: Can't resolve './providers/discord' in '/.../node_modules/worker-auth-providers/src'
Did you mean 'index.js'?
BREAKING CHANGE: The request './providers/discord' failed to resolve only because it was resolved as fully specified
(probably because the origin is strict EcmaScript Module, e. g. a module with javascript mimetype, a '*.mjs' file, or a '*.js' file where the package.json contains '"type": "module"').
The extension in the request is mandatory for it to be fully specified.
Add the extension to the request.
 @ ./src/worker.ts 10:32-64
 @ ./src/index.ts 3:17-36

ERROR in ./node_modules/worker-auth-providers/src/index.js 7:0-47
Module not found: Error: Can't resolve './providers/spotify' in '/.../node_modules/worker-auth-providers/src'
Did you mean 'index.js'?
BREAKING CHANGE: The request './providers/spotify' failed to resolve only because it was resolved as fully specified
(probably because the origin is strict EcmaScript Module, e. g. a module with javascript mimetype, a '*.mjs' file, or a '*.js' file where the package.json contains '"type": "module"').
The extension in the request is mandatory for it to be fully specified.
Add the extension to the request.
 @ ./src/worker.ts 10:32-64
 @ ./src/index.ts 3:17-36

ERROR in ./node_modules/worker-auth-providers/src/index.js 8:0-60
Module not found: Error: Can't resolve './providers/sendgrid-email' in '/.../node_modules/worker-auth-providers/src'
Did you mean 'index.js'?
BREAKING CHANGE: The request './providers/sendgrid-email' failed to resolve only because it was resolved as fully specified
(probably because the origin is strict EcmaScript Module, e. g. a module with javascript mimetype, a '*.mjs' file, or a '*.js' file where the package.json contains '"type": "module"').
The extension in the request is mandatory for it to be fully specified.
Add the extension to the request.
 @ ./src/worker.ts 10:32-64
 @ ./src/index.ts 3:17-36

ERROR in ./node_modules/worker-auth-providers/src/index.js 9:0-58
Module not found: Error: Can't resolve './providers/mailgun-email' in '/.../node_modules/worker-auth-providers/src'
Did you mean 'index.js'?
BREAKING CHANGE: The request './providers/mailgun-email' failed to resolve only because it was resolved as fully specified
(probably because the origin is strict EcmaScript Module, e. g. a module with javascript mimetype, a '*.mjs' file, or a '*.js' file where the package.json contains '"type": "module"').
The extension in the request is mandatory for it to be fully specified.
Add the extension to the request.
 @ ./src/worker.ts 10:32-64
 @ ./src/index.ts 3:17-36

webpack.config.js

const path = require('path')

module.exports = {
  entry: './src/index.ts',
  output: {
    filename: 'worker.js',
    path: path.join(__dirname, 'dist'),
  },
  devtool: 'cheap-module-source-map',
  mode: 'production',
  resolve: {
    extensions: ['.ts', '.tsx', '.js'],
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        loader: 'ts-loader',
        options: {
          // transpileOnly is useful to skip typescript checks occasionally:
          // transpileOnly: true,
        },
      },
    ],
  },
}

tsconfig.json

{
  "compilerOptions": {
    "outDir": "./dist",
    "module": "commonjs",
    "target": "esnext",
    "lib": ["esnext"],
    "alwaysStrict": true,
    "strict": true,
    "preserveConstEnums": true,
    "moduleResolution": "node",
    "sourceMap": true,
    "esModuleInterop": true,
    "types": [
      "@cloudflare/workers-types",
      "@types/service-worker-mock",
	  "@types/node"
    ],
	"noImplicitAny": false,
	"useUnknownInCatchVariables": false,
  },
  "include": ["src"],
  "exclude": ["node_modules", "dist", "test"]
}

package.json

"webpack": "^5.38.1",
"webpack-cli": "^4.7.0"

Tries messing with webpack rules but no success.

Paypal

want to confirm paypal transaction statuses.

Without user:email in the scope will cause an error of github provider

if (!data.email) {
// If the user does not have a public email, get another via the GitHub API
// See https://docs.github.com/en/rest/users/emails#list-public-email-addresses-for-the-authenticated-user
const res: any = await fetch("https://api.github.com/user/emails", {
method: 'GET',
headers,
});
const emails = await res.json()
data.emails = emails
data.email = (emails.find((e: any) => e.primary) ?? emails[0]).email
}

Without user:email in the scope:

const githubLoginUrl = await github.redirect({
    options: {
        scope: ['read:user'],

And when I'm a github user without public emails, I will get an error:

TypeError: o.find is not a function

I hope email could be optional.

new release

Hello there, is there a plan to create a new npm release soon?

getTokensFromCode, in the apple provider, is not exported in the latest release available at npmjs

Thanks!

Usage clarification / examples / documentation

Hello,

Could you please clarify a bit on the following:

// or send otp

What do you mean by that? As far as I'm aware, if you have 2FA enabled on your account, GitHub will prompt you for it. How can I know this and use the "// or send otp" as mentioned?

Can you also add some examples for those that have no idea:

  • How to get clientSecret, clientId (for several apps)
  • What is VITEDGE (and do we really need it?)
  • What KV namespaces to create (I see WORKER_AUTH_PROVIDERS_STORE hardcoded)

Many thanks

URGENT Apple OAUTH implementation incorrect

async function getUser(token) {
    try {
        const data = decodeJwt(token);
        logger.log(`[provider user data], ${JSON.stringify(data)}`, "info");
        return data;
    }
    catch (e) {
        logger.log(`[error], ${JSON.stringify(e.stack)}`, "error");
        throw new ProviderGetUserError({
            message: "There was an error fetching the user",
        });
    }
}

export default async function callback({ options, request, }) {
    const { query } = parseQuerystring(request);
    logger.setEnabled(options?.isLogEnabled || false);
    logger.log(`[code], ${JSON.stringify(query.code)}`, "info");
    if (!query.code) {
        throw new ConfigError({
            message: "No code is passed!",
        });
    }
    const tokens = await getTokensFromCode(query.code, options);
    const accessToken = tokens.access_token;
    logger.log(`[access_token], ${JSON.stringify(accessToken)}`, "info");
    const providerUser = await getUser(accessToken);
    return {
        user: providerUser,
        tokens,
    };
}

Current, implementation tries to get the user information by decoding the access token from Apple.

It should be decoding the id_token.

GitHub provider only returns public emails

Currently, the GitHub provider only returns an email if the user has a public email address shared on their profile.

Even though the user:email is part of the scope, to get the user, there needs to be a subsequent call to get their email address. See https://docs.github.com/en/rest/users/emails#list-public-email-addresses-for-the-authenticated-user for additional context.

Something like this in https://github.com/subhendukundu/worker-auth-providers/blob/main/src/providers/github/users.js:

    const getUserResponse = await fetch('https://api.github.com/user', {
      method: 'GET',
      headers,
    });
    const data = await getUserResponse.json();
    console.log('[provider user data]', data);
    if (!data.email) {
          // If the user does not have a public email, get another via the GitHub API
          // See https://docs.github.com/en/rest/users/emails#list-public-email-addresses-for-the-authenticated-user
          const res = await fetch("https://api.github.com/user/emails", {
                method: 'GET',
                headers,
          });
          const emails: GithubEmail[] = await res.json()
          console.log('[provider user emails]', emails);
          data.email = emails
    }
    return data;

If you think it looks good, I'll make a PR

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.