node.js Express/socket.io hybrid application with facebook - session

I am using express/socket.io combination in my node.js app. So far it's working fine.
Now, I need to store facebook user id and email id (after user being authorized) into session scope. I see there are lot of options and a bit lost here.. in my app, most of the communications happen through socket.io.. ultimately what i want is to access user id and email id anytime in the client side...
var express = require("express"),
fs = require("fs"),
app = express.createServer(
form({ keepExtensions: true })
),
io = require("socket.io");
socket = io.listen(app);

After being authorized, I suggest using the accessToken which is already in the cookies and then sending it through the socket.io and fetching the email and the id using graph.facebook or your own DB. The problem with storing user ID and Email is that it could insecure, since session hijacking could happen.
Facebook has its own experts on security to make sure it wouldn't be hijacked. Use it!

This might help:
http://criso.github.com/fbgraph/
After being authorized you can store the data in your session via express
http://expressjs.com/guide.html#session-support
On a very basic level:
// Get data from facebok and store it on a var `userData`
// server
socket.on('getUserData', function (callback) {
callback(facebookUserData);
});
// client
socekt.emit('getUserData', function(userData) {
console.log(userData);
});

Related

How to check if user is still logged in google?

I am using Google OAuth through Laravel Socialite to authenticate all the users in my web app.
I need the user session to end as soon as possible if user logs out of his google account.
I am trying to set up a middleware that would perform regular checks if user is still signed in with google. But I can't find a way to ask "Is user#example.com still the current user on google?"
I tried to get \Socialite::driver('google')->user() in the middleware but that doesn't seem to work without doing a redirect to google beforehand. I would like this check to be as quick and unobtrusive as possible. It should also work during a background ajax call.
It seems that it would be trivial using the client side authentication as there is gapi.auth2.init().isSignedIn.get(). However, that would mean I have to ask users for two authorizations (server side and client side) which seems wrong.
Looking at the docs at google, I see nothing that would let me check their authentication status apart from reauthenticating. Access token won't expire on logout... Is there a workaround?
It turns out that we can actually use gapi javascript in tandem with Socialite - just use the same client token. I didn't suspect that I will just get all the info without logging in separately for browser session, but it works.
I added the following code to the end of my master blade template to check state for authorized users.
#auth
<script>
var currentUserEmail = '{{Auth::user()->email}}'; // user "sameness" criterion
var googleClientId = '{{env('GOOGLE_ID')}}'; // the same oauth client id
</script>
<script src="https://apis.google.com/js/platform.js"></script>
<script src="{{mix('js/checkGoogleAuth.js')}}"></script>
#endauth
The script checkGoogleAuth is a simple then, I copied the google tutorial and shortened it:
var auth2; // The Sign-In object.
var googleUser; // The current user.
/**
* Initializes Signin v2 and sets up listeners.
*/
var initSigninV2 = function() {
auth2 = gapi.auth2.init({
client_id: googleClientId,
scope: 'profile'
});
// Listen for sign-in state changes.
auth2.isSignedIn.listen(checkState);
auth2.currentUser.listen(checkState);
};
var checkState = function (user) {
//if signed out or changed user
if (!auth2.isSignedIn.get() || currentUserEmail != auth2.currentUser.get().getBasicProfile().getEmail())
$('.logout-username').click(); //click logout button
};
gapi.load('auth2', initSigninV2); //launch it
I hope it helps someone else as well!

Cookies or Session on Google Apps Script Webservice

I've created websites before where the server-side code has access to either Cookies on the browser or some sort of Session variables. I have not figured out how to do this with GAS. I can host a website with GAS, but I have no way of seeing the login session when a new page is loaded. How do I do this?
I would expect to see this information in the doGet() event, like this:
function doGet(e){
e.session.userid; //or something like this
}
NOTE: Anyone can access my site, even anonymous. So I can't rely on Google logins.
Google has a Session method.
https://developers.google.com/apps-script/reference/base/session
// Log the email address of the person running the script (visiting the page).
var email = Session.getActiveUser().getEmail();
Logger.log(email);
Edit:
In regard to the comment about cookie based identification.
I am no expert at this but my thought was to do something like this
Client JS
$(function(){
var clientCookie = document.cookie
google.script.run
.withSuccessHandler(function(cookieString){
if(cookieString){
document.cookie= cookieString
}
})
.craeteCookie(clientCookie) // server function to create cryptographic cookie string
})
Server Side
function createCookie(clientCookie){
if(clientCookie){
//check cookie is valid
}
else{
// create client cookie
}
}

Firebase 3.x - Token / Session Expiration

Does anyone know how long would it take for the token to expire? There no option now to set the token validity on the console.
Since May 2016 Firebase Authentication login sessions don't expire anymore. Instead they use a combination of long-lived account tokens and short-lived, auto-refreshed access/ID tokens to get the best of both worlds.
If you want to end a user's session, you can call signOut().
Its does expire. After one hour logged in the token id expire. If you try to verify sdk returns a error "Error: Firebase ID token has expired. Get a fresh token from your client app and try again. See https://firebase.google.com/docs/auth/server/verify-id-tokens for details on how to retrieve an ID token."
Is There such a way to change expiration time to Firebase token, not custom token.
Anybody that know how this really works.
For anyone that is still confused, it is all explained in great detail here
If your app includes a custom backend server, ID tokens can and should
be used to communicate securely with it. Instead of sending requests
with a user’s raw uid which can be easily spoofed by a malicious
client, send the user's ID token which can be verified via a Firebase
Admin SDK (or even a third-party JWT library if Firebase does not have
an Admin SDK in your language of choice). To facilitate this, the
modern client SDKs provide convenient methods for retrieving ID tokens
for the currently logged-in user. The Admin SDK ensures the ID token
is valid and returns the decoded token, which includes the uid of the
user it belongs to as well as any custom claims added to it.
If the above answer is still confusing to you,
This is what i did:
firebase.auth().onAuthStateChanged(async user => {
if (user) {
const lastSignInTime = new Date(user.metadata.lastSignInTime);
const lastSignInTimeTimeStamp = Math.round(lastSignInTime.getTime() / 1000);
const yesterdayTimeStamp = Math.round(new Date().getTime() / 1000) - (24 * 3600);
if(lastSignInTimeTimeStamp < yesterdayTimeStamp){
await firebase.auth().signOut()
this.setState({
loggedIn: false
});
return false;
}
this.setState({
loggedIn: true,
user
});
}
})

How to reset google oauth 2.0 authorization?

I'm using Google APIs Client Library for JavaScript (Beta) to authorize user google account on web application (for youtube manipulations). Everything works fine, but i have no idea how to "logout" user from my application, i.e. reset access tokens.
For example, following code checks user authorization and if not, shows popup window for user to log into account and permit web-application access to user data:
gapi.auth.authorize({client_id: CLIENT_ID, scope: SCOPES, immediate: false}, handleAuth);
But client library doesn't have methods to reset authorization.
There is workaround to redirect user to "accounts.google.com/logout", but this
approach is not that i need: thus we logging user off from google account not only from my application, but also anywhere.
Google faq and client library description neither helpful.
Try revoking an access token, that should revoke the actual grant so auto-approvals will stop working. I assume this will solve your issue.
https://developers.google.com/accounts/docs/OAuth2WebServer#tokenrevoke
Its very simple. Just revoke the access.
void RevokeAcess()
{
try{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("https://accounts.google.com/o/oauth2/revoke?token="+ACCESS_TOKEN);
org.apache.http.HttpResponse response = client.execute(post);
}
catch(IOException e)
{
}
}
But it should be in asyncTask
It depends what you mean by resetting authorization. I could think of a three ways of doing this:
Remove authorization on the server
Go to myaccount.google.com/permissions, find your app and remove it. The next time you try to sign in you have to complete full authorization flow with account chooser and consent screen.
Sign out on the client
gapi.auth2.getAuthInstance().signOut();
In this way Google authorization server still remembers your app and the authorization token remains in browser storage.
Sign out and disconnect
gapi.auth2.getAuthInstance().signOut();
gapi.auth2.getAuthInstance().disconnect();
This is equivalent to (1) but on the client.
Simply use: gapi.auth.setToken(null);
Solution for dotnet, call below API and pass the access token, doc - https://developers.google.com/identity/protocols/oauth2/web-server#tokenrevoke
string url = "https://accounts.google.com/o/oauth2/revoke?token=" + profileToken.ProfileAccessToken;
RestClient client = new RestClient(url);
var req = new RestRequest(Method.POST);
IRestResponse resp = client.Execute(req);

node.JS - express framework create session and check if session exist

This is my server code, please take a look at the comments in the code.
var app = express.createServer();
app.get('/', function(req, res){
// create a session with the value of an email for example: me#gmail.com
});
// down here I want to check the session if the session exist
if( there is a session with value me#gmail.com){
//do stuff
}
The way sessions are implemented in Connect / Express doesn't allow for a custom session ID. This is partly because of security. So there's a bunch of things you can do.
Store everything in the session. Create an index somewhere (perhaps in a database) that maps email addresses to session IDs, so you can look up sessions by email.
Store only the email in the session. Keep the actual session data elsewhere (perhaps in a database), where you can fetch it by email address.
Create your own session middleware, perhaps based off Connect's code. The actual session code in Connect is a mere 300 lines. But be very careful to keep security features intact.

Resources