Search code examples
strapi

What is the safest way to save CurrentUser.id?


Dear Strapi team and fans,

I have a simple question:

I created a table with the following setting:

In "Author" I want to save "CurrentUser.id". I can write in FrontEnd "Author = CurrentUser.id", which works, but this assignment can be manipulated in FrontEnd, right?

For security, it might be better if Author automatically gets the value of CurrentUser.id in BackEnd.

Do I have to change anything in Strapi BackEnd or is this functionality already available?

Thanks in advance!

Benjamin

PS: Here is a screenshot. That's what I mean.


Solution

  • Documentation here https://strapi.io/documentation/3.x.x/guides/authentication.html#user-object-in-strapi-context

    When a user is authenticated and you request Strapi with, that set the User information in the context (ctx.state.user)

    So if you want to auto apply the user id of en entry when you create it. You have to customise the create function of your controller and add the ctx.state.user.id for the key you want of your ctx.request.body

    In your case will be ./api/article/controllers/Article.js And for the the create function will look like that

    create: async (ctx) => {
        ctx.request.body.author = ctx.state.user._id;
        return strapi.services.article.create(ctx.request.body);
      },