Jetstream/Fortify Multi-Auth: Roles, Permissions and Guards

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello guys today we will talk about multi-authentication with multiple guards in laravel it was a topic and a question requested a lot in your comments and finally i got the time and the information to shoot this a bit longer video about multi-auth this is one comment example multi-auth in jet stream another example is make tutorial on multi authentication with jetstream in livewire and it's not just about gesturing or livewire it's just general multi-auth with multiple tables so for example administrator students and teachers and another example is multi-auth system with fortify specifically so just the back end so the question became really strong in laravel 8 if you're using laravel 45 because before in general laravel auth or if you're not using fortify i will zoom it in in config auth there's a configuration for multiple guards so you can create web guard with provider users and another web guard with provider admins or teachers or whatever this is your database table and there are articles like this one i found on medium pretty old one but this is how it looks so users and admins are different providers and then you build all your logic in the routes and everywhere else around those multiple guards which would look like this one so if guard web check or if auth guard admin check so totally separate guards in database tables in laravel fortify it's not possible if you go to config fortify there's only one guard to be used and by default it is web and when some people raise that question in fortify github issue this is a specific issue that was discussed the most and then taylor comments at first that is a feature request not a bug so anyone can support and submit a pull request to that but at that time the issue was closed and taylor was referencing to use config auth so multi-auth system and build your own kind of fortify-like thing with multiple guards also there was this article mentioned in this github issue which kind of implemented the multi-guard authentication but in my opinion in quite a complicated way with sub domains with macros so a lot of things to be considering web admin like this and also changing fortify service provider from configuration so pretty complex stuff so what should you do if you want to use fortify or jet stream and you want multi authentication that is the question and here i want to change the question a bit so shift the question do you need multi auth with multi-guards or you need the roles in your system so all of those examples or most of those examples are about roles so administrators teachers users customers something like that they are not multiple guards they are multiple roles of user system and here i found a laracast forum thread with person asking the same thing so how to make multiple guard for admins teachers and students so that is not my own example and after a few comments and discussions bobby bauman convinced the author so better approaches one table and role based authorization system for different users so for anyone asking me in the comments on youtube or elsewhere how to implement multi guards think about rows and permissions instead and i think that confusion came from the fact that laravel documentation for authentication has adding custom guards with not so practical examples of how it should be implemented and when it should be implemented so for custom guards one example is jwt which is general example and then also down below there's custom user providers and the example here is provider and i think both of those are not that typical use case scenarios so it's not the roles right but the section of the documentation which should talk about the roles is authorization so the difference between authentication and authorization is authentication is login authorization is what features can be accessible by which user so authorization should talk about the roles but it mostly talks about permissions gates is the same thing as permissions and we will get to them practically in this video but i think there's a gap in the documentation that roles are not talked about and people confuse that guards should be rose where in fact it is not the case so now moving from theory to practice let's implement that admins teachers and students logic in laravel 8 using laravel jetstream and fortify but not with multi-auth but instead with rolls system so let's get totally practical and we will customize this registration form of flowerville jet stream i've installed the jet stream already locally and i've started building that project and i won't be live coding that because i will be showing different parts and live coding that will take too long but i will explain it bit by bit so when working with administrators teachers and students there are three things we can customize for each of the roles first thing is database fields for each of the role and that is probably the main reason why people create separate database tables because some fields are different so that's one problem we will solve second problem is access to the features so menu items and permissions to all of that and then third thing is a different layout so i will show you how to customize the layout so it will be different layout for administrator for teacher and for student and first extra fields as i said probably people create extra tables because there are some fields for teachers and some fields for students and none of those fields are needed for administrators right and in my opinion if it is only a few fields like teachers license or student license or address or birth date or something like that there's nothing wrong in adding them to users table but as nullable fields so this is how i have done it in the code i've created a rows table so rows model actually in artisan i've made a roll and then row cedar with three rows and then a separate migration to add the fields and in addition to role id as a foreign key there are nullable fields for student or for teacher with prefix and again in my opinion if it is 5 or up to 10 fields it's totally fine to store them in users table just be a bit more careful when selecting the data not select all the fields but select only the ones you need for that particular query to avoid too much data coming from the server if it is more fields than that if it's more than 10 fields then probably it makes sense to create separate tables like students or teachers but not instead of users on top of users so it will be table students with student fields and with user id foreign key relationship to users so again every user of the system student teacher admin is a user first and then they have their own profile which is additional fields on top of authentication fields in users table but then that way complicates things quite a lot because in every eloquent query need to join that table so i will not implement that in this video but just as a alternative way to do that it could be a separate table but not instead of users on top of users so we have those four new fields in migrations we need to make them fillable so in user php model i've added those three and of course i need to add role id as well and now we go to register blade which is in resources views auth register blade it's part of laravel jet stream and at the bottom of previous fields i've added those new fields almost copy pasting the label and the input which is blade components in jet stream and i have a separate video on blade components in jet stream i will link that in the description below and the full repository for this project will be on github for free so so you can read it all and try it all later so visual result is this at the bottom of four fields there are new four fields but now let's make the forum dynamic when i'm a student i should see these two fields and when i'm a teacher i should see only the qualifications field and behind the scenes to save you time i've implemented that so here's how it works register a student or teacher and then that refreshes and let me show you how i did it i used the framework micro framework called alpine.js which is a part of laravel jetstream so if you go to package.json of jstream there is alpine js enabled by default and alpine js is from the same founder the same creator as laravel livewire and have a separate video seven minute introduction to alpine js but basically what it does is for small dynamic things on the page like open something when something does something so you initialize some variable or variables and then have some syntax like x show x height x model and something like that so it's similar to vue.js bind and stuff but without the full framework of vue.js so the only thing i had to change in the register blade file in the main form i need to initialize the data so roll id is 2 by default in all of the behavior inside of that form and then inside of that form if we scroll to those fields i do x model role id on that select of teacher and student and then in those other fields i do x show with a condition so if roll id 2 then those fields will be visible if roll a d3 is teacher field and now let's save those fields so i will use fake filler chrome extension to fill it in and the actual registration is happening in a file called app actions fortify create new user this is part of laravel fortify and all we need to do here is to add student address equals input student address and other three fields actually four fields so let's duplicate that student license number teacher qualifications and also let's add null i'm not sure if we need that but just in case no and also we need role id role id equals input row id that's it let's try it out and click register and we are in so no errors it is successful and let's see what we have in the database so we have our new user and let's see the fields role id 2 student address is there license number is there and teacher qualification says no that's exactly what we wanted now let's build different menu items for different types of users and make them visible and accessible so i've done it behind the scenes and i will explain it to you step by step so here you can see the lessons menu item which is for students and if i click that i haven't actually created any functionality just the url of student lessons and accessible only for students and similarly if i log out and register with a teacher so fake filler and teacher something here register i have another menu item called courses with different url teacher courses so prefix teacher accessible only for teachers and if i go to student student lessons i get four or three forbidden so how did i do that first in the terminal i've created three separate controllers they are all resourceful controllers but i will implement only the index method and in each of those controllers we have something like this so namespace is important subfolder so for more controllers you will create them separately in one of those subfolders and all i'm doing here is launching the index view and also the views i've created them manually but resources views admin users index then student lesson index then teacher course index they all extend the same layout for now it's just they show different information then in the routes web this is the interesting part let's close the sidebar for now i've created one route group with middleware auth which means all the pages are only for logged in users and then separately three sub groups with middleware role student role teacher and role admin prefix is for url so for this student lessons and as is for routes for route names so in the navigation menu blade which is laravel gesturing navigation menu the top menu i have this if role is one then i add link to routeadmin.users.index so that admin comes from this with a dot keep in mind then users come from route resource and then indexes the actual method so i show one of those three menu items and they are protected by middleware called row i've created that in terminal php artisan make middleware check row and that check row it's not really pretty in real life scenario it probably should be something less about if else statements but some more structure some service to check the permissions but i want you to understand the logic so if the role is admin and user role logged in user role is not one then we abort with forbidden code and that role comes as this parameter to that function and this parameter comes from here so value after the row becomes the parameter value to middleware and then that middleware should be registered in app http kernel in route middleware like this so this is the actual name of that middleware which we call in routes web and that's it for permissions we have three pages each accessible only to that role now this scenario is fine for smaller projects where you have only rows and a few features per role but in more complex projects it makes sense to have authorization with gates and policies so i will transform one of that permissions to gates so you can write gate as gate defined in your auth service provider so we open auth service provider and in the boot we have something like this gate define for example manage users function user we don't have any post this should be auto completed by phpstorm and will assign the true or false value if role id equals one equals one means administrator i think this one is enough so now we define manage users and then we can change the navigation menu from here so can manage users manage users like this so if we refresh our menu now let's refresh that shouldn't appear but if we change the courses for example to can can manage courses by default it will disappear because currently we can't manage courses but if we define the gate here and manage courses like this to roll id3 which is a teacher we refresh and now we see that menu item but of course it's not enough to just show or hide the menu items we also need to validate that in the controller somewhere so for example in course controller index we can add if gate denies manage courses then abort 403 like this it can be in a controller it can be moved to some middleware that's your choice it's just that gate should be not the access gate but facade this one should be changed like this like this and now if we refresh that that still works but if we do a typo for example managed courses it will show 403 so don't forget to protect both controllers and the views and of course the topic is much deeper in authorization documentation there's a huge scrolling in the right side you can see so i suggest you read all of that authorization or you can take my course i have a separate course on rows and permissions practical roles and permissions in laravel it's one and a half hours of managing all the permissions rows and multi-tenancy and all of that you can see on the left side the content of that course and i will link that course in the description below also there are packages to help you manage the permissions in more convenient way for bigger projects i've reviewed two of the packages really really long time ago three years ago but they are still going strong and i totally recommend them it's laravel permission by sparty or bouncer by joseph silver both are good they are doing pretty much similar things so check their documentation and i will link them in the description below and final thing what i want to do in this video is tackle different layouts so for example you want to have a different design for teacher for student and for admin and currently in jet stream it all comes through layout of resources views layouts app blade but we can copy and paste that into a different layout so i've done exactly that and now we have resources views layouts admin blade student blade and teacher blade and the only difference between them is one parameter so background grade 100 is tailwind class and for teacher it is background red 100 and for student for example it's background blue 100 and we need to create layout component classes so in app view components by default it is app layout but i did file save as and created admin layout student layout and teacher layout and the only difference is that rendering is not from layouts app but layout teacher and now if i register as a teacher for example i register i go to my courses and the background is red because in courses index here i'm extending x teacher layout not x app layout anymore so in my case the only difference between layouts is one parameter just for demonstration but in fact you can totally recreate totally different blade for layout for each of the rows here i want to end this video of course there's much much more you can do with rows permissions and stuff like that but the main goal of this video i wanted to show you step by step how to create multi-roles application in laravel 8 in jet stream instead of multi-auth with guards as a lot of people are confused in most cases you don't need guards you need roles and permissions like in this video if you want to receive more videos like this one subscribe to the channel and support the channel financially by doing one of two things using our laravel quick admin panel generator or enroll in one of my courses at laravel daily the teachable.com one of the courses is on rows and permissions and you will have the link in the description of this video see you guys in other videos
Info
Channel: Laravel Daily
Views: 45,005
Rating: 4.9390135 out of 5
Keywords:
Id: NiQSNjWKLfU
Channel Id: undefined
Length: 18min 59sec (1139 seconds)
Published: Sun Jan 17 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.