Laravel 5.0 Authentication JWT and AngularJs

# Setup Project
We going to create the project and install the resources

### JWT and Cors
<pre>
composer create-project --prefer-dist laravel/laravel login-project "5.0.0"
composer require tymon/jwt-auth
</pre>

Continue with this link [Jwt-Intallation](https://github.com/tymondesigns/jwt-auth/wiki/Installation)

In the **require** of composer.json we going to add
<pre>
"asm89/stack-cors": "dev-master as 0.2.2",
     "barryvdh/laravel-cors": "^0.7.3"
</pre>

on  config/app.php inside of providers add
<pre>'Barryvdh\Cors\ServiceProvider'</pre>
Execute 
```composer update```


in kernel.php comment
```'App\Http\Middleware\VerifyCsrfToken',```
and add inside of $routeMiddle
<pre>
'jwt.auth' => '\Tymon\JWTAuth\Middleware\GetUserFromToken',
'jwt.refres' => '\Tymon\JWTAuth\Middleware\RefreshToken'
</pre>


### ApiAuthController

Create controller
```php artisan make:controller ApiAuthController```
add to ApiAuthController
*use Tymon\JWTAuth\Facades\JWTAuth;*

```
<?php namespace App\Http\Controllers;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Tymon\JWTAuth\Facades\JWTAuth;

use Illuminate\Http\Request;

class ApiAuthController extends Controller {
    public function userAuth(Request $request) {
        $credentials = $request->only('email', 'password');
        $token = null;


        try{
            if(!$token = JWTAuth::attempt($credentials)){
                return response()->json(['error' => 'invalid credential']);
            }
        }catch(JWTException $ex){
            return response()->json(['error' => 'something went wrong']);
        }
        return response()->json(compact('token'));
    }
}

```

### Seed
With Laravel 5.1 and after, we can do
```php artisan make:seeder UserTableSeeder```
but with Laravel 5.0 we need create manually
copy *database/seeds/DatabaseSeeder.php* 
to  *database/seeds/UserTableSeeder.php*
rename the class to *UserTableSeeder*

```
<?php

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;

class UserTableSeeder extends Seeder {

	/**
	 * Run the database seeds.
	 *
	 * @return void
	 */
	public function run()
	{
		Model::unguard();
        $users = [
            [
                'name' => 'Kevin',
                'email' => 'kev@mail.com',
                'password' => Hash::make('123')
            ]
        ];

        foreach($users as $user){
            \App\User::create($user);
        }
	}
}

```

on Databaseeder.php uncomment
```$this->call('UserTableSeeder');```

```composer dump-autoload```

Configure .env for database

<pre>
php artisan migrate
php artisan db:seed
</pre>

Add the route on *routes.php*
<pre>
Route::group(['middleware' => 'cors'], function(){
    Route::post('/login','ApiAuthController@userAuth');
});
</pre>
### Test Restful

I used a firefox addon [REST-easy](https://addons.mozilla.org/en-US/firefox/addon/rest-easy/)

![Page-Shot-2016-10-17 REST Easy.png](https://qiita-image-store.s3.amazonaws.com/0/91692/41a9db03-fdeb-f313-c9bc-cd331bb70302.png)





### Setup Angular
I want to use directory */public* and use bower

<pre>
prompt/public/> npm install -g bower
prompt/public/> bower install angular angular-route satellizer
prompt/public/> mkdir js && touch js/app.js
</pre>
Edit the file app.js

Aqui va la imagen con el codigo


```mkdir public/views/ 
touch public/views/login.html```

**public/js/service/authservice.js**

<pre>
angular.module('apiLogin')
    .factory('authUser',function($auth){
        var login = function (loginForm){
            $auth.login(loginForm).then(
                function(response){
                    console.log(response);
                },
                function(error){
                    console.log(error);
                }
            );
        };

        return{
            loginApi: function(loginForm){
                login(loginForm);
            }
        };
    });

</pre>
**public/js/controller/loginController.js**

<pre>
 angular.module("apiLogin")
    .controller("loginController", ["authUser", function(authUser){
        var vm = this;
        vm.loginForm ={
            email:'kev@mail.com',
            password:'123'
        };

        vm.login = function(){
            authUser.loginApi(vm.loginForm);
        };
    }]);
</pre>



**public/js/app.js**
<pre>
angular.module("apiLogin", [
        'satellizer',
        'ngRoute'
    ])
    .config(function($authProvider){
        $authProvider.loginUrl= 'http://localhost:8000/auth_login';
    });

</pre>

vista login **public/login.html**


```
<head>
	<meta charset="utf-8">
	<title>Login</title>
    <link rel="stylesheet" type="text/css" href="bower_components/bootstrap/dist/css/bootstrap.css">
    <link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body ng-app="apiLogin">
<div class="container" ng-controller="loginController as login">
<div class="row">
<div class="col-md-12 text-center">
  <h3>Login</h3>
</div>
</div>
  <form>
    <div class="form-group">
      <input type="email" class="form-control" placeholder="Email" ng-model="login.loginForm.email">
    </div>
    <div class="form-group">
      <input type="password" class="form-control" placeholder="Password" ng-model="login.loginForm.password">
    </div>
    <button class="btn btn-primary" ng-click="login.login()">Log in</button><br>
  </form>
</div>
<script src="bower_components/angular/angular.min.js"></script>
<script src="bower_components/angular-route/angular-route.min.js"></script>
<script src="bower_components/satellizer/dist/satellizer.min.js"></script>
<script src="js/app.js"></script>
<script src="js/services/authService.js"></script>
<script src="js/controllers/loginController.js"></script>
</body>
```

![Screenshot_20161011_003912.png](https://qiita-image-store.s3.amazonaws.com/0/91692/61bafb2a-fd73-a4da-4e5c-5baa156265cb.png)

**homeController.php**

```
public function index()
{
     // return view('app');
     return redirect('app.html');
}
```

Modificar en homecontroller redirect to app.html

**login.html**

~~~
<body ng-app="apiLogin">
<div class="container" ng-controller="loginController as login">
<div class="row">
<div class="col-md-12 text-center">
  <h3>Login {{a}}</h3>
</div>
</div>
  <form>
    <div class="form-group">
      <input type="email" class="form-control" placeholder="Email" ng-model="login.loginForm.email">
    </div>
    <div class="form-group">
      <input type="password" class="form-control" placeholder="Password" ng-model="login.loginForm.password">
    </div>
    <button class="btn btn-primary" ng-click="login.login()">Log in</button><br>
  </form>
</div>
<script src="bower_components/angular/angular.min.js"></script>
<script src="bower_components/angular-route/angular-route.min.js"></script>
<script src="bower_components/satellizer/dist/satellizer.min.js"></script>
<script src="js/app.js"></script>
<script src="js/services/authService.js"></script>
<script src="js/controllers/loginController.js"></script>
</body>
~~~

**app.js**

```
angular.module("apiLogin", [
        'satellizer',
        'ngRoute'
    ])
    .config(function($authProvider){
        $authProvider.loginUrl= 'http://localhost:8000/auth_login';
    });

```

**authService.js**

```
angular.module('apiLogin')
    .factory('authUser',function($auth){
        var login = function (loginForm){
            $auth.login(loginForm).then(
                function(response){
                    console.log(response);
                },
                function(error){
                    console.log(error);
                }
            );
        };

        return{
            loginApi: function(loginForm){
                login(loginForm);
            }
        };
    });

```

**loginController.js**

```
angular.module("apiLogin")
    .controller("loginController", ["authUser", function(authUser){
        var vm = this;
        vm.loginForm ={
            email:'kev@mail.com',
            password:'123'
        };

        vm.login = function(){
            authUser.loginApi(vm.loginForm);
        };
    }]);

```


# Resource

https://github.com/tymondesigns/jwt-auth
[Issue with cors in laravel 5.0](https://github.com/barryvdh/laravel-cors/issues/81)
[Differente php artisan dump and composer dump](http://stackoverflow.com/questions/20274082/what-are-differences-between-php-artisan-dump-autoload-and-composer-dump-auto)

The videos in Spanish by KDCToturiales

* [video 1 Sistema de Autenticacion JWT con AngularJS y Laravel ](https://www.youtube.com/watch?v=tTYrAa9VUMA)
*  [video 2 Sistema de Autenticacion JWT con AngularJS y Laravel ](https://www.youtube.com/watch?v=Utld9evRMAo)

 I need finish video 3... soon
*  [video 3 Sistema de Autenticacion JWT con AngularJS y Laravel ](https://www.youtube.com/watch?v=rCIwUJWbhaM)