Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remember me functionality and Token in Angularjs

I am looking for a better approach to my problem here. I have a remember me functionality on my login form. Ones the user click on remember me box, My API sends me Token.

My question is what is the best way to store this token and authenticate user again when they are back to my site?

What I thought,

  1. Create a Cookie and store token there.
  2. Create a local Storage.

Please give me any advice which might help me.

like image 431
GeekOnGadgets Avatar asked Oct 30 '14 04:10

GeekOnGadgets


2 Answers

Use ngCookies: The ngCookies module provides a convenient wrapper for reading and writing browser cookies.

First you install ngCookies in your app using bower bower install [email protected] or manully.

then inject ngCookies in your app like angular.module('app', ['ngCookies']);

then simply use like

angular.module('App', ['ngCookies'])
      .controller('demo', ['$cookies', function($cookies) {
          // Setting a cookie
          $cookies.put('cookieName', 'object');
          // Retrieving a cookie
          var sample= $cookies.get('cookieName');
         // Remove a cookie
          $cookies.remove('cookieName');
      }]);
like image 102
Umair Ahmed Avatar answered Nov 08 '22 23:11

Umair Ahmed


I would use document.cookie with a factory code like this:

Creates a cookie (for example this one expires in a year):

app.factory('$remember', function() {
    return function(name, values) {
        var cookie = name + '=';

        cookie += values + ';';

        var date = new Date();
        date.setDate(date.getDate() + 365);

        cookie += 'expires=' + date.toString() + ';';

        document.cookie = cookie;
    }
});

This factory removes the cookie:

app.factory('$forget', function() {
    return function(name) {
        var cookie = name + '=;';
        cookie += 'expires=' + (new Date()).toString() + ';';

        document.cookie = cookie;
    }
});

Then whenever a user successfully logs in cache the key using $remember:

$remember('my_cookie_name', response.user._id);

And always check if the cookie is there when logging in the user else use a a standard login and save it to their cookies. If the remember me is not enabled, forget the document.cookie

like image 29
willjleong Avatar answered Nov 08 '22 21:11

willjleong