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

apollo-accounts-password-server

v0.3.0-beta.26-1

Published

Fullstack accounts for Apollo: server side

Downloads

2

Readme

Apollo Accounts Password—Server npm version

Server side of Apollo Accounts Password, a full-stack JS accounts system for Apollo and MongoDB.

Usage

npm install apollo-accounts-password-server

import { ApolloServer, makeExecutableSchema } from 'apollo-server'
import { merge } from 'lodash'
import mongodb from 'mongodb'

import {
  createApolloAccounts,
  accountsContext
} from 'apollo-accounts-password-server'

const start = async () => {
  const client = await mongodb.MongoClient.connect(process.env.MONGO_URL)
  const db = client.db()

  const accounts = createApolloAccounts({
    db,
    tokenSecret: process.env.TOKEN_SECRET,
    siteUrl:
      process.env.NODE_ENV === 'production'
        ? 'https://myapp.com'
        : 'http://localhost:3000'
  })

  const typeDefs = `
  type PrivateType @auth {
    field: String
  }

  type Query {
    publicField: String
    privateField: String @auth
    privateType: PrivateType
    adminField: String @auth
  }

  type Mutation {
    _: String 
  }

  extend type User {
    firstName: String
  }
  `

  const resolvers = {
    Query: {
      publicField: () => 'public',
      privateField: () => 'private',
      privateType: () => ({
        field: () => 'private'
      }),
      adminField: (root, args, context) => {
        if (context.user.isAdmin) {
          return 'admin field'
        }
      }
    },
    User: {
      firstName: () => 'first'
    }
  }

  const schema = makeExecutableSchema({
    typeDefs: [typeDefs, accounts.typeDefs],
    resolvers: merge(accounts.resolvers, resolvers),
    schemaDirectives: {
      ...accounts.schemaDirectives
    }
  })

  const server = new ApolloServer({
    schema,
    context: ({ req }) => accountsContext(req)
  })

  server.listen(4000).then(({ url }) => {
    console.log(`🚀  Server ready at ${url}`)
  })
}

start()

createApolloAccounts() generates typedefs, resolvers, and directives for us to use in our schema. It creates a User type that we can extend and an @auth directive for fields and types that returns an error if the client is not logged in. It also creates resolvers and types used by apollo-accounts-password-client.

Demo

See flyblackbird/apollo-accounts

API

createApolloAccounts

createApolloAccounts(options)

options format. Detailed format:

  • options.db: (Required) the database connection. Using the mongodb module:
const client = await mongodb.MongoClient.connect(process.env.MONGO_URL)

// uses the db listed at the end of the MONGO_URL
const db = client.db() 
// or:
const db = client.db('my-db-name')

Using Mongoose:

await mongoose.connect(
  'mongodb://localhost:27017/apollo-accounts-demo',
  { useNewUrlParser: true }
)
const db = mongoose.connection
  • options.tokenSecret: (Required) a secret the library uses for token creation. You can generate a secret with openssl rand -base64 30.
  • options.siteUrl: (Required) eg 'http://localhost:3000' or 'https://myapp.com'
  • options.sendMail: (Required) a function that sends an email. For instance:
import nodemailer from 'nodemailer'
let transporter = nodemailer.createTransport('smtps://username:[email protected]/?pool=true')

...
sendMail: ({ from, subject, to, text, html }) => {
  transporter.sendMail({
    from,
    to,
    subject,
    text,
    html
  }, (err, info) => {
    console.log(info)
  })
}
  • options.emailTemplates: templates for auth emails. Format. Defaults:
{
  from: 'accounts-js <[email protected]>',
  verifyEmail: {
    subject: () => 'Verify your account email',
    text: (user, url) =>
      `To verify your account email please click on this link: ${url}`,
    html: (user, url) =>
      `To verify your account email please <a href="${url}">click here</a>.`,
  },
  resetPassword: {
    subject: () => 'Reset your password',
    text: (user, url) => `To reset your password please click on this link: ${url}`,
    html: (user, url) => `To reset your password please <a href="${url}">click here</a>.`,
  }
}
  • options.userObjectSanitizer: a function that, given a user object from the database, returns a filtered user object that will be sent to the client. The default only removes authentication data (user.services). Here is an example that removes the username field:
userObjectSanitizer: (user, omit, pick) => omit(user, ['username'])
  • options.tokenConfigs: expiration for the access and refresh tokens. The default values are:
tokenConfigs: {
  accessToken: {
    expiresIn: '90m',
  },
  refreshToken: {
    expiresIn: '90d',
  },
}

The refresh token expiration matches Meteor's default 90-day login token expiration.

Expiration format matches jwt.sign's options.expiresIn.

  • options.impersonationAuthorize: a function that, given the current user and the target of impersonation, returns whether to allow impersonation. For example:
impersonationAuthorize: (currentUser, targetUser) => currentUser.isAdmin

accountsContext

Sets the request context so that we can access context.user in our resolvers:

const server = new ApolloServer({
  schema,
  context: ({ req }) => accountsContext(req)
})

onLogin

onLogin(cb)

cb is called each time a user successfully logs in via login(). It's given an object with information about the request, including a user property.

cb is not called when an access token is refreshed.

onCreateUser

onCreateUser(cb)

cb is called after a user is successfully created (by a call to createUser()). It's given the user record that was saved in the database.

Eject

This package is like Apollo Boost—if at some point you need more configuration options than this package exposes, you can eject by directly installing the below accounts-js packages and configuring them yourself:

npm install @accounts/server @accounts/password @accounts/graphql-api @accounts/database-manager @accounts/mongo

See index.js


Credits