Is authentication a concern of my domain or of my application? - php

I'm trying to design the authentication of my web application in an object oriented manner. Is this a concern of my domain in which case I would have something like this:
$user->authenticate($authenticator);
$user->login($authenticator);
Where $authenticator is an interface to my authentication service.
Or would this be a cross cutting concern and I would do it the other way around.
$authenticator->authenticate($user);
$session->setUser($user);
The first way seems more "OO" to me, since I don't have to ask anything from my user object...it passes the information the authenticator needs. But it feels like I'm "polluting" my domain in a certain respect...logging in is not a business requirement of my application...it is a side effect from the fact that I need a method of authentication to protect my application.

Unless your Domain includes authentication as a central concept, I would say that it's a cross-cutting concern and not part of the Domain Model.
Most developers write business applications that model something entirely different than software security. Authentication is a very important part of many applications, but really has nothing to do with the Domain itself.
That doesn't mean that you can't deal with authentication in an object-oriented way.
In Domain-Driven Design terminology, the business concept you model is part of your Core Domain while you could choose to implement authentication and other security concepts in a Generic Subdomain.
I can't help with the php-specific things, but in .NET, security is pretty much something that's just handled by the platform if you do it right. Here it's a truly cross-cutting concern by implementation, so that's how it's done elsewhere (FWIW).

IMHO passing an Authenticator is bad OO. Why should a user understand how to authenticate itself? It's a user it doesn't even need to know what an authenticator is. Also, passing an authenticator seems strange to me unless you plan on having different ways of authenticating a user thus having a need to pass different types of authenticators to your user. You make it seem like authentication isn't a major part of your application so I doubt you will have more than one way of authenticating a user.
I think your second approach makes more sense although still seems like overkill to me. My favorite framework is symfony and they have a great plugin called sfGuard that handles authentication. Take a look at the source code of the plugin and see if it gives you any inspiration.

Coupling
$user->authenticate($authenticator);
$user->login($authenticator);
Inversion of control
$authenticator->authenticate($user);
$session->setUser($user);
Coupling is bad, inversion is good. Go with the later.

Related

Where does an API call resides in a repository pattern laravel application?

I am building a web application which has 3 rd party api integrations which include
Payment gateways
Sms vendors
Email providers like mandrill
Now I can have concrete repository classes where functions which talk to my DB resides. As far as I know the repositories are on standard practice used to talk to databases. Now where do I build the logic of calling a 3rd party API resides? Is that what a service provider is meant for? If then can some one show me very basic example of how the whole flow works? For eg sending an sms from a controller by calling the service provider. The question might seems dump but I am not able to get any examples or flow searching it online. There is no real world examples to be seen.
Please give some reference or example if someone has done the same.
TIA!
Repositories are, in the strict sense, for encapsulating methods for advanced access to a set of data.
That being said, there is nothing that says this is the only way to use them. The pattern itself allows for you to group different processes into different places, improving the organization of your code.
At this point one could argue they are no longer repositories, but the most important factor isn't just adhering to design patterns in the strictest of senses. It's using the pattern that suits your applications needs, and sometimes that may also come with distorting the meaning of what that pattern implies.
Not every standard or pattern will perfectly fit into your application, nor should it. You should make changes where needed and break convention when appropriate. This is a matter of judgement. If you think it's simpler to use Repositories as effectively collections of advanced access methods (with application logic in another layer like Services), or collections of application logic. Even both.

Confusion about decoupling, separating of concerns, the framework and my business model

i got a little bit confused about decoupling, separating of concerns, the framework (Symfony2) and my business model. Let me explain :)
In modern web based projects we're supposed to have a thin controller. This seems to be best practice nowadays. Also it seems to be best practice to decouple the framework and the business model. And to do separation of concerns. I'm fine with all of that. Using events/event dispatching works like a charme to solve these concerns.
But now i have a task where i need to do the following things:
read a cookie
save some data to the database based on the contents of the cookie
delete the cookie
First my understanding of working with cookies in Symfony2:
I read the cookie using the request object
I manipulate the cookie using the response object
I should avoid using \setCookie directly
And that's the point where i got confused. Because:
I would assume that all of the three steps are part of my "task" i need to perform. So it would make sense to do all of the stuff in the same class/piece of business model.
I want to avoid mixing up my business model and third party components (like the request/response) as much as possible.
Now i have two options - But both of them are feeling wrong in some way:
Being strict on decoupling framework and business model - Reading/writing the cookie will be left in the controller, since framework components are involved. The persisting is done in the business model. - BUT: Not all the code belonging to the task are in one place now.
I also could have all of the code necessary to perform the task in one place. But then i would need to make the request and the response available within my service, which i try to avoid.
How do you guys handle this kind of issues ?
Thanks,
Stephan
I suppose that you have to make a choice: if you're trying to avoid injection of the request into a service you have to manipulate it into the controller directly.
Of course you could use a private controller that you can call from an arbitrary action and where you can store all the code: that way you could follow the DRY methodology that is always a good practice and you'll avoid injection.
In my vision of symfony however, I would use a service with injection keeping controllers small and not heavy. In that service you could store all business logic related to controller's object manipulation.
This answer, however, could vary from devel to devel so it's hard to find the right methodology
Regarding decoupling from the framework, I wrote a blog post about that here http://thesolidphp.com/decoupling-application-from-framework/
You could separate the cookie handling by creating your own class that will use the Symfony cookie manager. That class should implement an interface like CookieStorage. Your domain objects will only depend on that interface. A concrete implementation could be SymfonyCookieStorage, that will call the Symfony cookie handling objects. Now your business objects are separated from the Symfony cookie manager.
It's the same concept I wrote about in the blog post. That way you could decouple basically everything and keep you objects unaware they are using Symfony.

Advantages and disadvantages of OO code in a typical web application context

I'm interested in hearing about advantages and disadvantages of developing a web application using the OOP paradigm instead of Procedural.
I am NOT interested in
OOP vs Procedural
Contexts other than a typical web application, meaning a distributed application where a client makes an HTTP request to a server
My question is motivated by the fact that I've been developing a web application running on my company's Intranet, and would like this application to be "easily" maintainable by the person who will replace me, eventually, so that the application stay and is not replaced by some over abstracted over engineered paid solution a very few people will enjoy working with.
I posted some bits of my application source for review at codereview from wich I didn't get a lot of feedback. I then posted a link to my post on codereview over at reddit/r/PHP that didn't go really well.
For now, I am under the impression that the vast majority of the "web development" community have decided that OO is the way to go. I'm having a difficult time to understand why BUT I have a feeling that the next dev my company will hire will also be a strong believer in developing OO for a web application as it seems to be the norm nowadays.
I would like to agree with them and join the bandwagon, can someone try and explain to me the advantages and disadvantages of OOP in the typical context of a web application.
While doing some research I came accross this really interesting comment and this one too, wich makes it even harder for me to make the switch.
A small quote from one of the comments:
OOP is for people who can’t properly engineer software or for competent programmers who are involved in very large or complex non-web project. If I were to write an event-driven game to run on a PC, I would not choose procedural programming.
The selling point of a lot of web application frameworks these days is it is an MVC framework. You have the Controller that interfaces with the View and the Model. The model is your business and data layer which contains business objects/entities/data objects - well basically objects that communicate with each other using messages. The objects themselves are restricted to what it is unique to it and only what it can do.
These boundaries/restrictions somewhat make it easier for other people to understand your code and how to modify it. It also helps in unit testing each one of these layers separately.
I suppose if you wanted Rapidly developed application with the controller querying the database and sending information to the view, you could do that too. But the only way to test would be to run the application, check if something breaks, fix, restart it, again test.. You would not be saving a lot of time.
EDIT
You are using a single controller which has business logic in it. But your model looks very much like what an OO model should be. So the question I'd ask is, what happens if I break this controller to be domain specific? I would then have to create a UserController and a DepartmentController and UserController renders all views related to CRUDing Users. Is that worth the trouble? Absolutely. Someone else could jump in and work on AdminController or ReportingController, whatever your application needs without having to worry about changes you are making to this controller.
And if one of you colleagues wants to see some changes done to the Department section, you don't need to worry about the rest.
First of all I'm not a Php person at all but your self praising question seemed interesting so I researched a bit. My answer is general and is not related to a particular implementation of object oriented technology or web technology.
An object encapsulates the data along with the relevant functionality all in a single piece. it is not to say that you encapsulate your whole application inside a single giant object. A lot is related to how you analyze the problem, identity objects and use them.
A web application as a request-response thingy maybe true in early 90s but now the web apps are mature. It is not necessary to follow a typical request-response scenario. Have you seen a stock tracking app? it does not wait for a request to send a response. it sends whenever the data is available. I worked on the online candidate testing web app which asks questions in fixed amount of time. Once the time is up it ends the test whether the user "requests" to end it or not and results are displayed. Even if it user machine is turned off or there is a network issue, it remembers and never asked the same questions again nor extra time was ever given.
Yes there are bad programmers or "IT-guys" who are totally unaware of OO-analysis. They program the object oreinted stuf in a very procedural way. The result of their work is a request-response styled web app with 3 global variables and a 'z' namespace but that does not mean that the blame should go to the OO paradigm itself. It goes to the people who didn't understand it so much for apply it at the right place!

Client-Server Architectural Decision

This is less of a troubleshooting question and more of an industry standards question.
I am at a crossroads where architectural standards need to be addressed and implemented. One of these standards involves the communication route between the client application (AngularJS based, so single-page persistent with multiple views) and third party sources of information.
To me, it seems intuitive and logical to route all requests for third party libraries and data through my backend and then off to various destinations via CURL.
In this way, my server acts as a gateway between the client and the outside world (much like the relationship between a cellphone tower router and a cellphone).
I am curious as to what industry standards would say about this, and the potential pitfalls. To me, it seems like it would create more order, organization, and security long term.
Please let me know what your thoughts are regarding this, as I need outside perspectives.
Not really sure if this counts, as I am not aware of any industry standards - but I interpret it as what you're really asking for is general outside perspective. So here goes:
My short answer is that I think you're on the right track.
I think it's cleaner as it keeps the data path simple in that your client always sends requests to your server - so basically you're getting very loose coupling between your client and everything else (except towards the controller on the server, which is fine, even necessary IMO). Want to change the data source later? Client isn't affected (unless the format differs of course). It's also beneficial if you can picture yourself wanting to store the raw data in a DB for some reason some time in the future. Depending on what services you're connecting to and what you want to do with the data, going through your own server can have security benefits (like if you need to use a private key for authentication against the 3rd party service, like one has to with APIs like those MasterCard offer).
There is a performance hit though, as it gives your server more to do and requires a bit more memory, in addition to the extra requests and DNS look-ups incurred. Then again, you would be in control of caching, so you could possibly make the service slightly more robust in some cases.
So unless performance is paramount, I would go the route you were thinking of. Exactly how the routing is done on your server is a different question and might require some testing. Just make sure you use a method that lets you elegantly handle any errors that might pop up :)

User authentication

If I am to follow What should a developer know before building a public web site? on authentication, then what options do I have ?
I have never used PEAR, and I'm not about to start. I have read about phpGALC but have yet to try it.
After the authentication do rights/access level kick in. I'm not a big fan of using a single tinyint value which decides what a user can and cannot do, besides its not very flexible. I have recently written a section system where I specify what kind of access each user type have access to, but is there something better ?
If you want a language, then PHP5.
Authentication is fairly straightforward. Authorization, through an ACL or whatever, can be complex.
Authentication is usually just matching a username and password with stored credentials. Just use SSL and hash passwords using a salt.
Authorization can be a beast and the solution depends on your requirements. You might try PhpGALC and the Zend Framework ACL component. Both options have roles, resources, and optional privileges although they are all named differently. The Zend ACL is simpler and more generic (rules can be defined simply in your code and it doesn't require a database). If your roles, resources, and privileges are not static, then with the Zend ACL you'll have to write code to populate the ACL from your data store. The big advantage of phpGALC is that it has a web GUI. I found the GUI clumsy, but unless you really understand your ACL, it can be dangerous to make changes directly in the database considering ACL complexities like role and resource inheritance. Keep in mind that the Zend ACL can be used on its own without any other Zend Framework dependencies besides Zend Exception.
ACL and Auth are the things I'm working on at this very moment. I'm using CakePHP at the moment, and it provides an extensive (albeit not simple) module for ACL, and a simple way to do authentication. I'm interested in answers too.
What I've gathered:
Learn to validate input, especially the difference between blacklists and whitelists
Consider carefully your email validation pattern
Consider what languages will you have to support (pesky little accents, tildes and the like get in the way in names, e.g. Añagaza or Alérta).
Roll-your-own or prebuilt?
ACL: keep it simple or it could swallow you whole.
Careful about CSRF and XSRF!
I'm not a big fan of using a single tinyint value which desides what a
user can and cannot do, besides its
not very flexible.
That depends... Are you referring to using the value as an integer or as a bitfield?
If you're using it simply as a number (level 5 user has all the abilities of level 1-4 users, plus a little more), then, yeah, that's not very flexible.
If you're using it as a bitfield, it gives you 8 (sets of) capabilities which can be turned on or off in any combination for any user. I'd call that flexible. And, if 8 capabilities isn't enough for you, it's trivial to change the tinyint (8 bits) to a smallint (16 bits/capabilities), int (32 bits), or bigint (64 bits), which should be more than sufficient for just about any application most of us are likely to write.
Most frameworks have an authentication module built-in. So you may want to checkout Zend, CakePHP, Code Ignighter, etc.
Also one thing that tends to get confusing is the difference between escaping and encoding data. Things are a lot more flexible when data is encoded then escaped.
User Authentication makes sure that if a user tries to access a page which application denies free access, it redirects the user to logging page and after a successful login brings back to the requested page. One such implementation of cake's default Auth is explained in following wrt pitfalls, approach and ways.
http://enbake.com/cakephp-user-authentication-auth-component
The framework doesnt make you restricted. But rather grants you speed of dev with existing modules and more organized code. Can show you comparison b/w frameworks if interested.

Categories