0

I have created a basic authentication system in an angular app which is written against hardcoded credentials - see below:

app.js

/* global app:true */
/* exported app */
'use strict';

/**
 * @ngdoc overview
 * @name WebAppApp
 * @description
 * # WebAppApp
 *
 * Main module of the application.
 */
var app = angular
  .module('WebAppApp', [
    'ngAnimate',
    'ngAria',
    'ngCookies',
    'ngMessages',
    'ngResource',
    'ngRoute',
    'ngSanitize',
    'ngTouch'
  ])
  .config(function ($routeProvider) {
    $routeProvider
      .when('/', {
        templateUrl: 'views/login.html',
        controller: 'loginCtrl',
        controllerAs: 'login'
      })
      .when('/home', {
        templateUrl: 'views/home.html'
        //controller: 'loginCtrl',
        //controllerAs: 'login'
      })
      .otherwise({
        redirectTo: '/'
      });
  });

login.html

<form ng-submit="submit()">
  Username: <input type="text" id="username" ng-model="username" /><br>
  Password: <input type="password" id="password" ng-model="password" /><br>
  <input type="submit" value="Submit" />
</form>

login.js

'use strict';

//app global variable
//this is hte controller that handles post requests
app.controller('loginCtrl', function ($scope, $location) {

    $scope.submit = function(){
        var uname = $scope.username;
        var password = $scope.password;

        if($scope.username == 'admin' && $scope.password == 'admin'){

            $location.path('/home');

        } else {

            alert('username or password is wrong');
        }

    };

});

This works. What I want to do now, is check the username and password against an api call by posting the data to the server /login, if successful an access token is returned, and is then stored inside of a cookie. At which point the user gets access to the rest of the application.

If the credentials fails, for validation takes place preventing the user from logging in.

What is the best way to do this?

1 Answer 1

2

First of all check this url

Your code would look something like this:

$scope.submit = function(){
    $http.post('/login', {
        username:$scope.username,
        password:$scope.password
    }).then(function(response) {
        if (response.data=="ok") {
          //Login was ok
          $location.path("/home");
        } else {
          //Login was not ok
        } 
      }, function(response) {
           //Error happend, response.status or response.statusText have details
    });
}
Sign up to request clarification or add additional context in comments.

5 Comments

Should I put all of the code into the controller or services? Do you know how I can store the results into a cookie/session? Thanks
@bobo2000. It totally depends on the architecture (read as size) of your application. As soon as you have similar "call api" functionality in other controllers, you can move it to service. As for "session management" approach, here is first link I've found googling, that seem to be good Techniques for authentication in AngularJS applications
I see, after reading the docs, I am quite confused between 'service' and just making the API calls like you have described above. Your approach seems much more simpler and better. Why do I need a service? Thanks
"Service" in a case of small application, would be a place where you can keep some common functionality, grouped by some common meaning. As an example, could be, "UserAPIService", with methods like "login","logout","loadProfile" etc. So you can inject $UserAPIService dependancy from any controller of your application and use it, without having code duplicated
@jevgenig could you please provide some context for your link? This answer doesn't really explain anything, it just references documentation providing no real learning or understanding. (see the answer guidelines for more details: (stackoverflow.com/help/how-to-answer).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.