Where to put OAuth logic? - php

I'm using Zend Framework in a project, and I'm creating a controller only for authentication.
In this project we'll accept that a user signs up through a account of other sites like facebook, twitter, myspace, etc.. For this we will be using OAuth. But I'm having a doubt where I should put the logic for each OAuth site related authentication? Only the facebook, for example, occupied 50 lines of code in my controller, and in this way my controllers will not be thin...
I wonder where I should put this.
Create an Zend_Auth adapter for each one of the sites, create a service only to this, what is the best way?
And sorry the poor english. :)

JF Austin has a fairly generic OAuth authentication adapter implementation that uses a Zend_Oauth_Consumer. Creating specific subclasses of this for Twitter, Facebook, etc seems to be straightforward from there. He even seems to have a Twitter adapter already. Use of the adapter is described in his blog post about it.
Alternatively, note this one by Lloyd Watkin.
Upshot: all the OAuth logic is buried inside these adapters. Your controllers can then instantiate this authentication adapter, feed it to Zend_Auth::authenticate($adapter), and then take action based upon the returned result, keeping the controller focused on the higher-level app wiring.

Your OAuth logic should live inside models as should all your buisiness logic. Your controller should be left to do is control the program flow and setup view variables for use in your view script.
Kind regards
Garry

Related

Questions on creating OAuth 2.0 Server

I'm in the process of designing an API to service a browser web app. I want to design the API in a way where if the need arises, it can be used cross platform. For the first stage I want to implement user name and password authentication (I believe the terminology is grant_type = password). I've read up on OAuth 2.0 being a standard in practice and I have a few questions:
Is there a suggested way of binding tokens and token expiry dates to users in the database? Can this be done in one table, or is it better to keep them separate?
I want to polish up and verify username and password authentication works before exploring into having 3rd party authentication (Facebook, Google+, Twitter, etc...) Is there anything I should know ahead of time when creating the database tables and API to make sure it is extendable into these features?
I'm hearing a lot about JWT, is this considered a standard way of generating and returning tokens to the front end?
I am looking to build the api in PHP and I was going to use the implementation from https://github.com/bshaffer/oauth2-server-php but it looks like it is failing on php versions 7 and up. (I'm going to use 7.2 for this project) It may also be easier to create it myself one piece at a time.
Any direction or insight into the above would be greatly appreciated. This will be my first stab at implementing an extendable authentication framework in an app.

Best location in Laravel for third-party API connection

I'm writing a Laravel application using one or more third-party APIs when it suddenly dawned on me. Where is the best place within the Laravel application structure to set up the API connection to consume it from my Controller? Would you use a Service or put the logic somewhere else?
$this->api = new RestApi();
->setUrl(getenv('API_REST_URL'))
->setUsername(getenv('API_USERNAME'))
->setPassword(getenv('API_PASSWORD'))
->connect();
Using services would be the better approach in Laravel, once your third party is not a direct route or content in your API, per se, it should not be in your Controller. You may want to use a Service with Guzzle.
I think the best answer is that it depends on the size of your project and what you are doing.
This post lists 3 of the most common ways. I would go with Method 3 myself (Register the API with the service container), even for simple things. It abstracts it away nicely so should work best in all situations.
https://desertebs.com/laravel/how-to-consume-external-third-party-api-in-laravel-5

Laravel: Combine REST-Controllers with normal controllers and views?

I want to create an new app and for this purpose I've chosen laravel. So I'm also new to laravel.
I want to integrate an API from the beginning for things like browser addons or mobile apps. Of course I don't want to make it an API only app. I'll still need normal views and controllers which will handle this. Now I'm a bit confused about the proper structure. It should output the data as JSON when it's an API request, otherwise as a normal view.
What would be the best way to achieve this? All tutorials are based on API only apps which doesn't help me.
Is it good practice to make UserController.php and ApiUserController.php? Or UserController.php and a subfolder structure like API/v1.0/UserController.php? Wouldn't I repeat things often with this kind of structure? I mean often the only thing changes is the output, isn't it?
Thanks in advance!
Your API should be served on API routes, those can be in the same controller as the other user stuff but they really don't have to be.
I like to use an ApiController with all the API functions in it. In that you can implement stuff like "showUsers" and have it return User::all() or User::paginate(50). If you directly return a Model in Laravel it will output as JSON by default, which is pretty convenient.
Now for some real API goodness, I love using the API package by dingo in combination with artdarek's Laravel OAuth 2 wrapper. It providers really high quality secure API with lots of functionality, like rate limiting and scopes and all that cool stuff.
Dingo's API package
Artdarek's Laravel OAuth wrapper
You really don't want to use RESTful controllers for an API, since you probably want differently named endpoints. I like to keep all users at api/users but single users at user/USER for example. It's just what I prefer, my API should be totally customizable and routable in my opinion.

Architecture: API as core for a website & mobile-app

I have different questions about a full architecture idea. I hope someone with great experience could help me out because I am pretty much getting stuck in all possibilities.
I'm planning to rewrite a community website. Our customer wants to make use of native mobile apps in the future. So I will need to take this into account. Because of this I have decided to create a 100% REST API architecture based on the PHP framework Kohana. I have choosen Kohana because this makes scaling the internal API to a other server very easily without much extra effort. (Kohana threats internal url requests not as HTTP so there isn't much overhead in the beginning and can scale to HTTP with some minor code changes).
At first the API will be private, but later on we might make it public to let more services connect to us easily.
De basic REST structure is as follow:
/cats
/cats/1
/cats/1/custom
'custom' could be 'childs' for instance.
same goes for:
/ads
/bids
/users
/banners
etc..
These are perfect entities for the API because the mobile app will definitely use all this functionality.
So we can conclude the core of the website is REST. So basically I want to make the website a client of the API just like the native app in the future. This way maintenance seems much easier.
What worries me though is the fact that there is much more than this (managing uploaded files, invoicing, automails for invoicing, automails for ads and so on). Uploading files needs to go through the website to the API. Is this common practice? If I do not do this, the website would do upload logic, which makes the site no client anymore and the app itself. Hence the mobile app can't even upload and both API and website need to know the upload folder (duplicate logic).
I thought of creating the following modules:
community-api
community-website
Api seems to be the core then. But.... what about cronjobs etc? Actually they should not be part of the website, as this is just a 'client'. I feel they should interact directly with the model or API. So basically the API gets more like a gateway to the core and thought I need this:
community-core
Models
Cronjobs
Auto Mailings (part of cronjobs)
Invoices etc
community-api
Interact with models in core through HTTP
community-website
Website
Admin
The core cronjobs are a exception to the REST structure. They are the only one that can change data without going through the api. At least that was my idea because they belong in the core and API is on top of the core.
But by design that seems just wrong. Manipulating should only go through the API!
Alternative:
community-core
Models
community-api
Interact with models in core through HTTP
community business
Cronjobs
Auto Mailings (part of cronjobs)
Invoices etc
community-website
Website
Admin
This look better by design to me.
(source: mauserrifle.nl)
Main Questions
1)
Should cronjobs manipulate through the API or Core models?
2)
My invoice cronjob needs a template pretty much the style of main website of course. But if my cronjob is part of business or core it won't have knowledge of my main website. What makes sense to solve this?
3)
My website will be using mustache as a template engine. (both php and javascript can parse these templates). I thought using the api directly for ajax calls but then realized:
The site gets data from api, formats timestamps to dates (Y-m-d) for the template and then renders. If I let javascript call the api directly, javascript must have logic too (formatting). This is duplicate code! Feels like the only solution is calling the website for ajax (which calls the api and formats) and returns the formatted json. Am I right?
But.... simple calls like deleting a ad can go through the api directly (e.g. DELETE: /ads/1
I get a mix of calls....
Any better solution for this?
4)
Overall: Is my architecture too complex? Any alternatives I should consider?
I would love to hear your feedback!
Once I've heard that a good way to develop a web application is to develop an API-Centric Web Application. The thing is, to me, if you couple the main service to the public API, building an API-Centric application, you lose the whole point of developing a public API at all.
This doesn't seem logical to me.
Yes, the API and the website and what ever might come next are separate things and website should be a client to the API itself but since it will simplify things greate, I believe that you should RE-USE the domain-classes to build and base your web-site logic. This way you can use all the same code base and handle all your issues including ads, invoicing and of course file uploads with ease.
For the public API, it should be on a separate box if possible re-using the same domain classes but with different authentication methods so that whatever problem might occur, it won't affect the main service.
Your cron-jobs should only be used to fire the call through the API itself and those calls should be made on the main app (website through the API)
If you build your website without repeating-yourself, as in, using the same code as the base and wrapping the web-app around it, you won't have the issue raising in q#2.
Same thing applies for question number 3. If you wrap the website around the API, the website can use the api itself without being a separate entity.
Your architecture seems complex but if you do these things, it will be simple. ;-)
Good luck!
REST is just one way to initiate a request. Your core code that processes the request shouldn't be tightly coupled to the REST interface, or HTTP for that matter. I would advise designing your REST API as a simple mapper to an include file or something similar. Your cron could then bypass the whole REST API and just include the file directly. Separate the request interface from the code that does the actual processing.

User authentication with CodeIgniter

I am writing a web application using PHP. I want to use the MVC pattern for this, and decided to go with CodeIgniter. My application will have some pages which will require authentication, and some pages won't. I want to design this in a very generic way, so that there should be no code duplication. Can any one point to some good "design/class structure" for this?
Write a custom library that you can autoload in your code igniter app on every page view. It should have functions that:
Authenticate the user ie. check if a user is logged in or not
Log you in ie. set a session variable or something
Log you out
Then in your controller classes you can do a call to the authentication function in the constructor then depending on the outcome continue as normal or redirect them to a login screen with an access denied message.
Do a search on the code igniter wiki for 'authentication' and there are a number of results that may help: http://codeigniter.com/wiki/
"Ion Auth" is lean, well-programmed, somewhat widely used and is actively maintained.
http://github.com/benedmunds/CodeIgniter-Ion-Auth
If by "some pages" you mean some controllers (the gateway to your views), then you may want to investigate controller inheritance. Extend the default CodeIgniter controller with your own and put an authentication check in the constructor (check the session for a logged in flag or something and if not logged in then redirect to login page). Then, all controllers that require authentication will need to extend your new parent controller. That's it.
Head on over to the CodeIgniter forums and search for some different ways to extend the controller. Here is one http://codeigniter.com/forums/viewthread/89768/#452890
May be you can use CL_AUTH library for CI. I've used it and it works good. You can find it here http://www.jasonashdown.co.uk/cl_auth_doc/
I was looking into the same thing recently, and I found a CodeIgniter fork called Kohana that includes a nice authentication module. If you are set on CI, maybe adapting Kohana's auth module backwards to CI would save you some time? If you have just started out on your project and PHP5 is OK to use, consider switching over; they are very similar frameworks.
Visit GitHub and search for Codeigniter Auth or Authentication, or check the CodeIgniter Wiki, you'll find many libraries with different features.. explore them and choose the one you need! But be careful, many are for CI 2, and you have to ucfirst the classes to use with CI 3, otherwise they don't work at all.
Use flexi auth a modified version of the popular Ion Auth library. It's more advanced and do all the job out-of-the-box.
flexi auth is a free open source user authentication/login library for use with the CodeIgniter 2.0+ framework.
I know it's too late but I hope someone else will find it helpful. Cheers!

Categories