tafax / angular-digest-auth

AngularJS module to manage HTTP Digest Authentication
MIT License
28 stars 6 forks source link

How to use a controller method to authenticate? #11

Open danielpsf opened 9 years ago

danielpsf commented 9 years ago

Hi, good morning.

I found this module fantastic and I'm really excited to see it working, but until now I could not configure and use it properly.

Can you provide a simple web-app as a sample?

My problem is when I try to load the function $scope.submit nothing happens.

Anyway, here is what I'm doing:

PHP auth service extracted from here:
<?php
header('Access-Control-Allow-Origin: *');
$realm = 'Restricted area';

//user => password
$users = array('admin' => 'mypass', 'guest' => 'guest');

if (empty($_SERVER['PHP_AUTH_DIGEST'])) {
    header('HTTP/1.1 401 Unauthorized');
    header('WWW-Authenticate: Digest realm="'.$realm.
           '",qop="auth",nonce="'.uniqid().'",opaque="'.md5($realm).'"');

    die('Text to send if user hits Cancel button');
}

// analyze the PHP_AUTH_DIGEST variable
if (!($data = http_digest_parse($_SERVER['PHP_AUTH_DIGEST'])) ||
    !isset($users[$data['username']]))
    die('Wrong Credentials!');

// generate the valid response
$A1 = md5($data['username'] . ':' . $realm . ':' . $users[$data['username']]);
$A2 = md5($_SERVER['REQUEST_METHOD'].':'.$data['uri']);
$valid_response = md5($A1.':'.$data['nonce'].':'.$data['nc'].':'.$data['cnonce'].':'.$data['qop'].':'.$A2);

if ($data['response'] != $valid_response)
    die('Wrong Credentials!');

// ok, valid username & password
//echo 'You are logged in as: ' . $data['username'];
echo json_encode(array('user' => 'admin', 'role' => array('VIEW_ALL', 'CREATE_ALL')));

// function to parse the http auth header
function http_digest_parse($txt)
{
    // protect against missing data
    $needed_parts = array('nonce'=>1, 'nc'=>1, 'cnonce'=>1, 'qop'=>1, 'username'=>1, 'uri'=>1, 'response'=>1);
    $data = array();
    $keys = implode('|', array_keys($needed_parts));

    preg_match_all('@(' . $keys . ')=(?:([\'"])([^\2]+?)\2|([^\s,]+))@', $txt, $matches, PREG_SET_ORDER);

    foreach ($matches as $m) {
        $data[$m[1]] = $m[3] ? $m[3] : $m[4];
        unset($needed_parts[$m[1]]);
    }

    return $needed_parts ? false : $data;
}
?>
My app.js
var app = angular.module('app', ['dgAuth']);

app.config(['$routeProvider', 'dgAuthServiceProvider',
  function($routeProvider, dgAuthServiceProvider) {

    dgAuthServiceProvider.setHeader('PHP_AUTH_DIGEST');

    dgAuthServiceProvider.setConfig({
        login: {
            method: 'POST',
            url: 'http://localhost/digest/digest-auth.php'
        },
        logout: {
            method: 'POST',
            url: '/signout'
            //Other HTTP configurations.
        }
    });

    dgAuthServiceProvider.callbacks.login.push(['', function()
    {
        return {
            successful: function(response)
            {
                console.log("Worked man: " + response);
            },
            error: function(response)
            {
                console.log("Ops, did not work: " + response);
            },
        }
    }]);

    $routeProvider.
      when('/', {
        templateUrl: 'partials/login/login.html',
        controller: 'loginController'
      }).
        when('/main', {
        templateUrl: 'partials/main/main.html',
        resolve: {
    auth: ['dgAuthService', '$q', '$location', function (dgAuthService, $q, $location)
        {
            var deferred = $q.defer();

            dgAuthService.isAuthorized().then(function (authorized)
            {
                if (authorized)
                    deferred.resolve();
                else
                    deferred.reject();
                    $location.path('/');
            },
            function (authorized)
            {
                deferred.reject();
            });

            return deferred.promise;
        }]
}
      }).
      when('/logout', {
        templateUrl: 'partials/logout/logout.html'
      }).
      otherwise({
        redirectTo: '/'
      });
  }]);

app.run(['dgAuthService', function(dgAuthService)
{
    dgAuthService.start();
}]);
My controller.js
app.controller('loginController', function ($scope, dgAuthService){

    $scope.submit = function() {
        console.log($scope.username,$scope.password);
        dgAuthService.setCredentials($scope.username,$scope.password);
        dgAuthService.signin();
    }
});
My auth form:
<div class="loginContainer center-block">
    <div class="panel panel-primary">
        <div class="panel-heading">User Information</div>
            <div class="panel-body">
                <form data-ng-submit="submit()">
                    <div class="form-group">
                        <label for="usename">User Name</label>
                        <input class="form-control col-sm-1 col-md-1" id="usename" type="text" placeholder="Username" data-ng-model="username">
                    </div>
                    <div class="form-group">
                        <label for="password">Password</label>
                        <input type="password" class="form-control col-sm-1 col-md-1" id="password" placeholder="Password" data-ng-model="password">
                    </div>
                    <input type="submit" class="btn btn-lg btn-primary btn-block col-sm-1 col-md-1" value="Sign in"/>
                </form>
            </div>
    </div>
</div>
cadrogui commented 9 years ago

dude you solved it?, im facing the same issue.

regards.

danielpsf commented 9 years ago

Nop. I tried make my own modification inside this other module https://github.com/PatrickHeneise/angular-digest-interceptor.

But I left both behind because customer has requested a change to use the Browser popup instead of custom one.

cadrogui commented 9 years ago

ok, regards.