Firebase Polymer PWA with custom domain, signInWithPopup doesn't work on mobile device - redirect

Testing on desktop works fine, the various provider's popups come up. On mobile device however with each provider a new browser window opens, but the address is the non-customized hosting URL of the firebase app and the sign-in flow halts.
Originally the Firebase documentation advises the non custom hosting URL to be used in the redirect URLs. I changed those for all providers to the custom one: https://valleydevfest.com/__/auth/handler instead of https://valleydevfest-620d6.firebaseapp.com/__/auth/handler (for both Facebook app, Twitter app and my Github app too). That didn't help at all and the mobile Chrome still redirects to some https://valleydevfest-620d6.firebaseapp.com/... address, which either halts loading or it loads a very broken version of the website (instead of the OAuth login).
Most relevant code:
var signIn = function(providerId) {
var provider = getProviderForProviderId(providerId);
var that = this;
return this.auth.signInWithPopup(provider).catch(function(error) {
...
https://github.com/gdgfresno/valleydevfest/blob/develop/scripts/helper/firebase.js#L43
How can I overcome that?
(Whole source of the app: https://github.com/gdgfresno/valleydevfest/tree/develop)

Related

Flutter app does not return to the app post user authentication from Google Oauth

I have created a flutter app which adds calendar events to user's google calendar using the google Calendar API. The app is doing the job but I have the following problem.
The app has initializeCalendarApi(); function(code attached below) in the initState() function which authenticates the user using Google Oauth. This is done by redirecting the user to user's browser where they select their Google account and click Allow to allow app to access their calendar. The problem is, once the authentication is done, the browser window is not closed automatically and the user has to close the browser app and shift to the flutter app manually which is bad for a production app.
How do I resolve this to make sure the user automatically gets back to the flutter app after clicking Allow.
Future<void> initializeCalendarApi() async {
var _clientID = new ClientId(Secret.getId(), "");
const _scopes = const [calendar.CalendarApi.calendarScope];
await clientViaUserConsent(_clientID, _scopes, prompt)
.then((AuthClient client) async {
CalendarClient.calendar = calendar.CalendarApi(client);
});
}
Image shows the final Page Obtained in browser after Oauth has been completed. I want to return my flutter app after successful authentication rather than this window opened in browser.

Updating old url to new url in PWA

I am trying to change the start_url of my PWA app from one page to another but need to understand the working. Can anyone please tell me what will happen to users of my PWA app user (with old start_url). Is there any some kind of update happen after which old user can get the updated start_url.
For example:
PWA with old start_url: www.testweb.com/oldurl
PWA with new start_url: www.testweb.com/newurl
will users of PWA with old URL will get any URL after I change the start_url.
With Chrome, it depends on whether you're on desktop or mobile. On desktop, changing the start_url will have no effect, but on Android, it should be updated within a day or two. See How Chrome handles updates to the web app manifest for details about how manifest changes affect an installed PWA.
My recommendation would be don't change the start_url but instead, use the service worker to redirect the browser to the new page. For example, you could use something like:
self.addEventListener('fetch', (event) => {
// Check if URL is old start_url, if so redirect to new URL
if (event.request.url.endsWith('/previous/start_url.html')) {
const resp = Response.redirect('/new/start_url.html', 301);
event.respondWith(resp);
}
});

Actions on Google implicit account linking works in simulator/browser, but not on device (via Google Home app)

I've implemented the implicit flow for Actions on Google account linking, and am using Dialogflow (previously API.AI) to define intents.
The full flow works in the device simulator (from AOG). The first intent gets a "It looks like your account isn't linked yet..." response, and the debug pane includes a URL to initiate linking:
https://assistant.google.com/services/auth/handoffs/auth/start?account_name=[account]#gmail.com&provider=[project_id]_dev&scopes=email&return_url=https://www.google.com/
If I follow this URI in a cache-less window:
I'm redirected to my app's authentication page
I choose to sign in with my Google account (same as [account] above)
I'm redirected to google.com with a success message in the URI bar
The simulator now accepts actions via my app and responds correctly
However, if I follow the same flow using a physical Google Home & the gH app for Android.
Device tells me account not yet linked
Open Google home and follow 'Link to [my app]' link
Browser opens to authentication page
Sign in as user
Redirected to a white page with a single link "Return to app", which has an href: about:invalid#zClosurez
Linking was unsuccessful, so additional attempts to run intents on the Google Home get the same "Account not yet linked" response.
I've inspected the intermediate access_token and state variables at length, and they all match and look to be correctly formatted:
Authentication URL (app sign in page): https://flowdash.co/auth/google?response_type=token&client_id=[client_id]&redirect_uri=https://oauth-redirect.googleusercontent.com/r/[project_id]&scope=email&state=[state]
After authenticating, redirected to (this is the white screen with 'return to app' broken link): https://oauth-redirect.googleusercontent.com/r/genzai-app#access_token=[token]&token_type=bearer&state=[state]
So, it seems there's something non-parallel about the way the simulator and physical devices work in terms of implicit flow account linking.
I've been struggling with this, and with the AOG support team for a very long time to no avail. Anyone else see a similar issue?
Updated with response redirect code:
Login handled by react-google-login component with profile & email scopes. On success we call:
finish_auth(id_token) {
let provider = {
uri: '/api/auth/google_auth',
params: ['client_id', 'redirect_uri', 'state', 'response_type'],
name: "Google Assistant"
}
if (provider) {
let data = {};
provider.params.forEach((p) => {
data[p] = this.props.location.query[p];
});
if (id_token) data.id_token = id_token;
api.post(provider.uri, data, (res) => {
if (res.redirect) window.location = res.redirect;
else if (res.error) toastr.error(res.error);
});
} else {
toastr.error("Provider not found");
}
}
provider.uri hits this API endpoint:
def google_auth(self):
client_id = self.request.get('client_id')
redirect_uri = self.request.get('redirect_uri')
state = self.request.get('state')
id_token = self.request.get('id_token')
redir_url = user = None
if client_id == DF_CLIENT_ID:
# Part of Google Home / API.AI auth flow
if redirect_uri == "https://oauth-redirect.googleusercontent.com/r/%s" % secrets.GOOGLE_PROJECT_ID:
if not user:
ok, _email, name = self.validate_google_id_token(id_token)
if ok:
user = User.GetByEmail(_email, create_if_missing=True, name=name)
if user:
access_token = user.aes_access_token(client_id=DF_CLIENT_ID)
redir_url = 'https://oauth-redirect.googleusercontent.com/r/%s#' % secrets.GOOGLE_PROJECT_ID
redir_url += urllib.urlencode({
'access_token': access_token,
'token_type': 'bearer',
'state': state
})
self.success = True
else:
self.message = "Malformed"
else:
self.message = "Malformed"
self.set_response({'redirect': redir_url}, debug=True)
I am able to make it work after a long time. We have to enable the webhook first and we can see how to enable the webhook in the dialog flow fulfillment docs If we are going to use Google Assistant, then we have to enable the Google Assistant Integration in the integrations first. Then follow the steps mentioned below for the Account Linking in actions on google:-
Go to google cloud console -> APIsand Services -> Credentials -> OAuth 2.0 client IDs -> Web client -> Note the client ID, client secret from there -> Download JSON - from json note down the project id, auth_uri, token_uri -> Authorised Redirect URIs -> White list our app's URL -> in this URL fixed part is https://oauth-redirect.googleusercontent.com/r/ and append the project id in the URL -> Save the changes
Actions on Google -> Account linking setup 1. Grant type = Authorisation code 2. Client info 1. Fill up client id,client secrtet, auth_uri, token_uri 2. Enter the auth uri as https://www.googleapis.com/auth and token_uri as https://www.googleapis.com/token 3. Save and run 4. It will show an error while running on the google assistant, but dont worry 5. Come back to the account linking section in the assistant settings and enter auth_uri as https://accounts.google.com/o/oauth2/auth and token_uri as https://accounts.google.com/o/oauth2/token 6. Put the scopes as https://www.googleapis.com/auth/userinfo.profile and https://www.googleapis.com/auth/userinfo.email and weare good to go. 7. Save the changes.
In the hosting server(heroku)logs, we can see the access token value and through access token, we can get the details regarding the email address.
Append the access token to this link "https://www.googleapis.com/oauth2/v1/userinfo?access_token=" and we can get the required details in the resulting json page.
`accessToken = req.get("originalRequest").get("data").get("user").get("accessToken")
r = requests.get(link)
print("Email Id= " + r.json()["email"])
print("Name= " + r.json()["name"])`
Not sure which python middleware or modules you are using but
self.set_response({'redirect': redir_url}, debug=True)
seems to be setting parameters for a returning a response which isn't correct. Instead you should redirect your response to the redirect_url. For example importing the redirect module in Flask or Django like:
from flask import redirect or from django.shortcuts import redirect
then redirect like:
return redirect(redirect_url)
It appears Google has made a change that has partially solved this problem in that it is now possible to complete the implicit account linking flow outside of the simulator, in the way outlined in my question.
It seems the problem stemmed from an odd handling (on the AOG side) of the client-side redirect case used after sign in with the Google sign-in button.
From Jeff Craig in this thread:
The current workaround, where we provide the "Return to app" link
currently what we're able to provide. The issue is with the way that
redirecting to custom-scheme URIs is handled in Chrome, specifically,
with regard to the redirect happening in the context of a user action.
XHR will break that context, so what is happening is that you click
the Google Sign-In Button, which triggers an XHR to Google's servers,
and then you (most likely) do a client-side redirect back to the
redirect_url we supply, our handler executes, and isn't able to do a
JS redirect to the custom scheme URI of the app, because were outside
of the context of a direct user click.
This is more of a problem with the Implicit (response_type=token) flow
than with the authorization code (response_type=code) flow, and the
"Return to app" link is the best fallback case we currently have,
though we are always looking for better solutions here as well.
The current behavior shows the 'Return to app' link, but as of last week, this link's href is no longer about:invalid#zClosurez, but instead successfully completes the sign-in and linking process. It's an odd and confusing UX that I hope Google will improve in the future, but it was sufficient to get my app approved by the AOG team without any changes to my flow.

Like option using cordova

I need a web and mobile application which will work on android, iphone and windows as well.
I want to use facebook login for my apps and customer can like my page after login thats why i am using cordova to convert my web app into android app but i need to integrate facebook-like option which i didn't get in plugin.
So i implemented this using oglike
$scope.facebookLike = function() {
if($localStorage.hasOwnProperty("accessToken") === true) {
$http.post("https://graph.facebook.com/me/og.likes?access_token="+$localStorage.accessToken+"&object=https://www.facebook.com/Nxtlife-Technologies-Ltd-UK-180614345644169/?ref=br_rs");
alert("like sucessfully done");
} else {
alert("Not signed in");
$scope.facebookLogin();
}
}
Problem:
The code will not throwing any error but after success message it didin't make any changes to my page. like count is remains same.
og.likes is for Open Graph objects – external URLs, outside of Faceook.
You can not like Facebook pages by any other means than the official Like button.

AgileToolkit OAuth add-on error 500 at facebook's mobile site

I am using the OAuth Facebook controller add-on for ATK4.
It works as expected when authenticating with Facebook from a regular desktop browser.
It works when authenticating using a mobile browser that is telling face book that it's a desktop browser.
It does not work when Facebook detects a mobile browser and redirects to m.facebook.com/dialog/oath.
What's more, is that it works fine for signups from mobile browsers (ie, when Facebook asks the user to give permission to the app).
The login flow stops with an Error 500 at:
https://m.facebook.com/dialog/oauth?redirect_uri={my_url_encoded_landing_page_where_the_OAuth_controller_lives}&scope=email&client_id={fb_app_id}
What the hell is going on here? There isn't some difference between the Facebook mobile service and the regular one that the addon isn't taking care of, or is there?
It must be something I'm doing wrong. In init() on the page that handles the FB, I am doing the following:
function init(){
parent::init();
$f = $this->add("oauth/Controller_OAuth_Facebook", array('sign_method'=>'PLAINTEXT'));
if ($fbtoken = $f->check()) {
$f->setSignatureInfo();
$f->setAuthToken($fbtoken["access_token"], $fbtoken["expires"]);
$s = $this->add("sni/Controller_SNI_Facebook");
$s->setOAuth($f);
// ...
// grab profile from SNI, database lookup, session stuff, etc
// ...
}
}
I've tried all three sign_methods, and tried leaving it alone, but that doesn't make much difference because the user is not making it back to the controller with an access token to use anyway.
I tried creating a new app with Facebook and I get the same issues with a basically vanilla configuration on that. I've only marked and specified the "Website with Facebook Login" site URL integration.
The image below was captured from Chrome after overriding the user agent to a mobile device to trigger the forward to facebook's mobile servers:
Screen shot of request
Facebook closed my bug report with them stating that it's not an issue since no one else is reporting the bug. I am removing the ATK4 tag, as I get the same issue using the example PHP code provided by Facebook on GIT.
Created dedicated example here:
http://demo.ambienttech.lv/d.html?ns=d3
Example is downloadable and includes instructions of setting up facebook app as well. See if that helps.
Try This:
<?php
class page_fb extends Page {
function init(){
parent::init();
$f = $this->add("oauth/Controller_OAuth_Facebook");
$fbtoken = $this->api->recall("fbtoken");
if ($m = $_GET["error_msg"]){
$v=$this->add("View_Error");
$v->add("Text")->setHTML("You can't connect to the application.");
$v->add("Button")->setHTML("Try again")->js("click", $this->js()->univ()->location("fb"));
return;
}
if (!$fbtoken){
if ($fbtoken = $f->check("email")){
$this->api->memorize("fbtoken", $fbtoken);
$this->api->redirect($this->api->url("/index"));
}
} else {
$f->setSignatureInfo();
$f->setAuthToken($fbtoken["access_token"], $fbtoken["expires"]);
$c = $this->add("sni/Controller_SNI_Facebook");
$c->setOAuth($f);
if (!$this->api->recall("fbuserinfo")){
$this->api->memorize("fbuserinfo", $c->getUserProfile());
}
$info = $this->api->recall("fbuserinfo");
$username = $info->username;
$img = $c->customRequest("/" . $username . "/picture?type=large");
$this->api->memorize("userimg", $img);
$this->api->memorize("userinfo", $info);
if (!$this->api->auth->isLoggedIn()){
$this->api->auth->login($info->email);
}
$this->api->redirect($this->api->url("/index"));
}
}
}
I've got the same problem, but using PHP: just using a mobile web browser is not working, giving '500 internal server error'.
I'm just asking myself if exists a parameter for the method getLoginUrl to force return a non-mobile version of the authentication page...
I reported this issue here: https://github.com/atk4/atk4-addons/issues/35
Please stay tuned and if you can, you can always make changes yourself and pull request.
I can't test and fix this because strangely I still don't have smart phone :(
Something changed in FB's mobile OAuth service that is causing the error. I ran a test with my code base on a shorter URL (ie; http://domain.net/fb/ rather than http://development.project.domain.net/fb) and it works fine. I am not entirely sure of what exactly is causing the problem as Facebook refuses to acknowledge the issue as being on their server, but I have a few possible culprits that may be triggering the error on their side, but since they don't care, I don't either, and I am providing my results for anyone else who encounters this bs.
The environment I am developing in uses semi-complex (apparently) naming scheme. The development server has its own hostname under a subdomain. The issue may be caused by the fact that there are multiple components to the host portion of the URL or simply too many characters.
The name servers for the development environment are provided by DynDNS. Facebook's mobile OAuth service may be choking on the idea of a development site being hosted on a non-permanent IP address.
I'm not going to do anymore testing on this because it really is a problem with Facebook, not my code or servers, and it will work in production.