Skip to content

Instantly share code, notes, and snippets.

@saptarshibasu
Last active August 29, 2018 03:41
Show Gist options
  • Save saptarshibasu/d7a1470d5d9d38e82c9c334f8aa43cba to your computer and use it in GitHub Desktop.
Save saptarshibasu/d7a1470d5d9d38e82c9c334f8aa43cba to your computer and use it in GitHub Desktop.
[User Authentication Using Google OAuth 2.0 APIs for TVs & Devices] This is an Angular service that invokes the Google APIs to authenticate a user in an app that doesn't run on a browser, for e.g. a desktop app. This service uses RxJS to retry the REST API calls at a specific interval in case of failure due to unstable internet connection. #Angu…
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { retryWhen, delay, tap, scan, concatMap } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class GoogleDeviceAuthService {
private readonly client_id = "<client-id>";
private readonly client_secret = "<client-secret>";
private readonly userCodeRequest = {
"client_id": this.client_id,
"scope": "email profile"
};
private readonly pollGoogleAuthServerRequestTemplate = {
"client_id": this.client_id,
"client_secret": this.client_secret,
"code": "",
"grant_type": "http://oauth.net/grant_type/device/1.0"
}
private readonly userCodeUrl = "https://accounts.google.com/o/oauth2/device/code";
private readonly pollGoogleAuthServerUrl = "https://www.googleapis.com/oauth2/v4/token";
constructor(private readonly http: HttpClient) { }
public getUserCode() {
return this.http.post(this.userCodeUrl, this.userCodeRequest)
.pipe(
retryWhen(err => err.pipe(
scan(
(retryCount, err) => {
if (retryCount > 3)
throw err;
else
return retryCount + 1;
}, 0
),
delay(1000),
tap(err => console.log("Retrying...", err))
)));
}
public checkAuthServerForUserInput(deviceCode) {
let pollGoogleAuthServerRequest = { ...this.pollGoogleAuthServerRequestTemplate, ...{ "code": deviceCode } };
return this.http.post(this.pollGoogleAuthServerUrl, pollGoogleAuthServerRequest)
.pipe(
retryWhen(err => err.pipe(
scan(
(retryCount, err) => {
if (retryCount > 3)
throw err;
else
return retryCount + 1;
}, 0
),
delay(1000),
tap(err => console.log("Retrying...", err))
)));;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment