google plus login api cookie - google-app-engine

I am using google app engine python. I followed the example code to let user login. After this step am I supposed to create my own cookie or session to remember the user? Because when i refresh the page, the login button appears again.
This is the javascript.
<script src="https://apis.google.com/js/plusone.js" type="text/javascript"></script>
<script type="text/javascript">
/*
* Triggered when the accepts the the sign in, cancels, or closes the
* authorization dialog.
*/
function loginFinishedCallback(authResult) {
if (authResult) {
if (authResult['error'] == undefined){
gapi.auth.setToken(authResult); // Store the returned token.
toggleElement('signin-button'); // Hide the sign in upon successful sign in.
getEmail(); // Trigger request to get the email address.
} else {
console.log('An error occurred');
}
} else {
console.log('Empty authResult'); // Something went wrong
}
}
/*
* Initiates the request to the userinfo endpoint to get the user's email
* address. This function relies on the gapi.auth.setToken containing a valid
* OAuth access token.
*
* When the request completes, the getEmailCallback is triggered and passed
* the result of the request.
*/
function getEmail(){
// Load the oauth2 libraries to enable the userinfo methods.
gapi.client.load('oauth2', 'v2', function() {
var request = gapi.client.oauth2.userinfo.get();
request.execute(getEmailCallback);
});
}
function getEmailCallback(obj){
var el = document.getElementById('email');
var email = '';
if (obj['email']) {
email = 'Email: ' + obj['email'];
}
//console.log(obj); // Uncomment to inspect the full object.
el.innerHTML = email;
toggleElement('email');
}
function toggleElement(id) {
var el = document.getElementById(id);
if (el.getAttribute('class') == 'hide') {
el.setAttribute('class', 'show');
} else {
el.setAttribute('class', 'hide');
}
}
</script>
This is the login button.
<span id="signin-button" class="show">
<div class="g-signin" data-callback="loginFinishedCallback"
data-approvalprompt="force"
data-clientid="279937419542.apps.googleusercontent.com"
data-scope="https://www.googleapis.com/auth/plus.login
https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/plus.me https://www.googleapis.com/auth/userinfo.profile"
data-height="short"
data-cookiepolicy="single_host_origin"
>
</div>
</span>

Related

AWS Cognito Authentication in Reactjs

I have built applications using Firebase and React, and the procedure is pretty seamless.
Lately I have been required to use AWS Cognito, and it seems a bit of a pain to set up as the docs are not clear.
Firstly, how can I do user authentication using Cognito? I set up a user pool, with the following app client settings:
Now, I add the authorizer to my API as follows:
Now my question is, how do I use this with my frontend to sign in a user and make authenticated API calls?
There seem to be two different toolkits available:
https://github.com/aws/aws-sdk-js
https://github.com/aws-amplify/amplify-js
It is not clear at all for a beginner what to use, and how to get authentication working. Ideally I would use it like I do for firebase, and just have my frontend make an authentication call using the email and password, and in turn receiving a token of some sort (on success only) that can then be used to then make signed API calls.
Can someone please help with code examples?
sorry for the confusion.
AWS Cognito Userpools act as an Identity Provider. It supports all User management (Sign Up, Sign In, Password reset, User deletion, etc). Cognito also supports Federated Identity (E.g., A User who already has an Google/Facebook account can sign in). In this case, Cognito talks to Google/Facebook using OAuth.
When I was learning about Cognito/JWT tokens, I created a simple JS/HTML to understand how it works. Since you asked for code, you can refer it - https://github.com/ryandam9/Cognito-tokens.
As per your screen shot, you already configured a Userpool - sls-notes-backend. Say, you configured the mandatory attribute as Email.
Step 0 - Initialize
You get both userPoolId and appId when you create the user pool.
poolData = {
UserPoolId: userPoolId,
ClientId: appId
};
userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(poolData);
Step 1 - Signup a User using Email and Password - Say your UI already captured these details from the User and user clicked on 'Sign Up' button.
/**
* Signup a User
* #param e
*/
function addUser(e) {
signupMessage.style.display = 'none';
signupMessage.className = '';
e.preventDefault();
let name = document.getElementById('name').value.trim();
let email = document.getElementById('signup-email').value.trim();
let password = document.getElementById('signup-password').value.trim();
if (name.length === 0 || email === 0 || password === 0) {
return;
}
let attributeList = [
new AWSCognito.CognitoIdentityServiceProvider.CognitoUserAttribute({
Name: 'given_name', Value: name
}),
];
userPool.signUp(email, password, attributeList, null, function (err, result) {
if (err) {
signupMessage.innerText = err;
signupMessage.style.display = 'block';
signupMessage.className = 'alert alert-danger';
return;
}
cognitoUser = result.user;
console.log('user name is ' + cognitoUser.getUsername());
// Show a text box to enter Confirmation code
document.getElementById('signup-btn').style.display = 'none';
document.getElementById('code-block').style.display = 'block';
document.getElementById('confirm-user-btn').style.display = 'inline-block';
});
}
If the signup is successful (It is valid Email and the Email does not yet exist in Userpools, a Confirmation code is sent to the Email provided. Next step is to, allow the user to enter the code and confirm his identity.
Step 3 - Confirm User
/**
* Confirm the user by taking the Confirmation code.
* #param e
*/
function confirmUser(e) {
e.preventDefault();
let verificationCode = document.getElementById('code').value;
cognitoUser.confirmRegistration(verificationCode, true, function (err, result) {
if (err) {
signupMessage.innerText = err;
signupMessage.style.display = 'block';
signupMessage.className = 'alert alert-danger';
return;
}
signupMessage.innerText = result;
signupMessage.style.display = 'block';
signupMessage.className = 'alert alert-success';
});
}
If the User enters correct code, his identity is confirmed. At this point, An entry is made to the Userpool for this user. It looks like this.
Step 4 - Authentication (Sign In)
At this point, User registration is done. Its time to allow him to login. Please ignore the unnecessary code in the code below (the code that fetches and prints credentials, decoding part). If the authentication is successful, Cognito returns two types of Tokens to the application - ID Token and Access Token. These are valid only for this session and for this user only. More details here - https://ryandam.net/aws/19-cognito-userpools/index.html#0
/**
* Signin user with Email and Password
* #param e
*/
function authenticateUser(e) {
e.preventDefault();
let email = document.getElementById('signin-email').value;
let password = document.getElementById('signin-password').value;
if (email.length === 0 || password === 0 || userPool === null || userPool === undefined) {
signinMessage.innerText = 'Fill in all fields!';
signinMessage.style.display = 'block';
signinMessage.className = 'alert alert-danger';
return;
}
let authenticationData = {
Username: email,
Password: password,
};
let authenticationDetails = new AWSCognito.CognitoIdentityServiceProvider.AuthenticationDetails(authenticationData);
let userData = {
Username: email,
Pool: userPool
};
let cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData);
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function (result) {
signinMessage.innerText = 'Authentication Success!';
signinMessage.style.display = 'block';
signinMessage.className = 'alert alert-success';
document.getElementById('token-section').style.display = 'block';
document.getElementById('signin-btn').style.display = 'none';
// Decode ID Token
let idToken = result.idToken.jwtToken;
document.getElementById('id-token').innerText = idToken;
document.getElementById('decoded-id-token').appendChild(parseIdToken(idToken));
// Decode Access Token
let accessToken = result.getAccessToken().getJwtToken();
document.getElementById('access-token').innerText = accessToken;
document.getElementById('decoded-access-token').appendChild(parseAccessToken(accessToken));
let cognitoUser = userPool.getCurrentUser();
if (cognitoUser != null) {
cognitoUser.getSession(function (err, result) {
if (result) {
// Set the region where your identity pool exists (us-east-1, eu-west-1)
AWS.config.region = region;
AWS.config.update({region: region});
logins = {};
let key = 'cognito-idp.us-east-2.amazonaws.com/' + userPoolId;
logins[key] = result.getIdToken().getJwtToken();
// Add the User's Id Token to the Cognito credentials login map.
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: identityPoolId,
Logins: logins,
});
// Make the call to obtain credentials
AWS.config.credentials.get(function () {
// Credentials will be available when this function is called.
var accessKeyId = AWS.config.credentials.accessKeyId;
var secretAccessKey = AWS.config.credentials.secretAccessKey;
var sessionToken = AWS.config.credentials.sessionToken;
});
if (s3BucketName.length > 0)
listS3Bucket(s3BucketName);
}
});
}
},
onFailure: function (err) {
signinMessage.innerText = err;
signinMessage.style.display = 'block';
signinMessage.className = 'alert alert-danger';
}
}
);
}
Step 5 - Invoking the API Endpoint you already created - Since you've already created an Authorizer using the Userpool and you're using Authorization as the header, you can invoke the End point from JS by passing the ID token as Authorization header. What happens is that, the token is validated by the authorizer. Since it is valid the user is able to invoke the API.**
I do not have JS code, you can test your API from CLI/Postman something like this:
Note
AWS Amplify seems to be a wrapper for Cognito and other services. For instance, Amplify sets up User pool for you when you invoke its CLI commands. You can refer this code if you want to see how Amplify works with Flutter - https://github.com/ryandam9/Auth-flutter-aws-amplify.
I am still learning. I tried to be as accurate as possible.

phonegap + framework7 how to programmtacally set starting page?

I have application which on start lets you pick - if are you contributor or user. After that I want always load the starting page for a contributor or the user. I know you can set <content src="index.html" /> to do it once on start, but how can I do it dynamically?
#proofzy answer is right, but you could still do it using only DOM7 instead of Jquery
Inside your JS file:
//to save data if user pick contributor or user button after first start.
$$("#contributor").on('click', function(){
localStorage.setItem("whois", "contributor");
});
//And call this same script but for user:
$$("#user").on('click', function(){
localStorage.setItem("whois", "user");
});
//So call this function on the end of page index.html and it will redirect programmatically
function check(){
if (localStorage.getItem("whois") !== null) { //if whois exists on localStorage
if (localStorage.getItem("whois") == "user"){ // if is USER send to User Page
window.location.href = "userIndex.html"
}else if (localStorage.getItem("whois") == "contributor"){ // if is USER send to contributor Page
window.location.href = "contributorIndex.html"
}
}
}
There are many other ways to do it, even better, but this one is simplest.
You must use
localStorage
to save data if user pick contributor or user button after first start.
Simple use jQuery script:
<script>
$("#contributor").click( function()
{
//alert('button clicked');
localStorage.setItem("contributor", "contributor");
}
);
</script>
And call this same script but for user:
<script>
$("#user").click( function()
{
//alert('button clicked');
localStorage.setItem("user", "user");
}
);
</script>
So on next html page control if user is previously press "user" or "contributor".
$(document).ready(function() {
if (localStorage.getItem("user") === null) {
//user is null
} else {
document.location.href = "userIndex.html"
}
if (localStorage.getItem("contributor") === null) {
//contributor is null
} else {
document.location.href = "contributorIndex.html"
}
});
Good luck!

Link Sails's authenticated user to websocket's user

I am currently trying to create an sails+angular web-app.
I already have a user-authentication system working (based on this tutorial : https://github.com/balderdashy/activity-overlord-2-preview). I am trying to integrate a very simple chat inside using websocket.
My issue is to link websocket's "user" to the authenticated user.
Because when an authenticated user writes a message, I want to send the message as data but not the id of the current user, i would like to get this id from the sail's controller.
This is my actual sails chatController :
module.exports = {
addmsg:function (req,res) {
var data_from_client = req.params.all();
if(req.isSocket && req.method === 'GET'){
// will be used later
}
else if(req.isSocket && req.method === 'POST'){
var socketId = sails.sockets.getId(req);
/* Chat.create(data_from_client)
.exec(function(error,data_from_client){
console.log(data_from_client);
Chat.publishCreate({message : data_from_client.message , user:currentuser});
}); */
}
else if(req.isSocket){
console.log( 'User subscribed to ' + req.socket.id );
}
}
}
and this is my angular's controller
io.socket.get('http://localhost:1337/chat/addmsg');
$scope.sendMsg = function(){
io.socket.post('http://localhost:1337/chat/addmsg',{message: $scope.chatMessage});
};
req.session.me
...was the solution.

Firebase: How can i use onDisconnect during logout?

How can i detect when a user logs out of firebase (either facebook, google or password) and trigger the onDisconnect method in the firebase presence system. .unauth() is not working. I would like to show a users online and offline status when they login and out, minimize the app (idle) - not just when the power off their device and remove the app from active applications on the device.
I'm using firebase simple login for angularjs/ angularfire
Im using code based off of this tutorial on the firebase site.
https://www.firebase.com/blog/2013-06-17-howto-build-a-presence-system.html
Please i need help with this!
Presence code:
var connectedRef = new Firebase(fb_connections);
var presenceRef = new Firebase(fb_url + 'presence/');
var presenceUserRef = new Firebase(fb_url + 'presence/'+ userID + '/status');
var currentUserPresenceRef = new Firebase(fb_url + 'users/'+ userID + '/status');
connectedRef.on("value", function(isOnline) {
if (isOnline.val()) {
// If we lose our internet connection, we want ourselves removed from the list.
presenceUserRef.onDisconnect().remove();
currentUserPresenceRef.onDisconnect().set("<span class='balanced'>☆</span>");
// Set our initial online status.
presenceUserRef.set("<span class='balanced'>★</span>");
currentUserPresenceRef.set("<span class='balanced'>★</span>");
}
});
Logout function:
var ref = new Firebase(fb_url);
var usersRef = ref.child('users');
service.logout = function(loginData) {
ref.unauth();
//Firebase.goOffline(); //not working
loggedIn = false;
seedUser = {};
clearLoginFromStorage();
saveLoginToStorage();
auth.logout();
};
The onDisconnect() code that you provide, will run automatically on the Firebase servers when the connection to the client is lost. To force the client to disconnect, you can call Firebase.goOffline().
Note that calling unauth() will simply sign the user out from the Firebase connection. It does not disconnect, since there might be data that the user still has access to.
Update
This works for me:
var fb_url = 'https://yours.firebaseio.com/';
var ref = new Firebase(fb_url);
function connect() {
Firebase.goOnline();
ref.authAnonymously(function(error, authData) {
if (!error) {
ref.child(authData.uid).set(true);
ref.child(authData.uid).onDisconnect().remove();
}
});
setTimeout(disconnect, 5000);
}
function disconnect() {
ref.unauth();
Firebase.goOffline();
setTimeout(connect, 5000);
}
connect();

emails from gmail but response is gmail.readonly

I am trying to get the emails from gmail using https://www.googleapis.com/auth/gmail.readonly/?access_token='fdrt654vfdgfe6545But in response I am getting gmail.readonlyBut the System.HttpResponse[Status=OK, StatusCode=200] is fine. Can any guide me is there anything I am missing out.
This I how I requested got auth but in the response I received access token
<script type="text/javascript">
(function() {
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/client:plusone.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
})();
</script>
<script type="text/javascript">
(function() {
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/client:plusone.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
})();
var AuthStates = {google: null};
function signinCallback(authResult) {
if (authResult['status']['signed_in']) {
// Update the app to reflect a signed in user
// Hide the sign-in button now that the user is authorized, for example:
document.getElementById('signinButton').setAttribute('style', 'display: none');
//alert(authResult['code']);
console.log('code state: ' + authResult['code']);
//console.log('authResult : ' + authResult[]);
AuthStates.google = authResult;
console.log('authResult 1 : ' + authResult['status']['method']);
console.log('auth Result : ' + authResult['id_token']);
//{!access_token} = authResult['access_token'];
//{!code} = authResult['code'];
connection(authResult['access_token'], authResult['code']);
} else {
// Update the app to reflect a signed out user
// Possible error values:
// "user_signed_out" - User is signed-out
// "access_denied" - User denied access to your app
// "immediate_failed" - Could not automatically log in the user
console.log('Sign-in state: ' + authResult['error']);
}
}
</script>
<apex:outputPanel >
<span id="signinButton">
<span
class="g-signin"
data-callback="signinCallback"
data-clientid="clientid"
data-cookiepolicy="single_host_origin"
data-scope="https://www.googleapis.com/auth/gmail.readonly"
data-response_type="code"
data-redirect_uri="http://test-on.ap1.visual.force.com/apex/Gmail_inbox">
</span>
</span>
<apex:form >
So as i got my access token from my request I can go directly for getting all information related to the logedin user. As I am getting all the information regarding the user I am trying to get all the emails related to him. Is I am doing right or I am wrong any place. I am very new with api and web service trying to learn. please do help me put out.
You're actually making an HTTP GET call to that URL ( https://www.googleapis.com/auth/gmail.readonly/?access_token= ...)? Isn't that just the auth scope identifier?
Once you have a valid Oauth2 token you can set in the Auth header then you can make HTTP requests to the API. For example, to list messages see:
https://developers.google.com/gmail/api/v1/reference/users/messages/list
That has the URL to access (GET https://www.googleapis.com/gmail/v1/users/me/messages ) then once you have the message IDs you can get the messages individually following: https://developers.google.com/gmail/api/v1/reference/users/messages/get (e.g. GET https://www.googleapis.com/gmail/v1/users/me/messages/ ).
Usually there are good client libraries for the Google APIs. Not sure if that works for you, but see, for example:
https://developers.google.com/gmail/api/downloads

Resources