1.1.0 • Published 6 years ago

@dav-nazaryan/brainstorm-task v1.1.0

Weekly downloads
1
License
ISC
Repository
-
Last release
6 years ago

Usage

Init new instance

const auth = require('@dav-nazaryan/brainstorm-task');

auth.init('admin', {
  mongoUrl: 'mongodb://localhost:27017/auth-db',
}).then((authInstance) => {
  // use auth instance methods
});

Usage example along with express and mongoose

const auth = require('@dav-nazaryan/brainstorm-task')

const mongoose = require('mongoose');
const express = require('express');
const app = express();

const dependencies = [
  mongoose.connect('mongodb://localhost:27017/auth-demo', {
    useNewUrlParser: true,
    useCreateIndex: true,
    useFindAndModify: false,
  }),
  auth.init('user', {
    mongoUrl: 'mongodb://localhost:27017/auth-user',
  }),
];

Promise.all(dependencies).then(() => {
  app.listen(3000, () => {
    console.log('Example app listening on port 3000!');
  });
});

Init instance on start and get it inside other file

server.js

const auth = require('@dav-nazaryan/brainstorm-task');

const express = require('express');
const app = express();

auth.init('user', {
  mongoUrl: 'mongodb://localhost:27017/auth-db',
}).then((authInstance) => {
  app.listen(3000, () => {
    console.log('Example app listening on port 3000!');
  });
});

user.router.js

const express = require('express');
const router = express.Router();

const auth = require('@dav-nazaryan/brainstorm-task');
const userAuth = auth.get('user');

router.post('/register', async (req, res) => {
  const user = await userAuth.register(req.body.login, req.body.password);
  res.status(201).send(user);
});

Usage without getting an instance

server.js

const auth = require('@dav-nazaryan/brainstorm-task')

const mongoose = require('mongoose');
const express = require('express');
const app = express();

const dependencies = [
  mongoose.connect('mongodb://localhost:27017/auth-demo', {
    useNewUrlParser: true,
    useCreateIndex: true,
    useFindAndModify: false,
  }),
  // you can init multiple instances
  auth.init('user', {
    mongoUrl: 'mongodb://localhost:27017/auth-admin',
  }),
  auth.init('user', {
      mongoUrl: 'mongodb://localhost:27017/auth-user',
    }),
];

Promise.all(dependencies).then(() => {
  app.listen(3000, () => {
    console.log('Example app listening on port 3000!');
  });
});

admin.router.js

const express = require('express');
const router = express.Router();

const auth = require('@dav-nazaryan/brainstorm-task');

router.post('/update', async (req, res, next) => {
  try {
    auth.bearer('admin', req.headers.authorization);
    next();
  } catch (e) {
    next(e);
  }
});

API

Main module

Auth

Kind: global constant

init(id, options) ⇒ Promise

Create new auth instance and save it inside module scope

Kind: global function

ParamTypeDescription
idstringunique id of auth instance
optionsobjectnew instance configs

get(id) ⇒ Auth

Get instance from instances scope

Kind: global function Returns: Auth - - auth object instance

ParamTypeDescription
idstringunique id of auth instance

callInstanceMethod(id, method, data)

Call method of auth instance without getting it

Kind: global function

ParamTypeDescription
idstringinstance id
methodstringmethod to call
dataobjectdata that need to be provided ot method

activate(id, userId)

Activate user in mongo for current auth instance

Kind: global function

ParamType
idstring
userIdstring

deactivate(id, userId)

Deactivate user in mongo for current auth instance

Kind: global function

ParamType
idstring
userIdstring

register(id, login, password, options)

Register new user in mongo for current auth instance

Kind: global function

ParamTypeDefaultDescription
idstringinstance id
loginstring
passwordstring
optionsobjectoptions object
options.loginbooleanfalselog in newly created user and return his token pair, user must be activate for this option
options.activebooleanactivate newly created user
options.getUserbooleanfalsereturn new user object, options.login must be false

getUser(id, login, password)

Get user object from mongo for current auth instance

Kind: global function

ParamTypeDescription
idstringinstance id
loginstring
passwordstring

logIn(id, login, password) ⇒ object

Login registered user for current auth instance

Kind: global function Returns: object - - access and refresh tokens pair

ParamTypeDescription
idstringinstance id
loginstring
passwordstring

bearer(id, token)

Check user access token for current auth instance

Kind: global function

ParamTypeDescription
idstringinstance id
tokenstringjwt access token

refresh(id, accessToken, refreshToken)

Check user access token for current auth instance

Kind: global function

ParamTypeDescription
idstringinstance id
accessTokenstringjwt access token
refreshTokenstringone time refresh token

logOut(id, userId, options, login, password)

Cut the users sessions via removing token/all tokens for current auth instance

Kind: global function

ParamTypeDefaultDescription
idstringinstance id
userIdstringuser mongo objectId
optionsobjectoptions object
options.authByCredentialsbooleanfalseuse user_id or get it via checking credentials
options.hardbooleanfalsecut all user sessions (logout from all devices)
options.refreshTokenbooleanfalseuse user_id or get it via checking credentials
loginstring
passwordstring

update(id, userId, login, password)

Update user login or password

Kind: global function

ParamTypeDescription
idstringinstance id
userIdstringuser mongo objectId
loginstring
passwordstring

Auth Instance

Kind: global class

new Auth(options)

Returns: auth - - new auth object

ParamTypeDescription
optionsobjectoptions object
options.mongoUrlobjectmongo connection url
options.collections.userobjectuser collection name
options.collections.tokenobjecttoken collection name

auth.connect(enforcer)

Connect Auth object to mongo

Kind: instance method of Auth

ParamTypeDescription
enforcersymbolto avoid this method calling out of module

auth.initModels(enforcer)

Add models to instance, it can be done after instance db connect

Kind: instance method of Auth

ParamTypeDescription
enforcersymbolto avoid this method calling out of module

auth.validateCredentials(login, password)

Validate login and password

Kind: instance method of Auth

ParamType
loginstring
passwordstring

auth.register(login, password, options)

Register new user in mongo for current auth instance

Kind: instance method of Auth

ParamTypeDefaultDescription
loginstring
passwordstring
optionsobjectoptions object
options.loginobjectfalselog in newly created user and return his token pair, user must be activate for this option
options.activeobjectfalseactivate newly created user
options.getUserobjectfalsereturn new user object, options.login must be false

auth.getUser(login, password) ⇒ object

Check user auth credentials without logging him in

Kind: instance method of Auth Returns: object - - user object

ParamType
loginstring
passwordstring

auth.logIn(login, password) ⇒ object

Login registered user

Kind: instance method of Auth Returns: object - - access and refresh tokens pair

ParamType
loginstring
passwordstring

auth.activate(userId)

Activate registered user

Kind: instance method of Auth

ParamType
userIdstring

auth.deactivate(userId)

Deactivate registered user

Kind: instance method of Auth

ParamType
userIdstring

auth.bearer(token)

Check user access token

Kind: instance method of Auth

ParamTypeDescription
tokenstringjwt access token

auth.refresh(accessToken, refreshToken) ⇒ object

Generate new refresh and access tokens pair and update document

Kind: instance method of Auth Returns: object - - access and refresh tokens pair

ParamTypeDescription
accessTokenstringjwt access token
refreshTokenstringone time refresh token

auth.logOut(userId, options, login, password)

The logOut method will mostly be used by admins cut the users session, that's why I provide credentials check as an option

Kind: instance method of Auth

ParamTypeDefaultDescription
userIdstringuser mongo objectId
optionsobjectoptions object
options.authByCredentialsbooleanfalseuse user_id or get it via checking credentials
options.hardbooleanfalsecut all user sessions (logout from all devices)
options.refreshTokenbooleanfalseuse user_id or get it via checking credentials
loginstring
passwordstring

auth.update(userId, login, password)

Update user login or password

Kind: instance method of Auth

ParamTypeDescription
userIdstringuser mongo objectId
loginstring
passwordstring