Ultimate Authentication using GraphQL Nexus

This tutorial requires that you have a knowledge of GraphQL queries, mutation and context.

This tutorial covers the following:

  1. Signup User
  2. Account Activation
  3. Login User
  4. Password Reset
  5. Facebook Login
  6. Google Login
  7. Admin Role (Deleting Users, Get All Users)
  8. Get Current User

These are the following packages required for authentication and authorization:

  1. bcrypt: This package use to hash our passwords
  2. jsonwebtoken: This package use encrypt the payload, returns the token which use for authentication and we can also configure how much time this token last.
  3. node-fetch: This package use to make a fetch request
  4. nodemailer: This package use to send a email
  5. graphql-middleware: This package use to apply middlewares to manage additional functionality on multiple resolvers.
  6. graphql-shield: This package helps to create a permission middleware for your application.

Install these packages

yarn add bcrypt jsonwebtoken node-fetch nodemailer graphql-middleware graphql-shield google-auth-library

In this user schema

  1. id and email is unique
  2. Password is not required for every user like facebook and google.
  3. ResetPasswordToken is used to check the token is not expired when resetting password
  4. isAdmin is set to false by default
type User {
  id: ID! @id
  name: String!
  email: String! @unique
  password: String
  isAdmin: Boolean @default(value: false)
  resetPasswordToken: String @default(value: "")
  createdAt: DateTime! @createdAt
  updatedAt: DateTime! @updatedAt
}

Define the context in the GraphQL Server

We have to create a context type for it

import { Prisma } from "./generated/prisma-client";

export interface Context {
  prisma: Prisma;
  request: {
    request: {
      headers: {
        authorization: string;
      };
    };
    connection: {
      context: {
        Authorization: string;
      };
    };
  };
}

After defining the context type set global context to prisma and request so we can use prisma methods and request object for getting authorization token.

#web-development #javascript #programming #graphql #prisma

Ultimate Authentication using GraphQL Nexus