Laravel 5.2: Adding Extra Checks at Authentication

This quick post will be about changing the built-in authentication to include more checks beyond username and password. In this post, we will be specifically checking that, along with the correct username and password, the active field, in the users table, must also be equal to 1 (users.active = 1).

Quick Answer

Just add the following to your app\Http\Controllers\Auth\AuthController.php file:

Above, I want the authentication to also check that the user’s active field is set to 1. If your user status check is different, make sure that you change these values.

Long(er) Answer

The getCredentials() method, from the AuthenticatesUsers trait, builds an associative array and sends it to be checked by another function (SessionGuard:attempt) . By default, it will only send the username and password and the attempt() function will loop through the items in the $credentials array, and build a database query from it. We will override the getCredentials() method and add our extra additional check to the $credentials array.

Add this code to your app\Http\Controllers\Auth\AuthController.php file:

Now test it by setting your user’s status to something invalid, and see if you can still log in or not.

Enjoy 🙂

Posted in Dev, Laravel, PHP | 1 Comment

Laravel 5.2 – Using Custom Config Variables

Quick tip: If you need to store a custom configuration value, that you can call from any Controller, then just do it like this:

1. Add the variable 'key' => 'value'  pair to /config/app.php like so:

The value could also be an array:

2. Then to retrieve the stored value, we can use the config  command, using the examples above, I would do:

If you want to have a default value to use, in case your key didn’t return anything, then just add it as a second argument to the config  command, like so:

Enjoy!

Posted in Dev, Laravel, PHP | Leave a comment

Installing Laravel 5.2 on Ubuntu 16.04 and Apache2

This post will document how I installed Laravel 5.2, on Apache2 on an Ubuntu 16.04 server. Will will also install MySQL, as we will need a database, and PHP which is required by Laravel. This will be the starting point of most of my posts, so if you’re following along from scratch…this is “scratch!”

First thing you need, of course, is the Ubuntu 16.04 server, with an SSH connection. Follow these excellent instructions and get yourself sorted out with one. Make sure you also give the server a static IP address (step 8., in the linked instructions). Come back when you’re done.

Welcome back! Lets get started.

Connect to your server now, using SSH, on your terminal.

1. Install Apache2 Web Server

The Apache server will run on Ubuntu and allow us to host websites. We will need to use “sudo” so that we have the correct permission to install it. Enter your user’s password when it asks for it. Run the following commands:

If you enabled the UFW firewall, then you must add a rule to allow traffic to the Apache2 server by running the following command:

Now use your web browser and test the Apache installation. Do this by going to the server’s IP address. In my case, this was 192.168.1.147. Insert your server IP address, of course, and not mine! 😛

url

If all is well, your browser will load the default “It Works!” page. Well done!

apache_hello

While we’re here, let’s enable mod_rewrite that Laravel will need later. Run the following commands in your terminal:

Upwards and onward!

2. Install MySQL server

Although Laravel 5.2 is supports many different types of database, I will be using MySQL for all my posts. If you are going to use a different type of database, then feel free the skip this section.

Go back to your terminal connection and run the following command:

When you are asked to set a MySQL root password, please do so. Don’t leave it blank.

3. Install PHP

Laravel 5.2 requires the following packages installed:

  • PHP >= 5.5.9
  • OpenSSL PHP Extension
  • PDO PHP Extension
  • Mbstring PHP Extension
  • Tokenizer PHP Extension

Run the following command to make it all happen:

We also included php7.0-zip  as this will be required by Composer, and
php7.0-xml which is required by PHPUnit (required to create a new Laravel project).

4. Install Composer

Laravel uses Composer to handle all its dependencies, so we need to install this next, by running the following command:

Note that this is for a global install. If you want to install it locally, just follow these instructions.

5. Install Laravel

We will use Composer to get Laravel, then add it to the PATH, so we can use Laravel commands anywhere. Run this command now:

And add it to the PATH:

If for some reason your installation doesn’t have  ~/.bashrc, you can use ~/.bash_profile  instead.

Restart apache now with:

6. Create a Laravel Project and configure

Now in order to create a new Laravel project, just use the laravel new command, followed by the directory name. For example, laravel new monkey will create a new Laravel project, in the directory monkey . Let’s create a new project now at  /var/www/html/ .

If you are hit with a permissions problem, make sure that you have correct permission to use the directory ( in this case html ).

We now have to make sure that a couple of directories, /storage  and /bootstrap/cache  are accessible by Apache2. We do this by running the following command:

Make sure you change “project” to whatever you named your own project.

7. Apache Virtual Host

To get Apache to serve up the correct page to your browser, we need to create a Virtual Host for our Laravel project. First thing to do is to go to the depth of Apache and copy the default configuration file, like so:

Use your favorite text-editor, I will be using VIM, and open up the copy you just made:

Now edit your copy of project.conf as below. If you are following along with VIM, then you need to press “i” to start editing the file. Note that I have removed all the comments just to make it clearer:

Again, if you are using VIM, click “esc” (the escape key) to come out of insert mode, then click :wq (colon w and q) to save the changes to you have made and quit VIM.

A quick note regarding some of the lines above. ServerName  is what you will type into the browser to reach your Laravel project’s first page. If you are not using a domain for this, then you can put whatever you want as the ServerName. If you do have a domain, then use that instead. DocumentRoot  and Directory are set with the structure that I have been using in this post, if yours differ, then please adjust as appropriate.

Now enable this new virtual host, disable the default one and reload Apache2:

For those who are not using a registered domain name, a final step is required. We need to change our computer’s host file so that entering http://local.project.com will tell our browser to go to our server, and not look for project.com on the internet.

On my Windows 10 machine, the hosts file is at C:\Windows\System32\drivers\etc\hosts . Once there, we’re going to add our server’s IP address (set when we were installing Ubuntu at the very beginning of this post) and the value we set for ServerName in the virtual host conf file (earlier in this step) to it:

The hosts file tends to have some crafty security added to it, so make sure you running your text-editor (notepad etc.) as administrator to edit it.

Now go back to your browser, enter the address you gave your project, and view the default index page in all its glory!

2016-08-03 12_59_22-Laravel

Posted in Dev, Laravel, PHP | 7 Comments

Laravel 5.2: Getting started

Please note. Like everything on this website. These posts are merely to allow me to document my journey through various tasks. It will not cover everything, nor be well written. There are definitely better resources out there, please consider using them instead!

Also: This specific post will very much follow the Intermediate Task List on the Laravel site. I have not had an original thought since 1980.

Getting Ready

In order to play, make sure that you have completed the following:

  1. Installed Laravel, created a project and performed the required permission edits.
  2. Create a database, a database user, and edit the .env  file to allow Laravel access.
  3. Tell your significant other that you love them. 🙂

Prepping the database

Laravel’s Artisan and Migration tool is like version control for your database. It allows you to define a structure for your database so that everyone can start on the same page.

This little project will be dealing with user accounts and authentication, and a todo list, our database will need a users and a tasks  table.

A basic structure for the users  table has been automatically created by Laravel, so we don’t need to manually create it.

Use the following command to create the framework for the tasks  table:

A need migration file for the tasks table has now been added to the  database/migrations folder of your project. The migration tool has already added code to create an incrementing ID column, as well as code to create timestamp columns for us. Our tasks table will need to have a column holding the user_id of who created the task, and a column to hold the name of the task itself.

Edit the file with the name ending in  create_task_table.php so it looks like the example below:

Now to run the migration, which creates the actual table(s) in the database, with the following command:

Use your database client to have a look at the newly created tables.

Models (Eloquent part I)

Eloquent is a tool that will help us to work with the database via our “models.”

The user  model has already been created by Laravel. It can be found at  app/User.php . Nothing else to see here…move along.

The task  model will now be created by us, using the following command:

An empty app/Task model file will have been created for you.

Since every table is guarded against mass-assignment, so we have to specifically state that the  name attribute is mass-assignable. This is done by added the table name to the special $fillable array;

Relationships (Eloquent part II)

Now our required models are defined, we need to tell Laravel how the user  and task tables relate to one another. One user can have many tasks, but a task can only belong to a single user (no sharing yet!). So we set this one-to-many relationship in the models.

First, edit the User  model to add its relationship to the tasks  model:

Now edit the Task  model to state how it relates to the User  model:

Now our relationships have been defined!

Routing

Routes in Laravel are defined in  app/Http/routes.php . Here we will be introducing controllers and using them to handle most of our routes.

Our  / route is currently already defined to return a view template, which we will be defining later.

Authentication

Laravel has already created a special controller at  app/Http/Controllers/Auth/AuthController.php .  This controller uses a special AuthenticatesAndRegistersUsers  trait which will be use in creating and authenticating users.

We still need to created the required views and define route that will point to the correct controller. We can do this by using the following command:

The command has created a bunch of new views for us. Now we need to create the routes for our authentication needs. Luckily, this is very simple. Edit your app/Http/routes.php  by adding the following line within the  ['middleware' => ['web']]route group:

The Task Controller

We will be retrieving and storing tasks, so we will be using a Task Controller. Let’s use the Artisan tool to create a new controller for us. Use this command to create a new controller in the  app/Htpp/Controllers  directory:

Now create some stubs in the app/Http/routes.php  file to point to the new contoller. Remember to put these in the ['middleware' => ['web']] route group also:

Authenticating All Tasks Routes

We want all task routes to only be available to users who have logged in (authenticated). Laravel uses the middleware method to make this simple.  Let’s add the auth  middleware to the controller’s constructor so that all TaskController actions will require the use of this middleware.

Layouts and Views

The first thing we are going to do here is to create a basic layout that will hold the common features which appear on most pages. The is done by creating a layout view that uses the Blade template engine.

Create a new layout view in  resources/views/layouts/app.blade.php  with the following content:

The only line that is not HTML,  @yield('content') , is a special blade directive. It specifies the location for displaying the contents of any child page that extends this layout.

Child View

Now we are going to define out view that will have the form for adding tasks and a table listing all tasks already in the system. The Bootstrap CSS stuff, used to make it all pretty, is included but has been labeled as such. It’s not laravel and you can ignore it if you want.

The first line, @extends('layouts.app')  shows that this view is extending the layout we defined earlier at  resources/views/layouts/app.blade.php . So anything between @section('content')  and @endsection   will be displayed at the @yield('content') directive in the app.blade.php  layout.

The @include(‘common.errors’) directive, at line 14 above, will load a template located at  resources/views/common/errors.blade.php  (which we will define later). Not surprisingly, this file will handle the retrieving and displaying of error messages.

Now we have a basic layout and view, let’s add an index method, which will return this view, to our TaskController .

Adding Tasks

Now we will add code the store  method to our TaskController . This method will be able to validate and store the user input. Since we are using a controller to do validation, validation failures are automatically redirected back to where it came from, and errors are flashed into session for us.

The $errors  Variable

In our tasks view, at resources/views/tasks/index.blade.php , we used the @include('common.errors)  directive to render any validation errors that might occur. Let’s create the view now:

The $errors  variable is available in every Laravel view. It will be an empty instance of the viewErrorBag  object if no errors have occurred.

Creating The Task

With validation implemented, we are now going to add code to our TaskController@store  that will allow a task to be created, then redirect the user back to /tasks .

Using relationships between models will usually expose a create method, which accepts an array of attributes and will automatically set a foreign key, in the case the user_id ,  before adding the data to the database.  We can access this value using  $request->user() :

Display Existing Tasks

We will be using dependency injection to inject a TaskRepository (more on this below) into our TaskController .

Dependency Injection

Creating The Repository

The TaskRepository  will hold all our data access logic for the Task  model. This will make it simple to share Eloquent queries across the platform, if required in the future.

Create an app/Repositories  directory and add a TaskRepository  class.

Injecting The Repository

Now we have our repository defined, we will use it as a type-hint for our $tasks parameter of our Task constructor. We can then use it in our index route, to only return tasks for the current, authenticated, user. (Using the forUser  method that we created in the TaskRepository  file.

Displaying The Tasks

Now we will update our index.blade.php to include code to display the current tasks. Replace the <!-- TODO: Current Tasks -->  comment with the following code.

Deleting Tasks

Adding The Delete Button

We left a “TODO” note in our code where we will be adding the delete button. It will be in the shape of a small single-button form and will send a DELETE /task request to our TaskController@destroy method:

The method_field('DELETE')  function will generate the following hidden input:

This will allow us to spoof the form’s method so that we can respond to the form’s request using a Route::delete  route.

Route Model Binding

Remember our route declaration for the delete route? It is like this:

Laravel has a clever way to inject entire model instances into the route. It will automatically resolve type-hinted Eloquent models defined in the controller action. So our destroy  method can look like this:

Since the parameter $task  is type-hinted as type Task , Laravel sees that it matches the {task}  segment of the route’s URI (above) and will automatically inject the model instance with an ID matching the vakue in the request URI. If a matching instance is not found, a 404 HTTP error will be generated.

Authorization

Now we have the Task  instance injected into the destroy method, but we still need to make sure that only the task’s owner can destroy the task. Otherwise anyone can try to make requests with random IDs to the /task/{task}  URL. We do this by using Laravel’s authorization capabilities.

Creating A Policy

Laravel uses small classes as “policies” for organizing authorization logic. Usually there is a policy for each model, so let’s use the Artisan CLI to generate a TaskPolicy  for our Task  model:

Now let’s add a destroy  method to the shiny new policy file which Laravel created for us in app/Policies/TaskPolicy.php . This method will receive a User  instance and a Task  instance. The method, like all policy methods, should simply return true  or false . In our case, the method will check if the user’s ID matches with the task’s user_id :

HOWEVER!!! For some reason, $task->user_id  returns the user_id as a string, while $user->id  returns a integer. This means that the ===  evaluation always return a false  and therefore deleting a task is never authorized.

There are several ways to fix this, such as casting everything as integers  or using the == operator instead, but the most logical way that I found was to change the return  line as follows:

Now we need to associate this TaskPolicy  policy to our Task  model. Add the following line to the app/Providers/AuthServiceProvider.php  file’s   $policies  property.

Authorizing The Action

Now that our policy is written and associated with the model, let’s use it in our TaskController@destroy  method. We will use the authorize method, which takes two arguments: the name of the policy we want to call, and the model instance that we are wanting to authorize. Edit you destroy method now so it looks like the code below:

If the action is authorized (i.e. our policy’s destroy  method returned true ) then the code will continue normally, otherwise it will throw a 403 exception and an error page will be displayed.

Deleting The Task

Let’s finish this destroy  method by actually deleting the task. We use Eloquent’s delete method to delete  the model instance in the database, then redirect the user back to the /tasks  page:

 

Posted in Dev, Laravel, PHP | Leave a comment

Installing Laravel 5.2 on Ubuntu 15.10 and Apache2

First off, I’d like to mention that there is a “highly recommended” virtual machine that comes with Laravel itself. So perhaps you really should be using that.

Moving on…

Install PHP and required extensions

Minimum requirements for your PHP installation are as follows:

  • PHP >= 5.5.9

Check this by going to the command-line and doing:

  • OpenSSL PHP Extension
  • PDO PHP Extension
  • MbString PHP Extension
  • Tokenizer PHP Extension

Use the following command to check your installed extensions:

Installing Composer

Laravel also uses Composer so install that by using the following command:

Note that this is for a global install. If you want to install it locally, just follow these instructions.

Get Laravel and Add To PATH

Let’s use Composer to download the Laravel installer:

Then add it to our PATH, so that we can call the Laravel executable from anywhere:

If for some reason your installation doesn’t have ~/.bashrc , you can use  ~/.bash_profile  instead.

Now in order to create a new Laravel project, just use the  laravel new command, followed by the directory name. For example,  laravel new monkey  will create a new laravel project, in the directory  monkey

Laravel Configuration

The minimum amount of configuration that I had to do before I was able to get the Laravel 5 logo to show on my browser was to make the  storage  and bootstrap/cache  directories are writable by Apache.

Don’t forget to change the “monkey” directory to whatever you called your project earlier.

 

Apache Virtual Host

There are numerous ways of setting up the Apache2 Virtual Host and one must be careful about which guide to follow, as the exact method is changed (slightly) over the course of Apache updates. The following steps are what I did to get it working on my clean Ubuntu 15.10 installation. YMMV (Your Migraine May Vary).

First thing to do is to create a copy of the default host:

Then open the new file with your favorite text-editor (using sudo):

I have removed all the comments, but this is what you want to end up with:

Enable this new virtual host, and disable the default one.

Then restart Apache

Loading the page with a web browser should now proudly display the Laravel 5 logo.

*high-fives all around*

But wait, belay that order! Since most (if not all) of the projects I work on require some sort of user authentication, I am going to add instruction for it to this post (and link back to it ad infinitum).

To get Laravel to build user registration, and authentication, run this code, at the root folder of your project:

Refresh the browser and you will see that the home page now has a working log in and registration page.

Now it’s time for the high-fives….*sniff* so proud…

Posted in Dev, Laravel, PHP | Leave a comment

Installing Node.js on Ubuntu 15.04

Everything I know about how to do this I got from this page, on linoxide.com.  So, really, you might as well go there and save us all some embarrassment.

Still here? Well…let’s do this thing then.

Similar to my previous post on getting Node.js on Ubuntu 14.04.2, we will be installing using the Node.js source code. The reason we do this, instead of using  apt-get install,is because we want the newest version of Node.js to play with. The version that is available via apt-get tends not to be current.

1. Update system and get required tools:

 

2. Go to the Node.js download page to get the URL for that latest release then use wget to download it to your server.

2015-08-28 07_54_00-Node.js

(This was the latest version available to me. Your version might differ from this).

3. Expand the tarball, go into the directory and install

While waiting (as this takes a while) go make coffee, call your loved ones, write that one novel you have inside of you. Once make is complete, run the final command:

4. Test your installation

Check the version that is installed, and run some basic code.

2015-08-28 08_13_30-george@mean_ ~_node-v0.12.7

5. Clean Up

We don’t need the source code or the tarball anymore. We can delete them.

Posted in Uncategorized | Leave a comment

Android Studio 1.2.1.1 – “Aidl is missing ” error

After installing the Android Studio 1.2.1.1 and creating a blank project, I was face with several problems. The first one was that the Gradle gave an error which cause the build of the..erm…blank project to fail.

gradle_aidl_error

Being entirely new to Android development, including the use of Android Studio, I had no idea what this was even for. I barely even looked at it, and it’s already broken. It’s going to be a long day.

Solution:

1. Right-click on the root “app” folder of your application, then go down to “Open Module Settings”

gradle_aidl_error2

2. Select 22.0.1 from the “Build Tools Version” drop-down select box, then click OK.

gradle_aidl_error3

 

3. Gradle will now rebuild the project and the error should disappear. Take a deep breath, and move on to the next error.

Posted in Uncategorized | Leave a comment

Installing Node.js on Ubuntu 14.04.2 server

I know there are many posts and articles on this subject already but I am simply documenting exactly what I did so that I have a reference when, knowing my luck, I have to install the MEAN stack on (many)  more servers in the future. Continue reading

Posted in Dev, MEAN | Leave a comment

MongoDb 2.6.10 does not play well with Ubuntu 15.04

Trying to launch MondoDb 2.6.10 with Ubuntu 15.04 will result in an error:

$ sudo service mongod start
Failed to start mongod.service: Unit mongod.service failed to load: No such file or directory.

That’ll teach you to use the very latest version of everything. Damn kids these days! Continue reading

Posted in Dev, MEAN | Leave a comment