How to implement remember me in angularjs, using authToken?

5.1k Views Asked by At

I am finding difficulty in implementing the functionality for "remember me" in angularjs. I have gone through couple of blogs on stackoverflow but didn't get the solution.

Let us say I have 3 username and password stored in database.

[{username:1, password:1}, {username:2, password:2}, {username:3, password:3}]

Now every time when the user logs in, the server side is returning a token. Based on this token I want to implement my remember me functionality.

Below is the code I wrote for storing the username and password in cookies in my service.

 if (rememberLogin) {
     $cookieStore.put("userName", login);
     $cookieStore.put("password", password);
 }

And here is the code I am initializing on login page load

 function init() {
     if ($cookieStore.get("userName")!==undefined && $cookieStore.get("password")!==undefined){
         self.emailAddress=$cookieStore.get("userName");
         self.password=$cookieStore.get("password");
     }  
 }

With this approach I am just able to remember only one user, but not others, and also I know that storing passwords in cookies is not safe .

Kindly help me or suggest me some good quality of code to implement this. Any help is appreciated. Thanks

2

There are 2 best solutions below

4
On

As $cookieStore is deprecated, try to move to $cookies:

$cookies.putObject('key', value);
$cookies.getObject('key');
$cookies.remove('key');

And of course - storing a password in the cookie is a thing you have to avoid even in your school or private projects. Learn how to use Sessions and PHPSESSID cookie

0
On

As far as remember me functionality is concerned you can login from one user at a time at one login attempt,there is no chance any second user is logged in while first user is already in the session(browser session).You can store as much information of users as you want in your cookie unless you are not deleting the previous user's cookie.A simple scenario would be first user logged in and these details you save in browser cookie, another user cannot log in from that browser until the first logged out. Also every website does that,2 different users cannot log from one browser.It is quite unclear what you want to achieve. As I understand your problem is you are not clearing the previous cookie after 1st user logged out or you restart your server.Try

$cookies.remove("userInfo")