Skip to content

Latest commit

 

History

History
387 lines (289 loc) · 10.3 KB

File metadata and controls

387 lines (289 loc) · 10.3 KB

GraphQL Server with Authentication & Permissions

This backend is based on:

https://github.com/prisma/prisma-examples/tree/latest/javascript/graphql-auth

This example shows how to implement a GraphQL server with an email-password-based authentication workflow and authentication rules, based on Prisma, graphql-yoga, graphql-shield & Nexus Schema. It is based on a SQLite database, you can find the database file with some dummy data at ./prisma/dev.db.

How to use

1. Download example & install dependencies

Install dependencies:

yarn install

Note that this also generates Prisma Client JS into node_modules/@prisma/client via a postinstall hook of the @prisma/client package from your package.json.

2. Start the GraphQL server

Launch your GraphQL server with this command:

yarn dev

Navigate to http://localhost:4000 in your browser to explore the API of your GraphQL server in a GraphQL Playground.

Understanding the structure

Using the GraphQL API

The schema that specifies the API operations of your GraphQL server is defined in ./schema.graphql. Below are a number of operations that you can send to the API using the GraphQL Playground.

Feel free to adjust any operation by adding or removing fields. The GraphQL Playground helps you with its auto-completion and query validation features.

Retrieve all published posts and their authors

query {
  feed {
    id
    title
    content
    published
    author {
      id
      name
      email
    }
  }
}
See more API operations

Register a new user

You can send the following mutation in the Playground to sign up a new user and retrieve an authentication token for them:

mutation {
  signup(name: "Sarah", email: "sarah@prisma.io", password: "graphql") {
    token
  }
}

Log in an existing user

This mutation will log in an existing user by requesting a new authentication token for them:

mutation {
  login(email: "sarah@prisma.io", password: "graphql") {
    token
  }
}

Check whether a user is currently logged in with the me query

For this query, you need to make sure a valid authentication token is sent along with the Bearer-prefix in the Authorization header of the request:

{
  "Authorization": "Bearer __YOUR_TOKEN__"
}

With a real token, this looks similar to this:

{
  "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiJjanAydHJyczFmczE1MGEwM3kxaWl6c285IiwiaWF0IjoxNTQzNTA5NjY1fQ.Vx6ad6DuXA0FSQVyaIngOHYVzjKwbwq45flQslnqX04"
}

Inside the Playground, you can set HTTP headers in the bottom-left corner:

Once you've set the header, you can send the following query to check whether the token is valid:

{
  me {
    id
    name
    email
  }
}

Create a new draft

You need to be logged in for this query to work, i.e. an authentication token that was retrieved through a signup or login mutation needs to be added to the Authorization header in the GraphQL Playground.

mutation {
  createDraft(
    title: "Join the Prisma Slack"
    content: "https://slack.prisma.io"
  ) {
    id
    published
  }
}

Publish an existing draft

You need to be logged in for this query to work, i.e. an authentication token that was retrieved through a signup or login mutation needs to be added to the Authorization header in the GraphQL Playground. The authentication token must belong to the user who created the post.

mutation {
  publish(id: __POST_ID__) {
    id
    published
  }
}

Note: You need to replace the __POST_ID__-placeholder with an actual id from a Post item. You can find one e.g. using the filterPosts-query.

Search for posts with a specific title or content

You need to be logged in for this query to work, i.e. an authentication token that was retrieved through a signup or login mutation needs to be added to the Authorization header in the GraphQL Playground.

{
  filterPosts(searchString: "graphql") {
    id
    title
    content
    published 
    author {
      id
      name
      email
    }
  }
}

Retrieve a single post

You need to be logged in for this query to work, i.e. an authentication token that was retrieved through a signup or login mutation needs to be added to the Authorization header in the GraphQL Playground.

{
  post(id: __POST_ID__) {
    id
    title
    content
    published
    author {
      id
      name
      email
    }
  }
}

Note: You need to replace the __POST_ID__-placeholder with an actual id from a Post item. You can find one e.g. using the filterPosts-query.

Delete a post

You need to be logged in for this query to work, i.e. an authentication token that was retrieved through a signup or login mutation needs to be added to the Authorization header in the GraphQL Playground. The authentication token must belong to the user who created the post.

mutation {
  deletePost(id: __POST_ID__) {
    id
  }
}

Note: You need to replace the __POST_ID__-placeholder with an actual id from a Post item. You can find one e.g. using the filterPosts-query.

Evolving the app

Evolving the application typically requires four subsequent steps:

  1. Migrating the database schema using SQL
  2. Updating your Prisma schema by introspecting the database with prisma introspect
  3. Generating Prisma Client to match the new database schema with prisma generate
  4. Using the updated Prisma Client in your application code

For the following example scenario, assume you want to add a "profile" feature to the app where users can create a profile and write a short bio about themselves.

1. Change your database schema using SQL

The first step would be to add a new table, e.g. called Profile, to the database. In SQLite, you can do so by running the following SQL statement:

CREATE TABLE "Profile" (
  "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
  "bio" TEXT,
  "user" INTEGER NOT NULL UNIQUE REFERENCES "User"(id) ON DELETE SET NULL
);

To run the SQL statement against the database, you can use the sqlite3 CLI in your terminal, e.g.:

sqlite3 dev.db \
'CREATE TABLE "Profile" (
  "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
  "bio" TEXT,
  "user" INTEGER NOT NULL UNIQUE REFERENCES "User"(id) ON DELETE SET NULL
);'

Note that we're adding a unique constraint to the foreign key on user, this means we're expressing a 1:1 relationship between User and Profile, i.e.: "one user has one profile".

While your database now is already aware of the new table, you're not yet able to perform any operations against it using Prisma Client. The next two steps will update the Prisma Client API to include operations against the new Profile table.

2. Introspect your database

The Prisma schema is the foundation for the generated Prisma Client API. Therefore, you first need to make sure the new Profile table is represented in it as well. The easiest way to do so is by introspecting your database:

npx prisma introspect

Note: You're using npx to run Prisma 2 CLI that's listed as a development dependency in package.json. Alternatively, you can install the CLI globally using npm install -g @prisma/cli. When using Yarn, you can run: yarn prisma dev.

The introspect command updates your schema.prisma file. It now includes the Profile model and its 1:1 relation to User:

model Post {
  author    User?
  content   String?
  id        Int     @id
  published Boolean @default(false)
  title     String
}

model User {
  email   String   @unique
  id      Int      @id
  name    String?
  post    Post[]
  profile Profile?
}

model Profile {
  bio  String?
  id   Int     @default(autoincrement()) @id
  user Int     @unique
  User User    @relation(fields: [user], references: [id])
}

3. Generate Prisma Client

With the updated Prisma schema, you can now also update the Prisma Client API with the following command:

npx prisma generate

This command updated the Prisma Client API in node_modules/@prisma/client.

4. Use the updated Prisma Client in your application code

Option A: Expose Profile operations via nexus-prisma

With the nexus-prisma package, you can expose the new Profile model in the API like so:

// ... as before

const User = objectType({
  name: 'User',
  definition(t) {
    t.model.id()
    t.model.name()
    t.model.email()
    t.model.posts({
      pagination: false,
    })
+   t.model.profile()
  },
})

// ... as before

+const Profile = objectType({
+  name: 'Profile',
+  definition(t) {
+    t.model.id()
+    t.model.bio()
+    t.model.user()
+  },
+})

// ... as before

export const schema = makeSchema({
+  types: [Query, Mutation, Post, User, Profile],
  // ... as before
}

Option B: Use the PrismaClient instance directly

As the Prisma Client API was updated, you can now also invoke "raw" operations via prisma.profile directly.

Create a new profile for an existing user
const profile = await prisma.profile.create({
  data: {
    bio: "Hello World",
    user: {
      connect: { email: "alice@prisma.io" },
    },
  },
});
Create a new user with a new profile
const user = await prisma.user.create({
  data: {
    email: "john@prisma.io",
    name: "John",
    profile: {
      create: {
        bio: "Hello World",
      },
    },
  },
});
Update the profile of an existing user
const userWithUpdatedProfile = await prisma.user.update({
  where: { email: "alice@prisma.io" },
  data: {
    profile: {
      update: {
        bio: "Hello Friends",
      },
    },
  },
});

Next steps