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,
Please give me any advice which might help me.
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');
}]);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With