npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

mongauth

v1.0.2

Published

Mongauth is a simple library to manage accounts in mongodb. Add accounts to the database, find an account, delete an account and update an account field. Mongauth also provides a simple way to encrypt some account fields and generate tokens, ids...

Downloads

5

Readme

Mongauth

Mongauth is a simple library to manage accounts in mongodb. Add accounts to the database, find an account, delete an account and update an account field. Mongauth also provides a simple way to encrypt some account fields and generate tokens, ids...

  1. Create a system
  2. Add the functions you need ( add, find, delete, update )

Features

  • Infinite possibilites and customizations
  • Simple and easy to use
  • Body checking
  • Lots of error messages
  • No need to use mongodb syntax, just use the functions
  • Check if a field is unique ( like email )

Installation

# Using npm
npm install mongauth

# Using yarn
yarn add mongauth

Importing

// Using ES6 imports
import mongauth from 'mongauth';

// Using CommonJS imports
const mongauth = require('mongauth/cjs');

You can destructure the module to get the functions you need:

// Using ES6 imports
import { System, encrypt, generateToken, generateId } from 'mongauth';

// Using CommonJS imports
const { System, encrypt, generateToken, generateId } = require('mongauth/cjs');

Usage

Creating a system

const system = new System('mongodb://localhost:27017', {
  db: 'lists',
  collection: 'accounts',
});

Adding an account, using express

import express from 'express'
import mongauth from 'mongauth'

// using commonjs
const express = require('express')
const mongauth = require('mongauth/cjs')
// ---

const app = express()
app.use(express.json())

// Create system

app.post('/auth/createAccount', (req, res) => {
  mySystem.add(req, res, {
    bodySchema: { // This is what the request should receive
      email: 'string',
      password: 'string',
      username: 'string',
    },
    accountSchema: body => ({ // This is what the account will look like in the database
      password: mongauth.encrypt(body.password),
      username: body.username,
      token: mongauth.generateToken(),
      id: mongauth.generateId(),
      data: {
        email: body.email,
      },
      player: {
        trophies: 0,
        level: 1,
      }
    }),
    onError: (err) => { // Send the error if an error in returned
      res.json(err)
    },
    onSuccess: (user, add) => {
      if(user.username === 'admin') { // You can add other checks here
        return res.status(400).json({ error: 'Username is not allowed' })
      }
      add(user) // The final function to add the user to the database
      res.json({
        message: 'Account created',
      })
    },
    notTwice: body => ([ // This is where you can check if a field is unique
      { 'data.email': body.email }, // data.email is the path to the field in the db.
      { 'username': body.username }
    ])
  })
})

Mongauth will automatically return an error if the request body is not valid, if the email or username is already taken etc...

Finding an account, using express

app.post('/auth/findAccount', (req, res) => {
  mySystem.find(req, res, {
    bodySchema: {
      email: 'string',
      password: 'string',
    },
    conditions: (body, headers) => ([
      { 'data.email': body.email },
      { password: mongauth.encrypt(body.password) }
    ]),
    onError: (err) => {
      res.json(err)
    },
    onSuccess: user => { // If the user is not found, the function will not be called and an error will be returned
      res.json({
        message: 'Account found',
        user: user,
      })
    },
  })
})

Deleting an account, using express

app.post('/auth/deleteAccount', (req, res) => {
  system.delete(req, res, {
    bodySchema: {
      email: 'string',
      password: 'string'
    },
    conditions: (body, headers) => ([
      { 'member.email': body.email },
      { password: mongauth.encrypt(body.password) }
    ]),
    onError: (err) => {
      res.json(err)
    },
    onSuccess: (user, remove) => {
      res.json({
        "user": user,
        "deleted": true
      })
      remove(user)
    }
  })
})

Updating an account, using express

app.post('/auth/changeEmail', (req, res) => {
  system.change(req, res, {
    bodySchema: {
      newEmail: 'string'
    }, // imagine that the user is logged in and that the token is in the headers
    path: 'member.email', // the path to the field you want to change in the db
    newValue: body => body.newEmail,
    conditions: (body, headers) => ([ // conditions to find the user
      { token: headers.authorization }
    ]),
    onError: (err) => {
      res.json(err)
    },
    onSuccess: (user, change) => {
      change(user)
      res.json({
        "user": user,
        "message": "changed username"
      })
    }
  })
})

Advanced usage

Complex bodySchema

bodySchema: {
  email: new RegExp('^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$'), // You can use regex
  password: new mongauth.ComplexString({
    minLength: 4,
  }),
  username: new mongauth.ComplexString({
    minLength: 8,
    maxLength: 20,
    charsWhiteList: {
      templates: ['lowercase', 'uppercase'], // 'numbers', 'symbols', 'soft-symbols', 'space', 'all'
      customs: '.-_'
    }
  }),
}