0

Coming from the python/flask/django world, a couple of weeks ago I started playing with angular and Ionic (and Firebase). I am trying to implement a register/login functionality for a generic REST API - you send a user/pass combo, you receive a token etc.

Is it very wrong if I adhere to the python (and other server side languages) patterns - to make a factory service to store the auth token in the localstorage and than do a check for every state/route if the token is present and valid, if it is not I am thinking of doing the redirect to the login page? At this stage I would much rather prefer a solution I am able to undestand completely, rather than an efficient and elegant one.

4
  • 1
    stackoverflow.com/questions/29719894/… Commented Apr 1, 2016 at 8:25
  • m8 do you have server site implementation and want only code ionic site? Commented Apr 1, 2016 at 8:27
  • Yes the first link makes sense. The server side is not a problem, I am interested in the process of "checking" if the user is logged in and than redirecting to the login page, Commented Apr 1, 2016 at 8:30
  • 1
    ill will give u in some min :) Commented Apr 1, 2016 at 8:44

1 Answer 1

2

I was using this implementation is easy but you could use interceptor as well its require module so u need to adopt it to your code but hope it will help you figure this out :)

oauth.js

    define('oAuth',['app'],function(app){
      return app.module('appName').factory("oAuth",["$q", "$http", "$localStorage", function ($q, $http, $localStorage) {
        var oAuthModule = {};
        var _authorize = function(username,password){
          var deferred = $q.defer();
          var data = "grant_type=password&client_id=CLIENT&username="+username+"&password="+password;
          var host = $localStorage.host  + "/token";
          $http.post(host,data, { headers: { "Content-Type": "application/x-www-form-urlencoded"}}).then(function(s){
            $localStorage.authorizationData = s.data;
            $localStorage.tokenAwardTime = Date.now();
            deferred.resolve("success");
          },function(error){
            deferred.reject(error)
          });
          return deferred.promise;
        };
        var _refreshToken = function(){
          var deferred = $q.defer();
          var data = "grant_type=refresh_token&client_id=CLIENT&refresh_token="+$localStorage.authorizationData.refresh_token;
          var host = $localStorage.host + "/token";
          $http.post(host,data, { headers: { "Content-Type": "application/x-www-form-urlencoded"}}).then(function(s){
            $localStorage.authorizationData = s.data;
            $localStorage.tokenAwardTime = Date.now();
            deferred.resolve("success");
          },function(error){
            deferred.reject(error)
          });
          return deferred.promise;
        };
        var _updateHeader = function(){
          var deferred = $q.defer();
          try {
            if($localStorage.authorizationData.token_type && $localStorage.authorizationData.access_token){
              $http.defaults.headers.common.Authorization = $localStorage.authorizationData.token_type + " " + $localStorage.authorizationData.access_token;
            }else{
              deferred.reject('Code Undefined');
            }
          }
          catch(err) {
            deferred.reject(err);
          }
          finally {
            deferred.resolve("Code done");
          }

          return deferred.promise;
        };
        oAuthModule.updateHeader = _updateHeader;
        oAuthModule.auth = _authorize;
        oAuthModule.refresh = _refreshToken;
        return oAuthModule;
      }])
    });

in every request i add setupHeader(); that checks if token is near out of time.

var setupHeader = function(){
var diffrence = (new Date(Date.now()).getTime() - new Date($localStorage.tokenAwardTime).getTime())/1000;
if(diffrence >= 3500){
  socialveoOAuth.refresh().then(function(s){
      $http.defaults.headers.common.Authorization = $localStorage.authorizationData.token_type + " " + $localStorage.authorizationData.access_token;
  },function(e){
    $state.go('app.login');
  });
}
else{
  $http.defaults.headers.common.Authorization = $localStorage.authorizationData.token_type + " " + $localStorage.authorizationData.access_token;
}
};

and use it like:

 _requests.LogOut = function(){
var deferred = $q.defer();
setupHeader();
$http.get($localStorage.host+"/logout/").then(
  function(suc){
    deferred.resolve(suc.data.data);
  },function(err){
    deferred.reject(err);

  }
);
return deferred.promise;
};

and when token refresh is outoftime or rejected i just use

    $state.go('app.login');

hope this will help you out ;P

Sign up to request clarification or add additional context in comments.

1 Comment

just get localstorage u can use cordovasql aswell:P

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.