~/javascript/strapi-create-article-jwt-author-edit-update.md

How to Create Article by REST API and Configure only Author can Edit/Update/Delete articles

3 min readMay 02, 2021by Gorav Singal#javascript#strapi
// TL;DR

Create articles via Strapi REST API with JWT authentication and configure permissions so only the original author can edit, update, or delete their own articles.

How to Create Article by REST API and Configure only Author can Edit/Update/Delete articles

Introduction

In this post, we will see:

  • create a test user
  • Authenticate it via REST API
  • How we will create an Article using REST API.
  • How to configure that only Author can add/update/delete an article

So far, we have seen How to Configure permissions on Article

Create a Test User

  • Click on Users
  • Add new User

Get single Article

Authenticate the User

The REST end point for this is:

POST /auth/local

Body: 
{
  identifier: "email",
  password: ""
}

Authenticate User2

As you can see, once we authenticate user by REST API, we get a jwt token. Which will be used for authenticated other APIs, like create/update/delete.

Create an Article

POST /articles

Body:
{
  title: "",
  body: ""
}

Header:
Authorization: Bearer <jwt token>

Create Article

Edit or Update an Article

The process will remain same, only HTTP method will change

PUT /articles

Body:
{
  title: "",
  body: ""
}

Header:
Authorization: Bearer <jwt token>

Delete an Article

The process will remain same, only HTTP method will change

PUT /articles/<id>

Header:
Authorization: Bearer <jwt token>

Configure only Author can Update/Delete an Article

So far we have configured that authenticated users can create/update/delete articles. But, we do not want that any authenticated user will update other author’s articles.

We need to do little tweaking in strapi. Lets follow.

Save Author user details in Articles created.

Till now, there is no information saved that who created a particular article. Lets starting saving it.

  • Goto Content types builder.
  • Goto your Article type
  • Click on: “Add Another field”
  • Click on Relation type
  • On right side, select: “User (from users-permission)”
  • On left side, give it a name as “author”
  • Select relation as: “many-to-one”. It will show as: “User has many articles”

Add Author for Articles

Now, we need to start saving user information with created articles. For this, we need to write little code.

Open /api/article/controllers/article.js Replace file content with following:

const { parseMultipartData, sanitizeEntity } = require('strapi-utils');

module.exports = {
  /**
   * Create a record.
   *
   * @return {Object}
   */

  async create(ctx) {
    let entity;
    if (ctx.is('multipart')) {
      const { data, files } = parseMultipartData(ctx);
      data.author = ctx.state.user.id;
      entity = await strapi.services.article.create(data, { files });
    } else {
      ctx.request.body.author = ctx.state.user.id;
      entity = await strapi.services.article.create(ctx.request.body);
    }
    return sanitizeEntity(entity, { model: strapi.models.article });
  },
};

Save it.

Create Article again from REST API

Now when you submit the create article request again, you will have author information saved with each article. A sample response will look like:

{
    "_id": "608e66f33c976e44787564c4",
    "title": "How to create an Article2",
    "body": "I will explain the process",
    "published_at": "2021-05-02T08:46:43.948Z",
    "createdAt": "2021-05-02T08:46:43.952Z",
    "updatedAt": "2021-05-02T08:46:43.959Z",
    "__v": 0,
    "author": {
        "confirmed": true,
        "blocked": false,
        "_id": "608e0771a81d84396e94a1d8",
        "username": "test",
        "email": "[email protected]",
        "provider": "local",
        "createdAt": "2021-05-02T01:59:13.156Z",
        "updatedAt": "2021-05-02T01:59:13.163Z",
        "__v": 0,
        "role": "608d84c0dbb8e436fba3faa4",
        "id": "608e0771a81d84396e94a1d8"
    },
    "id": "608e66f33c976e44787564c4"
}

Restrict Author can Update only his Articles

Again, we will need to write little code for this. Open same file again: /api/article/controllers/article.js

Add following code:

  /**
   * Update a record.
   *
   * @return {Object}
   */

  async update(ctx) {
    const { id } = ctx.params;

    let entity;

    const [article] = await strapi.services.article.find({
      id: ctx.params.id,
      'author.id': ctx.state.user.id,
    });

    if (!article) {
      return ctx.unauthorized(`You can't update this entry`);
    }

    if (ctx.is('multipart')) {
      const { data, files } = parseMultipartData(ctx);
      entity = await strapi.services.article.update({ id }, data, {
        files,
      });
    } else {
      entity = await strapi.services.article.update({ id }, ctx.request.body);
    }

    return sanitizeEntity(entity, { model: strapi.models.article });
  },

In above code, while receiving update article request. We are checking if the authenticated user is the author of article asked. If yes, proceed else reject the call.

Restrict that Author can delete only his Articles

Similarly to restrict that users can delete only their articles. Write below code in same file: /api/article/controllers/article.js

async delete(ctx) {
    const { id } = ctx.params;

    let entity;

    const [article] = await strapi.services.article.find({
      id: ctx.params.id,
      'author.id': ctx.state.user.id,
    });

    if (!article) {
      return ctx.unauthorized(`You can't update this entry`);
    }

    if (ctx.is('multipart')) {
      const { data, files } = parseMultipartData(ctx);
      entity = await strapi.services.article.delete({ id }, data, {
        files,
      });
    } else {
      entity = await strapi.services.article.delete({ id }, ctx.request.body);
    }

    return sanitizeEntity(entity, { model: strapi.models.article });
  },

Next

In next post, we will see how to setup a Slug(Nice URL) system.

$ subscribe --weekly

One deep dive a week, in your inbox

System design, AI engineering, trading systems and interview prep. Tested code, real numbers. Free, and you can unsubscribe any time.

or read it on gyanbyte.substack.com

Share

Related Posts

Strapi Tutorial - How to Configure Slug to have Nice URLs for SEO

Strapi Tutorial - How to Configure Slug to have Nice URLs for SEO

Introduction In our previous posts, we have seen How to Create Article in Strapi…

Tutorial - How to Create a Content-type, and Configure User Permissions for REST APIs

Tutorial - How to Create a Content-type, and Configure User Permissions for REST APIs

Introduction In this post, we will see how we can create a content type. And…

Tutorial - How to Setup Strapi Backend with Mongodb

Tutorial - How to Setup Strapi Backend with Mongodb

Introduction In this step-by-step tutorial, we will setup strapi headless CMS…

How to use Draft.js WYSWYG with Next.js and Strapi Backend, Edit/Update Saved Article

How to use Draft.js WYSWYG with Next.js and Strapi Backend, Edit/Update Saved Article

Introduction This post is in contuation of our previous post: How to use Draft…

Create Articles with Image Upload Using Draft.js, Next.js, and Strapi

Create Articles with Image Upload Using Draft.js, Next.js, and Strapi

Introduction In this post, we will use in Next.js with strapi. And, we will…

How to Integrate Next.js with Strapi Backend and Create a common utility class for REST APIs

How to Integrate Next.js with Strapi Backend and Create a common utility class for REST APIs

Introduction In this post, we will integrate Next.js with Strapi fully. And we…

Latest Posts

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

In the previous article I argued that AI is not killing software engineering…

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

A few months back I approved a PR that was almost entirely AI-generated. It…

How to Debug AI-Generated Code: Understand First, Fix Last

How to Debug AI-Generated Code: Understand First, Fix Last

In the last article I wrote about reviewing AI code before it goes in. This one…

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

Every few weeks somebody sends me a scary headline — “AI will replace all…

The Transactional Outbox Pattern: Never Lose an Event Again

The Transactional Outbox Pattern: Never Lose an Event Again

This is one of those patterns that looks like nothing until you get burnt once…

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Here is a question I like to ask in interviews: your bank account shows a…