Refresh token in Gmail API? - gmail-api

After successful login, I am getting access token, expire token type, and this stuff in my console by "console.log("my response ",response)". But there is no refresh token. how to get a refresh token.
And 2nd question is, How to get an access token using a refresh token?
I am using JavaScript.
And guide me is this a best way way to get an access token?
Successful login is not giving refresh token, without refresh token how can I refresh my access token?
Here is my code
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>FIFV Dashboard</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<link rel="stylesheet" href="home.css">
<script src="https://apis.google.com/js/api.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons#1.9.1/font/bootstrap-icons.css">
</head>
<body>
<div class="wrapper fadeInDown">
<div id="formContent">
<!-- Tabs Titles -->
<!-- Icon -->
<div class="fadeIn first">
<img src="Images/company Logo.png" id="icon" alt="User Icon" />
</div>
<!-- Login Form -->
<form>
<h3 class="heading"> Welcome to
FIFV authentication </h3>
<p class="shortPara">Please authenticate yourself to get access to the dashboard.</p>
<!-- <input type="submit" class="fadeIn fourth" value="Log In" href="Home.html"> -->
<br>
<button onclick="authenticate().then(loadClient)" type="button" class="btn"><a>Authorise</a></button>
<p id="errorMsg"></p>
</form>
</div>
</div>
<script>
/**
* Sample JavaScript code for gmail.users.messages.list
* See instructions for running APIs Explorer code samples locally:
* https://developers.google.com/explorer-help/code-samples#javascript
*/
// Authentication code
function authenticate() {
return gapi.auth2.getAuthInstance()
.signIn({ scope: "https://www.googleapis.com/auth/gmail.modify https://www.googleapis.com/auth/gmail.compose https://www.googleapis.com/auth/gmail.readonly" })
.then(function (response) { console.log("Sign-in successful", response);
console.log("Access Token", response.Bc.access_token)
localStorage.setItem("accessToken", response.Bc.access_token)
localStorage.setItem("expire", response.Bc.expires_in)
},
function (err) { console.error("Error signing in", err); });
}
function loadClient() {
gapi.client.setApiKey("my-api-key");
return gapi.client.load("https://gmail.googleapis.com/$discovery/rest?version=v1")
.then(function () { console.log("GAPI client loaded for API"); },
function (err) { console.error("Error loading GAPI client for API", err);
document.getElementById('errorMsg').innerHTML = err;
});
}
gapi.load("client:auth2", function () {
gapi.auth2.init({
client_id: "my-client-id",
plugin_name: "hello"
});
});
function logout() {
fetch("https://oauth2.googleapis.com/revoke?token=" + token,
{
method: 'POST',
headers: {
"Content-type": "application/x-www-form-urlencoded"
}
})
.then((data) => {
location.href = "http://localhost:5500/index.html"
})
}
</script>
<script src="home.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/#popperjs/core#2.11.6/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/js/bootstrap.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</body>
</html>

I was reviewing the Google Documentation for JavaScript, and I found the following sample that might help you:
if (gapi.client.getToken() === null) {
// Prompt the user to select a Google Account and ask for consent to share their data
// when establishing a new session.
tokenClient.requestAccessToken({prompt: 'consent'});
} else {
// Skip display of account chooser and consent dialog for an existing session.
tokenClient.requestAccessToken({prompt: ''});
}
}
You can read more information about this here, and information about the refresh token can be found here.
Lastly, you can read the information in this question. It has a lot of information about the refresh token.

Related

Message in console.log is not showed anything i proved

i'm roking in a ASP.NET CORE MVC project and i have a React class that is a component used in a razor page.
I tried in every single way that i found in the web but seems like console.log don't show anything.
The component is render on the page and shows the properties correctly:
and this is the inspector:
class App extends React.Component{
componentDidMount() {
console.log('hi')
}
render() {
console.log(this.props)
const { Property1, Property2 } = this.props
const handler = (event) => {
console.log(event);
}
return (
<div>
<button onClick={handler}> clicca </button>
{console.log(this.props)}
<p>Property1: {Property1}</p>
<p>Property2: {Property2}</p>
<div className="box">Sono un box</div>
</div>
);
}
}
Non of them works and i don't understand why
Index.cshtml (just a simple page with the component)
#Html.React("App",new { Property1 = "value1", Property2 = "value2" })
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/remarkable/1.7.1/remarkable.min.js"></script>
Program.cs:
//configure the services for application
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddMvc().AddRazorRuntimeCompilation();
//builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
builder.Services.AddReact();
builder.Services.AddHttpContextAccessor();
builder.Services.AddJsEngineSwitcher(option => option.DefaultEngineName = V8JsEngine.EngineName).AddV8();
var app = builder.Build();
// configure middleware
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseReact(config => {
config.AddScript("~/js/App.jsx");
});
ReactSiteConfiguration.Configuration.JsonSerializerSettings.ContractResolver = new DefaultContractResolver();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
}
[EDIT]
with ReactInitJavascript at the end of the Index.cshtml when i start the page, data are showen like the component was loaded correcty, but in the inspectore says that component App is not defined.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title> - SportData</title>
<link rel="stylesheet" href="/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="/css/site.css?v=_5WottCwlLwmnX08KuvZv3ryqfP5c42il12e6LRxHqg" />
<link rel="stylesheet" href="/css/card.css?v=ZXutknPLolnM8AJ6Dofwp6kVw_54LAeyyWSi8YLbEeY" />
</head>
<body>
<div class="container">
<main role="main" class="pb-3">
<div id="react_0HMO2J0AM8AAV"><div data-reactroot=""><button> clicca </button><p>Property1: <!-- -->value1</p><p>Property2: <!-- -->value2</p><div class="box">Sono un box</div></div></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/remarkable/1.7.1/remarkable.min.js"></script>
<script>ReactDOM.hydrate(React.createElement(App, {"Property1":"value1","Property2":"value2"}), document.getElementById("react_0HMO2J0AM8AAV"));
</script> --> this is the error line
</main>
</div>
<script src="/lib/jquery/dist/jquery.min.js"></script>
<script src="/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<!-- Visual Studio Browser Link -->
<script type="text/javascript" src="/_vs/browserLink" async="async" id="__browserLink_initializationData" data-requestId="6501a3e3c110465981ca8b97a81c1842" data-requestMappingFromServer="false" data-connectUrl="http://localhost:57481/dc7f1eca94044a1ca53edfa6de85d80f/browserLink"></script>
<!-- End Browser Link -->
<script src="/_framework/aspnetcore-browser-refresh.js"></script></body>
</html>

cakephp 3.8.13 handle unauthorized request, response in JSON

I have implemented https://github.com/ADmad/cakephp-jwt-auth in my CakePHP application. My problem is whenever there is an unauthorized request it responds with HTML.
<html>
<head>
<meta charset="utf-8"/>
<title>
CakePHP: the rapid development php framework:
Error </title>
<link href="/favicon.ico" type="image/x-icon" rel="icon"/>
<link href="/favicon.ico" type="image/x-icon" rel="shortcut icon"/>
<link rel="stylesheet" href="/css/cake.generic.css"/>
</head>
<body>
<div id="container">
<div id="header">
<h1>
CakePHP: the rapid development php framework
</h1>
</div>
<div id="content">
<h2>Unauthorized</h2>
<p class="error">
<strong>Error: </strong>
An Internal Error Has Occurred.
</p>
</div>
</div>
</body>
</html>
But according to this tutorial https://www.bravo-kernel.com/2015/04/how-to-add-jwt-authentication-to-a-cakephp-3-rest-api/, it will respond with JSON. An example response from the tutorial is
{
"success": false,
"data": {
"message": "You are not authorized to access that location.",
"url": "\/api\/cocktails.json",
"code": 401
}
}
This is my router
Router::prefix('api', function ($routes) {
$routes->extensions(['json', 'xml']);
Router::connect('/api/check', ['_method' => 'GET','controller' => 'EmailNotification', 'action' => 'check', 'prefix' => 'api']);
$routes->fallbacks('DashedRoute');
});
How can I handle this? I want the unauthorised response in JSON. Thank you.
can you try sending your http request with Accept:application/json header

Validate Gmail account and retrieve basic profile info

Is there a way to validate account existence and retrieve basic gmail account info such as name and photo url using only email ?
Previously it was possible to get account photoUrl using the following endpoint:
http://picasaweb.google.com/data/entry/api/user/<hereYourUserIdOrYourEmail>?alt=json
but it was shut down.
You can't access that information with the gmail-api. If you are the admin of a g suite domain, you could use the directory API to obtain that info.
If the application is not intended for a specific domain, you can implement google oauth2 with JavaScript in the front-end, the user would have to authenticate and this way you'll be able to access the basic information. You need to create a project in cloud.google.com and get credentials (a clientID is needed in the code). More explanation here:
https://developers.google.com/identity/sign-in/web/sign-in
Implementation example (only clientID missing):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="google-signin-client_id" content="#clientId">
<title>Oauth2 web</title>
<!-- Google library -->
<script src="https://apis.google.com/js/platform.js" async defer></script>
<!-- Jquery library to print the information easier -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<!-- Bootstrap library for the button style-->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<div id="profileinfo">
</div>
<div class="g-signin2" data-onsuccess="onSignIn"></div>
<script>
function onSignIn(googleUser) {
var profile = googleUser.getBasicProfile();
console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead.
console.log('Name: ' + profile.getName());
console.log('Image URL: ' + profile.getImageUrl());
console.log('Email: ' + profile.getEmail()); // This is null if the 'email' scope is not present.
$("#profileinfo").append("<h2>Sup " + profile.getName() + ", welcome home my friend</h2>");
$("#profileinfo").append("<img style='width:250px;height:250px' src='" + profile.getImageUrl() + "'><br><br>");
$("#profileinfo").append("<p>Your email is: " + profile.getEmail() + "</p>");
}
</script>
<button type="button" class="btn btn-danger" onclick="signOut();">Sign out</button>
<script>
function signOut() {
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function () {
console.log('User signed out.');
$("#profileinfo").empty();
$("#profileinfo").append("<h2>Goodbye old friend</h2>");
});
}
</script>
</body>
</html>

AngularJS with Firebase Authentication

I am trying to create a user login page using AngularJS and firebase authentication (Email and password).
I looked up a couple of tutorials online and wrote the codes, but it does not seem to work.
Below are my codes.
1) page.html
<ion-view id="page646">
<ion-content padding="true" class="has-header">
<form>
<label class="item item-input">
<span class="input-label">EMAIL</span>
<input type="email" placeholder="" ng-model="user.email">
</label>
<label class="item item-input">
<span class="input-label">PASSWORD</span>
<input type="text" placeholder="" ng-model="user.pass">
</label>
<div style="margin-right:-20px;">
<button style="left:-10px;" class="button button-positive button-full"ng-click="signIn()">SIGN IN</button>
</div>
</form>
</ion-content>
</ion-view>
2) index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title></title>
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.3.0/firebase.js">
</script>
<script src="https://www.gstatic.com/firebasejs/5.3.0/firebase-app.js">
</script>
<script src="https://www.gstatic.com/firebasejs/5.3.0/firebase-auth.js">
</script>
<!-- AngularFire -->
<script
src="https://cdn.firebase.com/libs/angularfire/2.3.0/angularfire.min.js">
</script>
<!-- cordova script (this will be a 404 during development) -->
<script src="cordova.js"></script>
<!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
<link href="css/ionic.app.css" rel="stylesheet">
-->
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<style type="text/css">
.platform-ios .manual-ios-statusbar-padding{
padding-top:20px;
}
.manual-remove-top-padding{
padding-top:0px;
}
.manual-remove-top-padding .scroll{
padding-top:0px !important;
}
ion-list.manual-list-fullwidth div.list, .list.card.manual-card-fullwidth {
margin-left:-10px;
margin-right:-10px;
}
ion-list.manual-list-fullwidth div.list > .item, .list.card.manual-card-fullwidth > .item {
border-radius:0px;
border-left:0px;
border-right: 0px;
}
.show-list-numbers-and-dots ul{
list-style-type: disc;
padding-left:40px;
}
.show-list-numbers-and-dots ol{
list-style-type: decimal;
padding-left:40px;
}
</style>
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
<script src="js/routes.js"></script>
<script src="js/directives.js"></script>
<script src="js/services.js"></script>
<script src="lib/ngCordova/"></script>
</head>
<body ng-app="app" animation="slide-left-right-ios7">
<div>
<div>
<ion-nav-bar class="bar-stable">
<ion-nav-back-button></ion-nav-back-button>
</ion-nav-bar>
<ion-nav-view></ion-nav-view>
</div>
</div>
</body>
</html>
3) controller.js
.controller('pASSWORDGMCtrl', ['$scope', '$stateParams', 'aaaService',
function ($scope, $stateParams, aaaService) {
$scope.user = {
email:"",
pass:"",
}
$scope.signIn = function(){
aaaService.login($scope.user.email, $scope.user.pass);
}
aaaService.status();
$scope.signOut = function(){
aaaService.signout();
}
}])
4) Firebase-aaa.js
angular.module('firebaseAaa', ['firebase'])
.factory('aaaService', ['$firebaseArray','$firebaseAuth',
function($firebaseArray, $firebaseAuth){
var config = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: ""
};
if(!firebase.apps.length){
firebase.initializeApp(config);
}
var ref;
var adminArray;
return{
status: function(){
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
// if(loggingIn){
alert("Login success.");
ref = firebase.database().ref().child("Admin/" + user.uid);
adminArray = $firebaseArray(ref);
}
// loggingIn=false;
else {
// No user is signed in.
}
});
},
login: function(email, pass) {
firebase.auth().signInWithEmailAndPassword('abc#gmail.com', 'aaa').catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
alert("Error signing in user: ", errorCode + " " + errorMessage);
});
},
signout: function() {
firebase.auth().signOut().then(function() {
// Sign-out successful.
alert("You are now signed out.");
// loggingIn= false;
}).catch(function(error) {
// An error happened.
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
alert("Error signout: ", errorCode + " " + errorMessage);
});
},
}
}])
When I was trying out the codes, I got 'not logged in'.
I was watching at the firebase auth tutorial, there was a part where he did not enable the email and password auth. While he was trying the codes, he got an error in the console stating that the firebase email and password auth have yet been enabled.
I tried disabling mine, hoping to see the same error, but it did not turn out that way. It only says 'not logged in'.
I could not find the problem to it.
My question is how do i get a successful even for signInWithEmailAndPassword.
You need to move these bits, out of the sign in function
$scope.user = {
email:"",
pass:"",
}
It re-initialises the object "user" to empty value, plus the onAuthStateChanged should be outside too.

Cannot retrieve JSON, using ngResource

I'm trying to retrieve some JSON from a URL, but I am getting nowhere. This is for a small football application I'm trying to build (probably for personal use), mainly to get better at using Angular 1, (before using Angular 2).
http://api.football-data.org/code_samples
As you can see, there is not Angular JS example that I can use and I am closely trying to copy the javascript example.
http://api.football-data.org/v1/competitions/424
This is the data that I am trying to display, via the ngResource way. I followed a Udemy Tutorial and if possible, I would like someone to do an example, using this way, please. P.S. API KEY IS FREE (http://api.football-data.org/client/register)! JUST E-MAIL AND YOU WILL GET ONE BACK INSTANTLY!
If someone could help me with this. I would very much appreciate it.
Thanks
HTML
<!DOCTYPE html>
<html lang="en-gb" ng-app="quickEleven">
<head>
<title>AngularJS Football Stats</title>
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<meta charset="UTF-8">
<!-- load bootstrap and fontawesome via CDN -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" />
<style>
html, body, input, select, textarea
{
font-size: 1.05em !important;
}
</style>
<!-- load angular via CDN -->
<script src="//code.angularjs.org/1.3.0-rc.2/angular.min.js"></script>
<script src="//code.angularjs.org/1.3.0-rc.2/angular-route.min.js"></script>
<script src="//code.angularjs.org/1.3.0-rc.2/angular-resource.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<header>
<nav class="navbar navbar-default">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="/">AngularJS Football</a>
</div>
<ul class="nav navbar-nav navbar-right">
<li><i class="fa fa-home"></i> Home</li>
</ul>
</div>
</nav>
</header>
<div class="container">
<div ng-controller="homeController"></div>
</div>
</body>
</html>
JS
// MODULE
var quickEleven = angular.module('quickEleven', ['ngRoute', 'ngResource']);
// CONTROLLERS
quickEleven.controller('homeController', ['$scope', '$resource', 'cityService', function($scope, $resource, cityService) {
$scope.footballAPI =
$resource("http://api.football-data.org/v1/competitions/424", {headers: {"X-Auth-Token": "<API TOKEN KEY>"}}, { get: { method: "JSONP"}
});
$scope.fussball = $scope.footballAPI.get({});
console.log($scope.fussball);
}]);
Take a time to read about $resource , you did some error, like setting header.
USAGE:
$resource(url, [paramDefaults], [actions], options);
paramDefaults: Default values for url parameters.
So with your defined resouces, the token wont go to header but as parameter, and API will return a 404. You should set headers for every method:
And you don't need to use jsonp, get will work
eg:
$resource("http://api.football-data.org/v1/competitions/:competitionId", {}, {
get: {
method: "GET",
headers: {
"X-Auth-Token": "<API TOKEN KEY>"
}
}
});
For calling the method:
"class" actions without a body: Resource.action([parameters],
[success], [error]) "class" actions with a body:
Resource.action([parameters], postData, [success], [error])
So calling get for competition id 424 is:
$scope.footballAPI.get({
competitionId: 424
}, function(data) {
$scope.fussball = data;
}, function(err) {
console.log('error:', err);
});

Resources