Skip to content

A simple middleware for authentication in KOA2 with Firebase

Notifications You must be signed in to change notification settings

firebase-me/koa-firebase-auth

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

29 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Koa Firebase Auth

A simple middleware for authentication in Koa 2 with Firebase, This library using the Firebase Admin for verify and authentication from Firebase database or local memory only.

This is a work in progress and is not intended for use

My goal is to update the dependencies to be more lite weight in general, support redis and local storage over any databases with large backends unless its absolutely needed. We will do this by setting up custom listeners and internal config of preferences.

by default, we will only use Redis for in memory only authentication. used for small scale applications. Possibly support firebase realtime for small to medium applications but only for instance sharding purposes. for true large applications, it would be best to use custom listeners where users can define their own operations.

Requires

  • KOA.js version 2+
  • Node.js version 10+
  • Redis version 3+

Install

npm install koa-firebase-auth

Setup

Listeners

To use this library you have to start MongoDB and Redis server before, Redis for caching the token and expiry time and MongoDB for store fid and insert a new user.

Implement with Koa

This library is a middleware in Koa.js only support in version 2.

Usage

Will show an example and how to use this library in CommonJS.

  1. You have to require Koa, Koa-router and this lib.
const Koa = require('koa')
const Router = require('koa-router')
const firebaseAuth = require('koa-firebase-auth')
...
  1. Create new Koa application and using Koa router.
...
const app = new Koa()
const router = new Router()
...
  1. Create initialize for middleware and prepaid datas from Firebase.

Where can i get it? Going to Firebase Admin SDK

  • credential is json object get it from Firebase database.
...
firebaseAuth.init({
  credential: require('./FIREBASE_ACCESS_KEY.json'),
  databaseURL: 'https://SOME_ID.firebaseio.com'
})
...
  1. Create a router and listen the application with one middleware firebaseAuth.verifyAccessToken and these keys are require in headers.
{
	"Authorization": "ACCESS_TOKEN_FROM_FIREBASE",
	"FID": "FIREBASE_FROM_FIREBASE"
}
  • Authorization is access token from Firebase.
  • FID is unique id from Firebase.
...
router.get('/', firebaseAuth.verifyAccessToken, (ctx, next) => {
  ctx.body = 'Welcome to Firebase Middleware'
})

app
  .use(router.routes())
  .use(router.allowedMethods())

app.listen(3000, () => {
  console.log('listening on port 3000')
})

If you want to use ctx.user that datas from Redis, you just add passUserContext method to be middleware like this:

...
router.get('/users/currently-logged', firebaseAuth.passUserContext, (ctx, next) => {
  ctx.body = 'Welcome to Firebase Middleware'
})
  • The passUserContext method will not checking on Firebase Database and will not throw "Unauthorized"

Example

This an example for basic authorization with Firebase, simple and very easy to use it.

const Koa = require('koa')
const Router = require('koa-router')
const firebaseAuth = require('koa-firebase-auth')

const app = new Koa()
const router = new Router()

firebaseAuth.init({
  credential: require('./FIREBASE_ACCESS_KEY.json'),
  databaseURL: 'https://SOME_ID.firebaseio.com'
})

router.get('/', firebaseAuth.verifyAccessToken, (ctx, next) => {
  ctx.body = 'Welcome to Firebase Middleware'
})

app
  .use(router.routes())
  .use(router.allowedMethods())

app.listen(3000, () => {
  console.log('listening on port 3000')
})

Customize

this library is support custom to any fields in init option's object, by the way we provide default values for using like this:

{
  credential: null,
  databaseURL: null,
  mongo: {
    url: 'mongodb://localhost:27017/firebase_auth',
    userCollection: 'users',
    fields: {
      authFirebase: 'authFirebase',
      createdAt: 'createdAt',
      fid: 'fid'
    }
  },
  redis: {
    url: 'redis://localhost:6379/0',
    storeKey: 'fid:%(fid)s'
  },
  header: {
    tokenKey: 'Authorization',
    fidKey: 'FID'
  }
}

You can custom any field in above just create an object and put it in init see example below:

firebaseAuth.init({
  credential: require('./key.json'),
  databaseURL: 'https://traova.firebaseio.com',
  mongo: {
    url: 'mongodb://docker:27010/traova',
    userCollection: '_users',
    fields: {
      authFirebase: '_auth_firebase',
      createdAt: '_created_at',
      fid: 'firebase_id'
    }
  }
})

I did custom in mongo section, set url to connect to docker on port 27010, database name "traova", connection to user collection named "_users" and store custom fields.

It should be store into you MongoDB like this:

{
  "_id" : ObjectId("5a1d10cf5b5f4c85e5f2477f"),
  "_auth_firebase": {
    "firebase_id": "AfBru1sf5b5f4c85e5f10Sd9"
  },
  "_created_at": ISODate("2017-11-28T14:31:27.138+0700")
}

License

The MIT License

About

A simple middleware for authentication in KOA2 with Firebase

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages

  • JavaScript 100.0%