GeekOnGadgets GeekOnGadgets - 1 year ago 186
Javascript Question

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.

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download