A simple Login&Auth project with Slim Framework 4
Usually, when you want to develop a simple project in PHP, you have two options: vanilla PHP or use a framework.
I’m not a PHP dev, but do some little projects sometimes. Seems that the most popular framework for PHP is Laravel. I took a crash course on Laravel and it’s really great, but maybe overkill for a small project.
So I googled for more lighter frameworks and I found Slim Framework. It sounded good, so I studied it a bit and did my first project.
I may be wrong, but it feels like a mini-Laravel. It’s simple, but has some strong and complex concepts.
My needs where simple in this project: a login page and some protected forms to read/save data. when searching for examples, I notice that there are few login&auth examples, and those I found were complex (more than I was looking for). So I decide to share my final solution, because it works and it is simple.
All the basic code to bootstrap the login&auth project can be found in https://github.com/mcvendrell/SlimFramework4LoginAuth
NOTE: I didn’t protect the password in the database, everything is in clear text for the shake of simplicity. In a real project you always need to encrypt passwords. Even, if possible, all sensible fields such as emails, names, etc.
The basic concepts
I decided, in order to not to complicate the project, to use PHP session to check for an authenticated user, and to use a middleware in Slim to check for valid routes.
The basic idea is:
- Get current session, if it exists, and check if it is valid (I set a timeout of 5 minutes).
- Check if the user is authenticated or if the current route is allowed to be used without auth. If not, redirect to the login page.
- Any other case, the app works as usual: App tries to get the route, the route has a controller, the controller uses a model to retrieve data and a response is made.
Very simple. This little code does the auth validation trick. It is a middleware (a piece of code that is executed on every http before/after the the App code) that intercepts http request and validates all the needs to continue.
The key part is the line $publicRoutesArray = array('root', 'apiLogin');
where you define the routes that are allowed to be navigated without auth.
The other key part is in the LoginController, where the user/pass is checked and the session is saved (or killed) if all is right.
I think the skeleton is simple enough to be followed by anyone, and code has a lot of comments, but if you have any question, feel free to ask. From this base code, you can complicate things as much as you want.