How to implement remember me in angularjs, using authToken? - javascript

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

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

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")

Related

Google oauth session lost after page reload (javascript)

I recently moved from the deprecated gapi.auth2 to the new Google Identity Services, using the javascript client library, and noticed a big difference: if someone signs in, and then reloads the page, the session is lost, and has to sign in again, every time the page is loaded. This was not the case with the deprecated library.
The problem can be easily reproduced with the Calendar API example.
Is there any configuration option to keep the session persistent? Or do I need to store the access tokens somehow? I could not find anything relevant in the official docs.
UPDATE:
The migration guide states the following:
Previously, Google Sign-In helped you to manage user signed-in status using:
Callback handlers for Monitoring the user's session state.
Listeners for events and changes to signed-in status for a user's Google Account.
You are responsible for managing sign-in state and user sessions to your web app.
However there's absolutely no information on what needs to be done.
UPDATE 2
To be more specific, the actual issue is not making the session persistent. Managing the sign in state and user session is something I can solve.
The real problem is the access token used to call the Google APIs.
As mentioned in the comments, the access tokens are 1) short lived 2) are not stored anywhere, so even if not expired, they do not persist between page reloads.
Google provides the requestAccessToken method for this, however even if I specify prompt: '', it opens the sign-in popup. If I also specify the hint option with the signed in user's email address, than the popup opens, displays a loading animation briefly, and closes without user interaction. I could live with this, however this only works if triggered by a user interaction, otherwise the browser blocks the popup window, meaning that I cannot renew the token without user interaction, e.g. on page load. Any tips to solve this?
I faced all the same issues you described in your question.
In order to help:
Google 3P Authorization JavaScript Library: in this link we can check all the methods the new library has (it does not refresh token, etc..)
This doc says the library won't control the cookies to keep the state anymore.
Solution
Firstly I need to thanks #Sam O'Riil answer.
As Sam described: "you can somehow save access token and use it to speed-up things after page reload."
Given the the Google's exampe, we should call initTokenClient in order to configure the Google Auth and the requestAccessToken to popup the auth:
tokenClient = google.accounts.oauth2.initTokenClient({
client_id: 'YOUR_CLIENT_ID',
scope: 'https://www.googleapis.com/auth/calendar.readonly',
prompt: 'consent',
callback: tokenCallback
});
tokenClient.requestAccessToken({prompt: ''})
In your tokenCallback you can save the credentials you get somehow, e.g.:
const tokenCallback(credentials) => {
// save here the credentials using localStorage or cookies or whatever you want to.
}
Finally, when you restart/reload your application and you initialize the gapi.server again, you only need to get the credentials again and set token to gapi, like:
gapi.load('client', function() {
gapi.client.init({}).then(function() {
let credentials = // get your credentials from where you saved it
credentials = JSON.parse(credentials); // parse it if you got it as string
gapi.client.setToken(credentials);
... continue you app ...
}).catch(function(err) {
// do catch...
});
});
Doing it, your application will work after the reload. I know it could not be the best solution, but seeing what you have and the library offers, I think that's you can do.
p.s.: the token expires after 1 hour and there is no refresh token (using the implicit flow) so, you will have to ask the user to sign-in again.

Should Token created when the user registers or login?

I have an API created by one of my team :),
And he made an endpoints "Register/Login"
his thought
When user create a user we save his data and the endpoint response it " without generating a Token"
so i can't navigate him to other screens cuz I make a request based on his Token,
So he wants me to navigate user after register to the login screen then Login endpoint will response the Token
But I think it's not a nice way and not improve UX.
So what you think we do?
generate Token in the register or log in?
The way I see this:
Solution 1:
You have him change the register API so that returns a token for you and you keep doing whatever you do with it.
Solution 2:
By registering, I'm assuming they type in a username/email, some personal details and a password!? So you have all the data to log the user in after registration. Upon successful registration, use the same username/email and password from memory (do not store them in browser storage) and call the login api to get the token (you only redirect after you've gotten the token) - so UX doesn't suffer here.
P.S. Instead of "fighting" one another over who's solution is better, try to work together in a solution. This is clearly an "I told you so" attempt - hence why I gave you two solution where both sides can do the work. Both of you can implement a solution without affecting UX, it's a matter of who's more stubborn :P

AWS Cognito force refresh session

I'm running into some problems when I attempt to refresh my session tokens, (Access, Id, Refresh). I have already read this question and the answer has helped me understand what is going on some. But I feel what I am trying to do isn't quite what getSession is for.
I am attempting to implement a session expiration message (done) that allows the user to extend their session (refreshes the tokens). From what I gather about getSession(), it returns either the old tokens, if they are still valid, or new tokens if they are not valid. Please correct me if I am wrong there.
I am attempting to give the user new/refreshed tokens every time they click on extend session. For dev purposes, I have a button which then displays the message with the extend session button. The tokens I receive when I call getSession() are the old ones, but I want them to be new ones.
So basically, nullifying the old session and giving them a new one.
My questions are:
Am I missing some understanding about getSession(), as previously mentioned?
Can I give the user new session tokens (Access, Id, Refresh)?
Can I do #2 without having the user sign in again?
Thank you.
EDIT 1:
It may help to know that I am not using any Federated Identities.
You can call cognitoUser.refreshSession. I've found a reasonable example for you over here:
Sample code: how to refresh session of Cognito User Pools with Node.js and Express
Look for the method called checkTokenExpiration, it explains perfectly well what you have to do to refresh the session.

Facebook User Feed Subscriptions

I have what I'm sure will be a very easy question, I'm just confused.
I have successfully got my server subscribed, for real time user/feed but simply am not getting any updates.
I have logged myself in using the FB.login JavaScript SDK, using the scope "user_about_me,user_status,read_stream" - so I expected to see updates for my user, but not getting anything at all.
The app is in "Development Mode", so, can anyone confirm that since I have got a { success: true }, that the reason is simply because of this? Or perhaps I need to put it under review from Facebook?
Thanks.
Woo, it's fixed now!
On my research, I had come across this post:
How to subscribe to real-time updates for a Facebook page's wall
Not realizing that I can use the USER_ID in place of the PAGE_ID. Following the Real Time Subscription documentation, I thought that by using the APP_ID, that it would allow to make one subscription for all users that grant the application its scope.
On to the next hurdle...

How do I do anonymous Firebase logins which allow browser refresh?

I'm doing a javascript single-page app which allows people to log in, either via twitter or (for some use cases) anonymously.
A very important thing to figure out was how to let them reload the page -- this shouldn't force them to log back in!
I figured this out pretty quickly for the twitter login, and so it uses cookie-stored information to log back in (specifically, the user_id, oauth_token and oauth_token_secret).
However, I can't seem to make this work with the anonymous login facility.
I tried:
auth.login("anonymous", {
user_id: #get("userId"),
firebase_auth_token: #get("firebaseAuthToken")
});
but it doesn't work... I get a new anonymous user ID. I want to keep the same one for the duration of the user's browser session.
And yeah, I tried both user_id and id, firebaseAuthToken and firebase_auth_token.
Thanks!
By default, sessions are created any time you successfully log in a user, and last up until the session expiration time configured under the 'Auth' tab in Forge. This built-in sessioning applies to all Simple Login authentication types, and is automatic as long as local storage and cookies are available.
To resume a session, simply instantiate the FirebaseSimpleLogin object with a Firebase reference and callback. If a local session exists, the callback will be invoked with the same payload you would see if you had just logged the user in for the first time. Invoking the login method will always generate a brand new auth. flow regardless of current user authentication state or session.
Note that in anonymous auth, once a user session expires it cannot be recovered. This may change in the future or some additional functionality may be added to enable it, but it is currently only logged-in to once per user id.

Categories

Resources