<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Muhammad Ali on Medium]]></title>
        <description><![CDATA[Stories by Muhammad Ali on Medium]]></description>
        <link>https://medium.com/@muhammadali_48256?source=rss-3602b3d2d274------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*8-GRTvT4mVX9uc_e</url>
            <title>Stories by Muhammad Ali on Medium</title>
            <link>https://medium.com/@muhammadali_48256?source=rss-3602b3d2d274------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 11:39:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@muhammadali_48256/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Ultimate Authentication using GraphQL Nexus]]></title>
            <link>https://javascript.plainenglish.io/ultimate-authentication-using-graphql-nexus-ec01f79dff2c?source=rss-3602b3d2d274------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec01f79dff2c</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[prisma]]></category>
            <dc:creator><![CDATA[Muhammad Ali]]></dc:creator>
            <pubDate>Thu, 27 Aug 2020 00:44:46 GMT</pubDate>
            <atom:updated>2020-09-15T13:41:02.967Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*Ggf4CoLksFbvWcjXMGzQsg.png" /></figure><h4>How to make the ultimate authentication boilerplate for your application. We will be using graphql-nexus and prisma as our ORM.</h4><p>This tutorial requires that you have a knowledge of GraphQL queries, mutation and context.</p><h4>This tutorial covers the following:</h4><ol><li>Signup User</li><li>Account Activation</li><li>Login User</li><li>Password Reset</li><li>Facebook Login</li><li>Google Login</li><li>Admin Role (Deleting Users, Get All Users)</li><li>Get Current User</li></ol><h4>These are the following packages required for authentication and authorization:</h4><ol><li>bcrypt: This package use to hash our passwords</li><li>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.</li><li>node-fetch: This package use to make a fetch request</li><li>nodemailer: This package use to send a email</li><li>graphql-middleware: This package use to apply middlewares to manage additional functionality on multiple resolvers.</li><li>graphql-shield: This package helps to create a permission middleware for your application.</li></ol><h4><strong>Install these packages</strong></h4><pre>yarn add bcrypt jsonwebtoken node-fetch nodemailer graphql-middleware graphql-shield google-auth-library</pre><h4><strong>In this user schema</strong></h4><ol><li>id and email is unique</li><li>Password is not required for every user like facebook and google.</li><li>ResetPasswordToken is used to check the token is not expired when resetting password</li><li>isAdmin is set to false by default</li></ol><pre>type User {<br>  id: ID! @id<br>  name: String!<br>  email: String! @unique<br>  password: String<br>  isAdmin: Boolean @default(value: false)<br>  resetPasswordToken: String @default(value: &quot;&quot;)<br>  createdAt: DateTime! @createdAt<br>  updatedAt: DateTime! @updatedAt<br>}<br></pre><h4><strong>Define the context in the GraphQL Server</strong></h4><p>We have to create a context type for it</p><pre>import { Prisma } from &quot;./generated/prisma-client&quot;;<br><br>export interface Context {<br>  prisma: Prisma;<br>  request: {<br>    request: {<br>      headers: {<br>        authorization: string;<br>      };<br>    };<br>    connection: {<br>      context: {<br>        Authorization: string;<br>      };<br>    };<br>  };<br>}</pre><p>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.</p><pre>const server = new GraphQLServer({<br>  context: (req) =&gt; {<br>    return {<br>      request: req,<br>      prisma,<br>    };<br>  },<br>});</pre><h4><strong>Creating the Message Payload and Signup Input for Signup</strong></h4><p>To define the mutation we need to provide the resolver return payload and the argument type ,For signup we have to define the messagePayload as our payload and signupInput as our input argument.</p><pre>import { inputObjectType, objectType } from &quot;nexus&quot;;<br>export const signupInput = inputObjectType({<br>  name: &quot;signupInput&quot;,<br>  definition(t) {<br>    t.string(&quot;name&quot;, { nullable: false });<br>    t.string(&quot;email&quot;, { nullable: false });<br>    t.string(&quot;password&quot;, { nullable: false });<br>  },<br>});<br>export const messagePayload = objectType({<br>  name: &quot;MessagePayload&quot;,<br>  definition(t) {<br>    t.string(&quot;message&quot;, { nullable: false });<br>  },<br>});</pre><p>As the message payload returns only a successful message in string and signpInput takes 3 arguments which provided by the user name, email and password.</p><h4><strong>Creating a email service using nodemailer</strong></h4><p>You can define any provider you want, I use gmail as a provider for sending email. It just requires email, password for a gmail account and provider name for creating a transport layer.</p><p>If you use gmail enable less secure apps in your gmail settings. For activationEmail it requires a token and a html, so it can be look good when users can get email for activation. ResetPassword is also requires the same but it uses for forgot password functionality. SendEmail is used for actually send an email.</p><pre>import { createTransport } from &quot;nodemailer&quot;;<br>type Token = string;<br><br>const transport = createTransport({<br>  service: &quot;gmail&quot;,<br>  auth: {<br>    user: process.env.GMAIL_USER,<br>    pass: process.env.GMAIL_PASSWORD,<br>  },<br>});<br><br>export default {<br>  activationEmail(token: Token) {<br>    // Compose email<br>    const html = `Hi there,<br>      &lt;br/&gt;<br>      Thank you for registering!<br>      &lt;br/&gt;&lt;br/&gt;<br>      Please verify your email by clicking the following link:<br>      &lt;br/&gt;<br>      On the following page:<br>      &lt;a target=&quot;_blank&quot; href=&quot;${<br>        process.env.CLIENT_URL<br>      }/auth/activate/${token}&quot;&gt;${<br>      process.env.CLIENT_URL<br>    }/auth/activate/${token}&lt;/a&gt;<br>      &lt;br/&gt;&lt;br/&gt;<br>      Have a pleasant day.`;<br>    return html;<br>  },<br>  resetPassword(token: Token) {<br>    const html = `<br>    &lt;h1&gt;Please use the following link to reset your password&lt;/h1&gt;<br>    &lt;a target=&quot;_blank&quot; href=&quot;${<br>      process.env.CLIENT_URL<br>    }/auth/password/reset/${token}&quot;&gt;${<br>      process.env.CLIENT_URL<br>    }/auth/password/reset/${token}&lt;/a&gt;<br>    `;<br>    return html;<br>  },<br>  sendEmail(from: string, to: string, subject: string, html: string) {<br>    return new Promise((resolve, reject) =&gt; {<br>      transport.sendMail({ from, subject, to, html }, (err, info) =&gt; {<br>        if (err) reject(err);<br>        resolve(info);<br>      });<br>    });<br>  },<br>};</pre><h4><strong>Creating the generateHashPassword utility function</strong></h4><p>We have to import hash from bcrypt, the generatHashPassword requires one arg password, first it check for 8 characters validation if it is not valid it throws an error and if it is valid it hashed the password and return</p><pre>import { hash } from &quot;bcrypt&quot;;<br>const generateHashPassword = (password: String) =&gt; {<br>    if (password.length &lt; 8) {<br>        throw new Error(&quot;Password should be greater than 8 characters&quot;);<br>    }<br>    return hash(password, 10);<br>};<br><br>export default generateHashPassword;</pre><h4><strong>Creating the Signup and Account Activation Mutations</strong></h4><p>First, we have to check that if the email passed by the user is already associated with an account, if it is we have to throw an error, if it is not we have to generate the hash password. After this we have to create a jwt token. It requires a payload, a secret key and time to expire. We pass email, name and hashPassword in the payload. We give token 10 minutes of time to expire. We have to send a account activation mail for this we used our sendEmail service which we create before and in the last we return the message payload.</p><pre>t.field(&quot;signup&quot;, {<br>      type: &quot;MessagePayload&quot;,<br>      nullable: false,<br>      args: {<br>        signupInput: arg({ type: &quot;signupInput&quot;, required: true }),<br>      },<br>      resolve: async (_, { signupInput: { name, email, password } }, ctx) =&gt; {<br>        try {<br>          const isUserExist = await ctx.prisma.$exists.user({ email });<br>          if (isUserExist) {<br>            throw new Error(&quot;Email is already associated with another user&quot;);<br>          }<br>          const hashPassword = await generateHashPassword(password);<br>          const token = sign(<br>            {<br>              name,<br>              email,<br>              password: hashPassword,<br>            },<br>            process.env.JWT_ACCOUNT_ACTIVATION,<br>            {<br>              expiresIn: &quot;10m&quot;,<br>            }<br>          );<br>          const html = mailService.activationEmail(token);<br>          await mailService.sendEmail(<br>            process.env.EMAIL_FROM,<br>            email,<br>            &quot;Account activation&quot;,<br>            html<br>          );<br>          return {<br>            message: `Email has been sent to ${email}. Follow the instruction to activate your account`,<br>          };<br>        } catch (error) {<br>          throw new Error(error.message);<br>        }<br>      },<br>    });</pre><p>After sending email successfully to users its time to activate a user, accountActivation also have a messagePayload resolver return type and it requires token as an argument. First we used verify jwt method to check if the token is not expired, if it is not we decode name, email and hashPassword to create a user successfully and return the message payload.</p><pre>t.field(&quot;accountActivation&quot;, {<br>      type: &quot;MessagePayload&quot;,<br>      nullable: false,<br>      args: {<br>        token: stringArg({ required: true }),<br>      },<br>      resolve: async (_, { token }, ctx) =&gt; {<br>        try {<br>          if (!token) {<br>            throw new Error(&quot;No token for activation&quot;);<br>          }<br>          const decoded = verify(token, process.env.JWT_ACCOUNT_ACTIVATION);<br>          const { name, email, password } = decode(token) as {<br>            name: string;<br>            email: string;<br>            password: string;<br>          };<br>          await ctx.prisma.createUser({<br>            name,<br>            password,<br>            email,<br>          });<br>          return {<br>            message: &quot;Signup success. Please signin.&quot;,<br>          };<br>        } catch (error) {<br>          throw new Error(error.message);<br>        }<br>      },<br>    });</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZGF4UZMRkS2G1HZzTtSoJw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5IGqQjr3-OOV8eAAnTHMLw.png" /></figure><h4><strong>Creating the LoginInput, AuthPayload for login mutation</strong></h4><p>We have to create loginInput which defines email and password in string. Next we create an AuthPayload for resolver return type. AuthPayload returns a token and a user. We also define User type to only return these fields.</p><pre>export const User = prismaObjectType&lt;&quot;User&quot;&gt;({<br>  name: &quot;User&quot;,<br>  definition(t) {<br>    t.prismaFields([&quot;id&quot;, &quot;email&quot;, &quot;name&quot;, &quot;isAdmin&quot;]);<br>  },<br>});</pre><pre>export const loginInput = inputObjectType({<br>  name: &quot;loginInput&quot;,<br>  definition(t) {<br>    t.string(&quot;email&quot;, { nullable: false });<br>    t.string(&quot;password&quot;, { nullable: false });<br>  },<br>});</pre><pre>export const AuthPayload = objectType({<br>  name: &quot;AuthPayload&quot;,<br>  definition(t) {<br>    t.string(&quot;token&quot;, { nullable: false });<br>    t.field(&quot;user&quot;, {<br>      type: &quot;User&quot;,<br>      nullable: false,<br>    });<br>  },<br>});</pre><h4><strong>Create a generateToken utility function</strong></h4><p>We have to provide an userId as a payload, a secret key and a expire time for generating a token.</p><pre>import { sign } from &quot;jsonwebtoken&quot;;<br>const generateToken = (userId: String) =&gt; {<br>    const token = sign(<br>        {<br>            userId,<br>        },<br>        process.env.JWT_SECRET,<br>        {<br>            expiresIn: &quot;7d&quot;,<br>        }<br>    );<br>    return token;<br>};<br><br>export default generateToken;</pre><h4><strong>Creating login mutation</strong></h4><p>We have to check that if the provided email is associated with an account, then we compare the hashPassword with the provided password. We check the validations if failed throw an error if not returns the AuthPayload.</p><pre>t.field(&quot;login&quot;, {<br>      type: &quot;AuthPayload&quot;,<br>      nullable: false,<br>      args: {<br>        loginInput: arg({ type: &quot;loginInput&quot;, required: true }),<br>      },<br>      resolve: async (_, { loginInput: { email, password } }, ctx) =&gt; {<br>        const user = await ctx.prisma.user({<br>          email,<br>        });<br>        if (!user) {<br>          throw new Error(&quot;User not exist&quot;);<br>        }<br>        const isPasswordMatch = await compare(password, user.password);<br>        if (!isPasswordMatch) {<br>          throw new Error(&quot;Password not correct&quot;);<br>        }<br>        return {<br>          user,<br>          token: generateToken(user.id),<br>        };<br>      },<br>    });</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0OOcnHGaUy9YRdKal7PiQQ.png" /></figure><h4><strong>Creating a forgot Password Mutation</strong></h4><p>It also returns a messagePayload and requires a user email as an input argument. We have to check the email provided by the user is associated with an account or not, then we generate a token with a user id and name for payload. This token is last for 10 minutes. After this we send an email to the user and update the resetPasswordToken to the generated Token. In the last we return the messagePayload.</p><pre>t.field(&quot;forgotPassword&quot;, {<br>      type: &quot;MessagePayload&quot;,<br>      nullable: false,<br>      args: {<br>        email: stringArg({ required: true }),<br>      },<br>      resolve: async (_, { email }, ctx) =&gt; {<br>        try {<br>          const user = await ctx.prisma.user({<br>            email,<br>          });<br>          if (!user) {<br>            throw new Error(&quot;User not exist&quot;);<br>          }<br>          const token = sign(<br>            {<br>              _id: user.id,<br>              name: user.name,<br>            },<br>            process.env.JWT_RESET_PASSWORD,<br>            {<br>              expiresIn: &quot;10m&quot;,<br>            }<br>          );<br>          const html = mailService.resetPassword(token);<br>          await ctx.prisma.updateUser({<br>            where: {<br>              id: user.id,<br>            },<br>            data: {<br>              resetPasswordToken: token,<br>            },<br>          });<br>          await mailService.sendEmail(<br>            process.env.EMAIL_FROM,<br>            email,<br>            &quot;Password Reset&quot;,<br>            html<br>          );<br>          return {<br>            message: `Email has been sent to ${email}. Follow the instruction to reset your password`,<br>          };<br>        } catch (error) {<br>          throw new Error(error.message);<br>        }<br>      },<br>    });</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7HmfcJcRTBkQVDYNgPtxhA.png" /></figure><h4><strong>Creating a ResetPassword Input and Mutation</strong></h4><p>ResetPassword input takes two fields resetPasswordToken and newPassword as a string type.</p><pre>export const resetPasswordInput = inputObjectType({<br>  name: &quot;resetPasswordInput&quot;,<br>  definition(t) {<br>    t.string(&quot;resetPasswordToken&quot;, { nullable: false });<br>    t.string(&quot;newPassword&quot;, { nullable: false });<br>  },<br>});</pre><p>ResetPassword mutation returns the message payload and requires the resetPassword input as an argument. First we have to check resetPasswordToken provided by the user is associated with a user or not, if not it throws an error and if exist it returns a user. We hash the new password and update the user password and resetPasswordToken to empty string. In last we returns a message payload.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BAjbUYkBGR1RwACvjZ8A7g.png" /></figure><h4><strong>Create a Facebook login input and mutation</strong></h4><p>Facebook login input defines accessToken and userId as a string type. Mutation returns AuthPayload as a resolver return type. AccessToken and userId for testing purpose can be get from <a href="https://developers.facebook.com/tools/explorer/">Graph api explorer</a>, before it you have to create an app on <a href="https://developers.facebook.com/">facebook developer console</a></p><pre>export const facebookLoginInput = inputObjectType({<br>  name: &quot;facebookLoginInput&quot;,<br>  definition(t) {<br>    t.string(&quot;userId&quot;, { nullable: false });<br>    t.string(&quot;accessToken&quot;, { nullable: false });<br>  },<br>});</pre><p>We have to pass userId and accessToken to the graph api and fetch data from it. Name and email should return from the response, we have to first check that email is already associated with an account or not. If it already exist return the AuthPayload and if not we create a new user with that email and password and return the AuthPayload.</p><pre>t.field(&quot;facebookLogin&quot;, {<br>      type: &quot;AuthPayload&quot;,<br>      nullable: false,<br>      args: {<br>        facebookLoginInput: arg({ type: &quot;facebookLoginInput&quot;, required: true }),<br>      },<br>      resolve: async (<br>        _,<br>        { facebookLoginInput: { userId, accessToken } },<br>        ctx<br>      ) =&gt; {<br>        try {<br>          const url = `https://graph.facebook.com/v2.11/${userId}/?fields=id,name,email&amp;access_token=${accessToken}`;<br>          const response = await fetch(url, {<br>            method: &quot;GET&quot;,<br>          });<br>          const data = (await response.json()) as {<br>            name: string;<br>            email: string;<br>            // error: {<br>            //   message: string;<br>            // };<br>          };<br>          if (response.status !== 200) {<br>            throw new Error(&quot;Something went wrong&quot;);<br>          }<br>          const { email, name } = data;<br>          const user = await ctx.prisma.user({<br>            email,<br>          });<br>          if (!user) {<br>            const newUser = await ctx.prisma.createUser({<br>              name,<br>              email,<br>            });<br>            return {<br>              user: newUser,<br>              token: generateToken(newUser.id),<br>            };<br>          }<br>          return {<br>            user,<br>            token: generateToken(user.id),<br>          };<br>        } catch (error) {<br>          throw new Error(error.message);<br>        }<br>      },<br>    });</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HyGxUP883HbJIrtNVhS4Yg.png" /></figure><h4><strong>Create a Google login input and mutation</strong></h4><p>For<strong> </strong>google login we use google-auth-library npm package. It requires a client id for setup. Get client id from google cloud platform is simple follow this <a href="https://support.google.com/cloud/answer/6158849?hl=en">https://support.google.com/cloud/answer/6158849?hl=en</a></p><pre>import { OAuth2Client } from &quot;google-auth-library&quot;;<br>const client = new OAuth2Client(process.env.GOOGLE_CLIENT_ID);</pre><p>We define idToken as a string for google login input.</p><pre>export const googleLoginInput = inputObjectType({<br>  name: &quot;googleLoginInput&quot;,<br>  definition(t) {<br>    t.string(&quot;idToken&quot;, { nullable: false });<br>  },<br>});</pre><p>Google login mutation also returns a AuthPayload and it’s the same as facebook login mutation.</p><pre>t.field(&quot;googleLogin&quot;, {<br>      type: &quot;AuthPayload&quot;,<br>      nullable: false,<br>      args: {<br>        googleLoginInput: arg({ type: &quot;googleLoginInput&quot;, required: true }),<br>      },<br>      resolve: async (_, { googleLoginInput: { idToken } }, ctx) =&gt; {<br>        try {<br>          const { email_verified, email, name } = (await client.verifyIdToken({<br>            idToken,<br>            audience: process.env.GOOGLE_CLIENT_ID,<br>          })).getPayload();<br>          if (email_verified) {<br>            const user = await ctx.prisma.user({<br>              email,<br>            });<br>            if (!user) {<br>              const newUser = await ctx.prisma.createUser({<br>                name,<br>                email,<br>              });<br>              return {<br>                user: newUser,<br>                token: generateToken(newUser.id),<br>              };<br>            }<br>            return {<br>              user,<br>              token: generateToken(user.id),<br>            };<br>          }<br>        } catch (error) {<br>          throw new Error(error.message);<br>        }<br>      },<br>    });</pre><p>As google not provide test users like facebook, you have to setup a client for it If your client is build on react use <a href="https://www.npmjs.com/package/react-google-login">react-google-login</a> as it returns idToken in response.</p><h4><strong>Create a getUserId util and Current User query</strong></h4><p>For getUserId utility it only requires the context. Get the authorization token from the request headers and check if its valid or not using jwt verify method may be it expires if it is more then 7 days because we set the token should last for 7 days when login. Uncomment these 3 lines if your application have subscription.</p><pre>import { verify } from &quot;jsonwebtoken&quot;;<br>import { Context } from &quot;../types&quot;;<br>interface Token {<br>  userId: string;<br>}<br>export const getUserId = (context: Context) =&gt; {<br>  // const authTokenWithBarer = context.request.request<br>  //   ? context.request.request.headers.authorization<br>  //   : context.request.connection.context.Authorization;<br>  const authTokenWithBarer = context.request.request.headers.authorization;<br>  if (authTokenWithBarer) {<br>    const token = authTokenWithBarer.split(&quot; &quot;)[1];<br>    const user = verify(token, process.env.JWT_SECRET) as Token;<br>    return user &amp;&amp; user.userId;<br>  }<br>};</pre><p>For current user query we define User as a resolver return type. User only returns id, name, email and isAdmin because we define these prisma fields before. Get the userId from the utility function and get the user from this id.</p><pre>t.field(&quot;currentUser&quot;, {<br>      type: &quot;User&quot;,<br>      nullable: false,<br>      resolve: async (parent, args, ctx) =&gt; {<br>        const userId = getUserId(ctx);<br>        const user = await ctx.prisma.user({ id: userId });<br>        return user;<br>      },<br>    });</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*icCufJvDWY50WPGJWMQvYA.png" /></figure><h4><strong>Creating getting all Users and deleting Users functionality</strong></h4><p>All users query and mutation only access by a admin. For admin you have to manually set isAdmin to true in your database. All Users query return the list of users you can pass user name for filtering but its a optional argument. We set all users resolver type to user.</p><pre>t.list.field(&quot;allUsers&quot;, {<br>      type: &quot;User&quot;,<br>      nullable: false,<br>      args: {<br>        searchNameString: stringArg({ nullable: true }),<br>      },<br>      resolve: (parent, { searchNameString }, ctx) =&gt; {<br>        return ctx.prisma.users({<br>          where: {<br>            name_contains: searchNameString,<br>          },<br>        });<br>      },<br>    });</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2t7hD588keA1CXV7ccJzfQ.png" /></figure><p>For deleting users, we define deleting users input as it takes user ids in an array</p><pre>export const deleteUserInput = inputObjectType({<br>  name: &quot;DeleteUserInput&quot;,<br>  definition(t) {<br>    t.list.id(&quot;id&quot;, { required: true });<br>  },<br>});</pre><p>We define delete users resolver return type to message payload. This mutation requires an delete users input as it’s an array of user ids.</p><pre>t.field(&quot;deleteUsers&quot;, {<br>      type: &quot;MessagePayload&quot;,<br>      nullable: false,<br>      args: {<br>        ids: arg({ type: &quot;DeleteUserInput&quot;, required: true }),<br>      },<br>      resolve: async (parent, { ids }, ctx) =&gt; {<br>        await ctx.prisma.deleteManyUsers({<br>          id_in: ids.id,<br>        });<br>        return {<br>          message: &quot;Delete users successfully&quot;,<br>        };<br>      },<br>    });</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I7UR8NLmstCvWqrr8W28DA.png" /></figure><h4><strong>Defining rules for authorization</strong></h4><p>We have to define rules for query and mutation, so only admin or authenticated user can gain access to it. We use graphql-shield for defining rules. We define two rules isUserAuthenticated and isAdmin and create a shield for query and mutation. For currentUser query it only requires isAuthenticatedUser but for getting allUsers it requires isAdmin also. For mutation deletingUsers only requires isAdmin role</p><pre>import { rule, shield } from &quot;graphql-shield&quot;;<br>import { getUserId } from &quot;../utils/getUserId&quot;;<br>import { Context } from &quot;../types&quot;;<br><br>const rules = {<br>  isAuthenticatedUser: rule()((parent, args, ctx: Context) =&gt; {<br>    const userId = getUserId(ctx);<br>    return Boolean(userId);<br>  }),<br>  isAdmin: rule()(async (parent, args, ctx: Context) =&gt; {<br>    const userId = getUserId(ctx);<br>    const isAdmin = await ctx.prisma.$exists.user({<br>      id: userId,<br>      isAdmin: true,<br>    });<br>    return isAdmin;<br>  }),<br>};<br>export const middlewares = shield({<br>  Query: {<br>    currentUser: rules.isAuthenticatedUser,<br>    allUsers: rules.isAdmin,<br>  },<br>  Mutation: {<br>    deleteUsers: rules.isAdmin,<br>  },<br>});</pre><p>After defining permission criteria pass this middleware to the global graphQL server. For this we use <a href="https://www.npmjs.com/package/graphql-middleware">graphql-middleware</a></p><pre>import { applyMiddleware } from &quot;graphql-middleware&quot;;<br>import { middlewares } from &quot;./middlewares&quot;;</pre><pre>const server = new GraphQLServer({<br>  schema: applyMiddleware(schema, middlewares),<br>  context: (req) =&gt; {<br>    return {<br>      request: req,<br>      prisma,<br>    };<br>  },<br>});</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uop4IBiJ5SjFQs57vIVX3A.png" /></figure><h4><strong>Conclusion</strong></h4><p>In this tutorial we covered authentication and authorization in GraphQL Nexus. Learning about many libraries JWT, bcrypt,graphQL shield. This will help you in implementing authentication. My main purpose to build an Ultimate Auth biolerplate, I hope it helps.</p><p>Here’s the link to the full code for this Ultimate Authentication<br><a href="https://github.com/muhammadali448/ultimate_auth">https://github.com/muhammadali448/ultimate_auth</a></p><p>I love to know your feedback about the best way for you because there are so many approaches and if we can improve it further.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec01f79dff2c" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/ultimate-authentication-using-graphql-nexus-ec01f79dff2c">Ultimate Authentication using GraphQL Nexus</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>