Bastien Donjon

Développeur web à Bordeaux

Monthly Archive: April 2014

Thursday

24

April 2014

0

COMMENTS

Basic authentification with AngularJs and Laravel

Written by , Posted in Javascript, PHP

Here’s a simple solution to install basic authentication system with AngularJs.

This is a subject that is not much developed. Probably because of the different authentication methods and functional needs.

For me I needed:
– Authentication Required
– To authenticate the user on my RESTful API
– Not to send the user name and password to each request
– Not to make cross-domain
– To have a persistent connection (F5 or close browser window)
– To block access to the application if the authentication server is lost

Laravel configuration

route.php
// Route with basic authentification and custom method
Route::group(
    [ 'before' => 'auth.basicCustom' ], function () {
        // User authenticate with sesssion
        Route::post('authenticate', function(){
            echo 'ok';
        });
    }
);

// Logout current user
Route::get('/logout', function(){
    Auth::logout();
});

// Check state of current user authentification
Route::get('/guest', function(){
    if(Auth::guest()){
        throw new \Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException('x-Basic')
    }else{
        echo 'ok';
    }
});

filters.php

Route::filter(
    'auth.basicCustom', function () {
        $credentials = [ 'email' => Request::getUser(), 'password' => Request::getPassword() ];

        if (!Auth::check()) {
            if (!Auth::once($credentials)) {
                throw new \Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException('x-Basic');
            }
        }
    }
);

Configuration AngularJs

app.js

angular.module('App', [
    'LocalStorageModule',
    'authServices'
  ])

  .config(['$httpProvider' ,
    function ($httpProvider) {

      /* -- Add your routes or states -- */

      // Authentification provider
      $httpProvider.interceptors.push('authInterceptor');
  }]);

authInterceptor.js

'use strict';

/**
 * Authentification Services
 */
angular.module('authServices', [])

  /**
   * Add callback after/befor http request
   */
  .factory('authInterceptor', ['$rootScope', '$q', '$window', 'localStorageService',
      function ($rootScope, $q, $window, localStorageService) {
        return {

          /**
           * Before request
           * @param config
           * @returns {*}
           */
          request: function (config) {
            config.headers = config.headers || {};
            return config;
          },

          /**
           * After success request
           * @param response
           * @returns {*|Promise}
           */
          response: function (response) {
            return response || $q.when(response);
          },

          /**
           * After error request
           * @param rejection
           * @returns {Promise}
           */
          responseError: function (rejection) {
            localStorageService.add('authenticate', false);
            $rootScope.authenticate = false;
            return $q.reject(rejection);
          }
        };
    }]);

userController.js

angular.module('App')

  .controller('UserCtrl', ['$rootScope', '$scope', '$http', '$window', 'localStorageService',
    function ($rootScope, $scope, $http, $window, localStorageService) {
      $scope.submit = function () {
        $http
          .post('/api/authenticate', {}, {
            // Forcage du type d'authentification
            headers: {
              Authorization : 'Basic ' + btoa($scope.user.username + ":" + $scope.user.password)
            }
          })
          .success(function (data, status, headers, config) {
            localStorageService.add('authenticate', true);
            $rootScope.authenticate = true;
            // Suppression des informations utilisation pour ne pas les garder en claire dans le scope
            delete $scope.user;
          })
          .error(function (data, status, headers, config) {
            localStorageService.add('authenticate', false);
            $rootScope.authenticate = false;
          });
      };
  }]);

directives.js

'use strict';

angular.module('App')
  .directive('ngLogin', function () {
    return {
      restrict: 'E',
      templateUrl: 'partials/login.html'
    };
  });

login.html

<div id="login-wrapper">
    <table>
        <tbody>
            <tr>
                <td>
                    <form id="login-form" role="form">
                        <div class="form-group"><a id="login-logo" href="#/"><img alt="Chilican" src="/images/logo.png" /></a></div>
                        <div class="form-group">
                              <label for="userEmail">Adresse email</label>
                              <input class="form-control" id="userEmail" type="email" name="user" placeholder="ex : email@domain.com" />
                        </div>
                        <div class="form-group">
                              <label for="userPassword">Mot de passe</label>
                              <input class="form-control" id="userPassword" type="password" name="pass" />
                        </div>
                        <button class="btn btn-default" type="submit">Se connecter</button></form>
                 </td>
             </tr>
       </tbody>
   </table>
</div>

sources :

Thursday

3

April 2014

0

COMMENTS

Basic authentification with EmberJs and Laravel

Written by , Posted in Javascript, PHP

The following example uses the ember-simple-auth plugin. This is an early implementation for the Basic authentication with Laravel session and RestFul Api.

Currently, it can :

  • Require authentication to the IndexRoute and DashboardRoute
  • Refresh authentication if you refresh the page

Not being a specialist EmberJs this code is incomplete like :

  • Retrieving information form
  • Error handling in a loss of authentication with an API call
  • Proper use of the accessToken property

For safety reasons use the HTTPS protocol.

I am at your service if you have any comments or questions.

Ember configuration

Template : login.hbs

</pre>
<form action=""><label for="identification">Login</label>
 {{input id='identification' placeholder='Enter Login' value=identification}}
 <label for="password">Password</label>
 {{input id='password' placeholder='Enter Password' type='password' value=password}}
 <button type="submit">Login</button></form>
<pre>

app.js


// Defining a custom authentication with Basic method.
var CustomAuthenticator = Ember.SimpleAuth.Authenticators.Base.extend({
    // Check session if you refresh browser (F5)
    restore: function(properties) {
        return new Ember.RSVP.Promise(function(resolve, reject){
            Ember.$.ajax({
                url: 'http://localhost.com/api/guest',
                success : function(datas){
                    resolve(properties);
                },
                error: function(datas){
                    reject();
                }
            });
         });
    },
    // Initialized authentification
    authenticate: function(options) {
        return new Ember.RSVP.Promise(function(resolve, reject){
            Ember.$.ajax({
                url: 'http://localhost.com/api/profile',
                success : function(datas){
                    resolve({accessToken : 'fddfgdfgfdgfg'});
                },
                headers: {
                    "Authorization": "Basic " + btoa("email4@domain.fr:password4")
                }
            });
        });
    },
    invalidate: function(options) {
        return new Ember.RSVP.Promise(function(resolve, reject){
            Ember.$.ajax({
                url: 'http://localhost.com/api/logout',
                success : function(datas){
                    resolve({accessToken : 'fddfgdfgfdgfg'});
                }
            }).then(function(response){
                Ember.run(resolve);
            }, function(xhr, status, error){
                Ember.run(reject);
            });
        });
    }
});

// Initialied a custom authentication.
Ember.Application.initializer({
    name: 'authentication',
    initialize: function(container, application) {
        container.register('authenticators:custom', CustomAuthenticator);
        Ember.SimpleAuth.setup(container, application);
    }
});

BackendWebapp.LoginController = Ember.Controller.extend(Ember.SimpleAuth.LoginControllerMixin, {
    authenticatorFactory: 'authenticators:custom'
});

// Add authentification for Route Index
BackendWebapp.IndexRoute = Ember.Route.extend(Ember.SimpleAuth.AuthenticatedRouteMixin);

// Add authentification for DashBoardIndex
BackendWebapp.IndexRoute = Ember.Route.extend(Ember.SimpleAuth.AuthenticatedRouteMixin);

Laravel configuration

route.php

// Logout current user
Route::get('/logout', function(){
    Auth::logout();
});

// Chech current authentification state
Route::get('/guest', function(){
    if(Auth::guest()){
        throw new \Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException();
    }else{
        echo 'ok';
    }
});

filters.php

Change Authentification method “Basic” to “x-Basic” to desactivate authentification popup in Google Chrome with ajax request.

Route::filter(
    'auth.basicCustom', function () {
        $credentials = [ 'email' => Request::getUser(), 'password' => Request::getPassword() ];

        if (!Auth::once($credentials)) {
            throw new \Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException('x-Basic');
        }
    }
);

sources :