I am just about three days old in laravel, yesterday I tried creating an authentications system using eloquent, so without looking I deleted the default User model, and then I tried creating my own from what I had read from the documentation. After setting up every thing as I had studied and understood, I tried running my app, but whenever I enter the correct username and password I get this error
Argument 1 passed to Illuminate\Auth\EloquentUserProvider::validateCredentials()
must be an instance of Illuminate\Auth\UserInterface, instance of User given, called in dir
I did not know what the EloquentUserProvider was or where it was even coming from. My original model looked like this
class User extends Eloquent {}
I battled with this error for the whole day (no exaggeration), But today I found out from this SO Can't authenticate user in laravel that it was because I had not implemented some interface, so they linked me to https://github.com/laravel/laravel/blob/master/app/models/User.php where I copied the default model I initially deleted.
I used the documentation almost through out my learning process, and no where in the documention for authentication and for eloquent did they mention that we are suppose to implement these interface for us to be able to use Auth::attempt() method, my question now is how then do we (newbies) know what to implement and what not to implement, or what any of these interfaces even do.
This is simple. It's a laravel's requirement. The User model is generated by default for you. If you do not need to implement the interface's methods, just add them empty in your User class.
And of course, in your case, what to extend or implement will be shown as errors on startup. Reading them carefully can give you all the asnwers.
Also, if you want to use different User Authentication features, or extend the existing ones, you can look some info here in the docs
Related
I have used this tutorial for creating my user login in Laravel: Laravel Authentication Essentials. So I have a SessionController that contains the methods create, store and destroy, for showing the form, logging in and out respectively.
But there is no model in this tutorial, the validation and Auth::attempt is in the controller. And that doesn't feel right. I can not create a Session model, since the Session class already exists.
Should I put the login/out logic in the User model, or is there another way to do this that complies with the MVC architectural pattern?
First, remember (or know) that you can change everything in Laravel. If you need a Session model using a sessions table, go to app/config/session.php and change the Laravel sessions table to laravel_sessions:
'table' => 'laravel_sessions',
People are doing things differently these days, methods are improving on a daily basis and the way you do your code must be confortable to you. If you feel it is not right the way you are seeing people doing it, change it, Laravel give you the power to change and do things your way. And if you feel you just found a better way of doing it, share it.
This is a 2013 video and today Jeffrey is doing authentication in a completly different way. Sign up for a Laracasts account and take the full Build a Larabook video series to see how he's doing it now.
There's no Session model in this tutorial because he's not storing sessions (successful logins) in a sessions table.
In the tutorial he never touches the User model, so there is no login in the user model. The only thing he's using to do authentication is Auth::attempt(), a Laravel facade method which uses internally the user model (M), to find a user and check if the password matches. He's working with a Session controller (C) and everything related to login (or sign in) and showing login views (V) is done inside that particular controller.
If it is easier to you, you can rename SessionsController to LoginController, I, myself, don't really like the Sessions name for login, but that's a matter of taste not code correctness.
That being said I don't see an MVC (or whatever name people like to call it this week) problem in that video.
EDIT Answering the comment:
The purpose of the model is towards data, no data, no model. In the context of Laravel and a database management system, yes, no table, no model. In the context, for instance, of a client-server API, your server API (Laravel, Rails...) will provide data for your client model (Angular, EmberJS...), so, there will be no table directly related to the client model, but still a model.
But in that particular case you are accessing a model, the user model, via a service, the Authentication service.
Just really what the title says, does anybody have a decent explanation on how to use models properly in laravel 4? I'm fine with using the pre-existing User model. But I read somewhere that queries and such should be done in a model of your own.
So what I have is basically a form where you can make a status update (like facebook) and it stores it in a database but the query is run through the controller.
I want it to be done through a model.
Any information on this would be great! Thanks in advance
It's a broad question and right place to learn about how to use model in Laravel-4 is the laravel site itself, but anyways.
Actually, model is the the place where you should keep the business logic in any MVC framework, it could be database related or anything else that is the heart of the application and controller and View are just two parts of the application whose responsibility is only communicate to the model, fetch data and present it to the user but all the data processing should be done in the model and controller should be kept slim and view is only a mechanism to present the user a UI.
So, if you want to have a User model in your application (laravel-4) then you may extend it from Eloquent like
class User extends Eloquent{
// code goes here
}
and then call it's methods from the controller, like
$user = User::get(1);
then passing it to the view like
return View::make('viewname', $user);
That's it. But, if you think, where the find method come from then, it's because, you have extended the Eloquent model and in that model all the necessary methods (find e.t.c) are available and your User model inherited the behavior of Eloquent model, so you can use all the methods from User and it's not necessary to a single method in your User model unless you need to write some special methods for that User model, like relationship functions and so. well, the perfect place to seek help or to know the basic about it is the Laravel site, try to understand it from there and if you fail or just stuck anywhere then come here to ask with specific problem. Also, check Basic Database Usage and Query Builder.
BTW, you may check this post for a detailed answer on model of MVC.
While testing roles in my application I found the function isGranted of the SecurityContext. It works great but now I need to check the roles of a user that is not the current user so isGranted doesn't work for me.
I've been looking and I found the function hasRole of the user, the problem is that this function doesn't look in the hierarchy tree of Symfony and it just looks in the roles assigned to the user.
So, Is there a function that looks for a role of a user looking in the hierarchy tree like isGranted do for the current user?
EDIT
I found this solution:
How to use the AccessDecisionManager in Symfony2 for authorization of arbitrary users?
I implemented it and it works, the problem is that it needs the ContainerBuilder and I would prefer a different approach.
Any Idea?
Basically AFAIK SecurityContext work with Symfony\Component\Security\Core\Authentication\Token\TokenInterface from where can fetch current user using getUser method.
If user token is not authenticated then isGranted trying authenticate user token first and then use class called AccessDecisionManager which basically iterate over voters objects and call them (and can use different strategies for that) One of called voters is RoleHierarchyVoter which use Symfony\Component\Security\Core\Role\RoleHierarchy.
So answer to your question:
I think that is no such function like isGranted for other users (or do not know about any), but you can write own service which allow to that using security.role_hierarchy (just notice that is private service).
BTW hasRole probably should be sufficient most of the time, so maybe you should think about what do you want to do ;)
I'm building a management system for an idea I have. I'm well versed in PHP (at least enough to do everything I need to do) but I'm not that experienced with using OOP. I use it as much as I can but a lot of the best practices I'm not familiar with so when I do things I worry I'm doing them in the wrong order.
For this project I have a class for the thing the user is managing, I need to check whether or not the user has permissions to manage it. I know how to check the permissions, my question is: where should I be doing it?
Should I be doing it outside the class, like so:
if user permissions are valid
initialize class
else return error
or should I be doing
initialize class
class checks permissions
class returns error if permissions are invalid
I'm unsure which is the correct approach. On the one hand checking within the class seems the best based on what I know of OOP methodology, but then I also have the feeling that letting it get as far as initializing the class when permissions are unknown might be bad.
How should I be doing it? If there's any sort of article that covers this sort of thing a link would be greatly appreciated (I can't find anything through searches but I'm not 100% sure if I'm searching for the right thing as I know little of OOP)
It depends on what is your permissions model, and there is no "one correct way" to do it. It's a matter of approach. The important thing, is that whatever you choose, you use it consistently.
In my latest projects, I came across several different models. One of the most straightforward is a page-based permission, which is good if you do page-based flow, and use objects for support: you define at the top of the page who is supposed to access it and in case you can redirect. This is the simplest one, but can be very useful on specific applications.
If you, on the contrary, use objects to do your main flow, you should secure your object methods (rather than class instantiation). If you have a "save()" method, which can be called by specific users only, first thing when you enter that method, do your permissions check.
I am currently using an MVC pattern, and I have a Controller, which dispatches the actions to its children. Its only public method is execAction($params) and it will call actionAction($params) on itself, but first it will check permissions.
One important thing to remember is: never present actions on the UI that the user is not allowed to do (unless you are trying to force him to buy your "PRO version", that is) ;-)
I have written a pretty solid and robust CMS system. Here's how I do it and I hope you can extrapolate some information on making your own solution.
I have an index file, which loads an Admin class. Functionality in my CMS is modular (so containing in its own file and class).
A module is loaded based on a $_GET parameter.
Because the function to check the $_GET parameter and load the corresponding function is in my Admin class ($admin->pick_method()) and I also have a User object in my Admin class, I can first check the requested module is in the currently logged in user's permissions array.
If the permissions check returns true, I load the module. If false, I display a friendly "unauthorized access" page.
Hope this helps.
I think best way to do is to have class of permissions.
And then you can check before creating object or in object.
create permission class
if access then create class and set permission object
else error
// do action
if have permissions show something
else do not show something
Look how done in zend acl component
Validating within the class generates a dependency between the class and the permissions authorisation which isn't good because you are tying together two potential disparate items. You can solve this by Inversion of Control (eg. dependency injection) or as I do by authorisation notifications using Emesary.
Validating outside of the class is possibly worse because there is a real danger that the authorisation check will be wrong or missed completely. It also creates the wrong sort of linking between objects as the object is not in control of itself.
If you are going to do it outside of the object when it is created then it is probably better to require the object to provide an interface such as IAuthorisable which can be verified by a seperate object.
e.g.
interface IAuthorisable
{
public function getRequirements();
}
class Authorisation
{
public static createObject($newObj)
{
if ( canDo( $newObj->getRequirements()) )
return $newObj;
return null;
}
}
class Something implements IAuthorisable
{
public function getRequirements()
{
return SomeSortOfIdentifierOrSomething;
}
}
$mySomething = Authorisation::createObject(new Something($p1, $p2), "
If $mySomething is null it isn't allowed. Obviously this needs extending and designing properly which is left as an exercise for the reader.
OO basics
If it makes sense to include it in the class. You could do it.
Does a Book class have an authenticate function? No, functions like download() and convertToPDF() make more sense.
My approach
I always try to find the route of the least resistance.
If there are 10 scripts/pages that talk to 1 class and 1 or 2 scripts needs authentication for certain actions i would build the authentication into those 1 or 2 scripts. (or put them in a subfolder with a .htpasswd)
But when you're using a MVC structure, everything is a class, so its become a question of deciding which class.
I tend to put the authentication rules in the Controllers classes and the authentication to database-logic in a User class.
I'm looking for advice on how to tackle a design problem I've came up with. I'm currently using Symfony framework so I'll be using the names of Symfony classes.
When a user becomes "authenticated" or their "credentials" change in the Symfony user class, a regenerate() gets called on the currently used storage class. The store class extends sfStorage.
Now, when this regenerate() command is ran, we need to do some business logic. The following are options I've came up with so far:
Modify the three functions that addCredential, removeCredential, setAuthenticated and tell them to dispatch an event (setAuthenticated already does) so we know to do our business logic.
Second option would be to extend the sfSessionStorage class and tell it to throw an event on each regenerate. The problem I have with this is that sfUser asks for the interface sfStorage. Unless we modify sfStorage then if someone passed any kind of class that extends sfStorage that didn't know to add the event, it wouldn't work.
The third option would be the second option, but we would still extend the user object to say that we require the interface of a custom sfStorage abstract class that sends out a notification on regenerate. Then we would know for sure that any class that passes through would follow this notification method.
Anyone have any suggestions?
I would go with the second option and extend the sfSessionStorage class, and then use the class by inserting it into the factories.yml.
This shouldn't cause any issues with the sfUser though as your custom storage class will extend from sfStorage by proxy.