Team-Tea-Time / laravel-forum

A slim, lean forum package designed for quick and easy integration in Laravel projects
https://laravel-forum.teamteatime.net/
MIT License
601 stars 165 forks source link

Middleware for Auth users #379

Closed digimumo closed 2 months ago

digimumo commented 2 months ago

Hello,

Ive installed your package and I'm trying to add the forum so that it can only be viewed/accessed by logged in users. It's a members only discussion forum.

I'm using the livewire preset. I coped the livewire routes into my own routes web folder and wrapped them in Auth middleware, which seemed to work to some degree, however it doesn't fully protect all routes it would seem as I can still view discussion if I copy and past the URL for each category or discussion and the user is not logged in.

How can I implement this So that the whole 'forum/' directory can only be accessed by logged in users?

Thanks

Riari commented 2 months ago

Hey,

The way to do this is via Policies. The package ships with Category, Thread, and Post policies covering all of the actions a user can perform against those models, including viewing threads. There's also a more general Forum policy for things like bulk changes to categories. See the policies docs for more details.

To make this work, you need enable "private" mode for every top-level category defined in your forum (this will cascade down to any children defined in them), which will make the package check CategoryPolicy::view when a user attempts to view a category and ThreadPolicy::view when a user attempts to view a thread inside that category. If a policy check fails (which automatically happens for users who aren't authenticated), they won't be able to see the content.

If you want to further customize which users can view certain forum content, you'll need to extend the CategoryPolicy and ThreadCategory classes somewhere in your app in order to override their view methods and implement your own logic for determining who should have access.

Let me know if you need any further help with that.

digimumo commented 2 months ago

Thanks, for now as a simple fix I've wrapped the layout view in an auth check and redirect.

@if (Auth::check()) layout html @else

@endif