Redirect Users that is not the owner of posts

I have this in my view

@if(auth.user.id == post.user_id)
            <div class="all-edit">
                <div class="post-body">
                    <a href="/posts/edit/{{ post.id }}">(Edit)</a>
                </div>
            </div>
            @endif

When user that made the post click it, then it takes them to the edit post page. But users that did not create post visit the url it shows the edit post page. i want them to be redirected to the home page instead,

hello @heolad :wave:

You can create custom middleware.

Logic :

  1. Get post id with params object
  2. Get user from auth object
  3. Custom logic (if post owner)
    3.1 if false : redirect (with response.redirect())
    3.2 if true : call await next()
2 Likes

I did this

async handle ({ params:{id},request, response, auth }, next) {
    // call next to advance the request
    
      if(auth.user.id !== 'post.id'){
        return response.redirect('/')
      }else(auth.user.id == 'post.user_id')
    await next()
  }

but it did not work

Get post :

const post = await Post.find(params.id)

Does it work?

Yes it worked @CrBast Thank you very much

1 Like

@CrBast Yes it work, thank you very much

1 Like