Skip to content

Implementation for Google OAuth #11

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"license": "MIT",
"scripts": {
"start": "ng serve",
"start:https": "ng serve --ssl true --host 0.0.0.0 --port 8443",
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we add a line in README.md to explain how to experience Oauth based application?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also we should probably mention how / where to make changes to make OAuth using popup instead of page refresh in this README.md section

"build": "ng build",
"lint": "ng lint",
"json:server": "json-server --delay 3000 --watch db.json",
Expand Down
1 change: 1 addition & 0 deletions src/app/app.routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,6 @@ export const ROUTES: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', loadChildren: './home/home.module#HomeModule', data: { state: 'home' } },
{ path: 'demo', loadChildren: './demo/demo.module#DemoModule', data: { state: 'demo' } },
{ path: 'oauth', loadChildren: './oauth/oauth.module#OAuthModule', data: { state: 'oauth' } },
{ path: '**', component: PageNotFoundComponent }
];
51 changes: 51 additions & 0 deletions src/app/appcommon/security/OAuth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
export interface IOAuthOptions {
AUTH_URL: string;
CLIENT_ID: string;
SCOPE: string[];
OAUTH_REDIRECT_URI: string;
}

interface IOAuth {
oAuthLogin(url: string): Promise<any>;
}

class OAuthBrowser implements IOAuth {
options: IOAuthOptions;
constructor(options: IOAuthOptions) {
this.options = options;
}

public oAuthLogin(url: string): Promise<any> {
return new Promise(function(resolve, reject) {
console.log('OAuth URL : ' + url);
window.location.href = url;
});
}
}

export class OAuth {
private options: IOAuthOptions;
private APP_SCOPE_DELIMITER = ' ';
private _oAuthClient: IOAuth;
private url: string;

constructor(options: IOAuthOptions) {
this.options = options;
this._oAuthClient = new OAuthBrowser(options);
this.url = `${options.AUTH_URL}?response_type=token&client_id=${options.CLIENT_ID}&redirect_uri=${
options.OAUTH_REDIRECT_URI
}&scope=${options.SCOPE.join(this.APP_SCOPE_DELIMITER)}`;
}

authenticate(): Promise<any> {
return this._oAuthClient.oAuthLogin(this.url);
}

getClientId(): string {
return this.options.CLIENT_ID;
}

getRedirectUri(): string {
return this.options.OAUTH_REDIRECT_URI;
}
}
1 change: 1 addition & 0 deletions src/app/appcommon/security/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './OAuth';
2 changes: 1 addition & 1 deletion src/app/appcommon/services/app.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ export class AppState {
* Use our state getter for the clone.
*/
const state = this.state;
return state.hasOwnProperty(prop) ? state[prop] : state;
return state.hasOwnProperty(prop) ? state[prop] : null;
}

public set(prop: string, value: any) {
Expand Down
15 changes: 15 additions & 0 deletions src/app/components/header/header.component.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { MenuItem } from 'primeng/primeng';
import { Component, OnInit } from '@angular/core';
import { OAuth } from '../../appcommon/security';
import { environment } from '../../../environments/environment';

@Component({
selector: 'app-header',
Expand All @@ -21,6 +23,19 @@ export class HeaderComponent implements OnInit {
items: [{ label: 'Project' }, { label: 'Other' }]
},
{ label: 'Open', routerLink: ['pagename'] },
{
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we add the "Login" and "Logged In User's name" in the toolbar instead on right aligned menu item?

This way it will be far more "real life"..

label: 'Google OAuth',
command: event => {
event.originalEvent.preventDefault();
const oAuth = new OAuth({
AUTH_URL: environment.AUTH_URL,
CLIENT_ID: environment.OAUTH_CLIENT_ID,
SCOPE: ['profile'],
OAUTH_REDIRECT_URI: window.location.origin + '/oauth/'
});
oAuth.authenticate();
}
},
{ label: 'Quit', routerLink: ['pagename'] }
]
},
Expand Down
12 changes: 12 additions & 0 deletions src/app/oauth/components/oauth.component.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<div class="oauth-home">
<div>
Your Google Access Token :
<span class="information">{{accessToken}}</span>
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This page is good...
May be we show this as a tooltip / on-click tooltip to user when user clicks on "Signed-In User" in the toolbar icon as suggested elsewhere.

</div>
<br/>
<br/>
<div>
User Details :
<pre class="information">{{userInfo | json}}</pre>
</div>
</div>
10 changes: 10 additions & 0 deletions src/app/oauth/components/oauth.component.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
.oauth-home {
padding: 20px;

.information {
background-color: #cdcdcd;
border: solid 1px #a0a0a0;
border-radius: 5px;
padding: 10px;
}
}
47 changes: 47 additions & 0 deletions src/app/oauth/components/oauth.component.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { AppState } from '../../appcommon/services/app.service';
import { UserInfoService } from '../services/userinfo.service';

@Component({
selector: 'app-oauth',
templateUrl: './oauth.component.html',
styleUrls: ['./oauth.component.scss']
})
export class OAuthComponent implements OnInit {
userInfo: any;
accessToken: string;

constructor(
private appState: AppState,
private activeRoute: ActivatedRoute,
private router: Router,
private service: UserInfoService
) {
this.activeRoute.params.subscribe(params => {
const url = window.location.href;
if (url.split('#').length > 1) {
const responseParameters = url.split('#')[1].split('&');
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This type of URL splitting is very shaky.. as # is not guaranteed to be present in the URL.

We should be using paramMap to read params.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is while reading the access token from URL. This is standard OAuth specification that the values will be separated by #

const parsedResponse = {};
for (let i = 0; i < responseParameters.length; i++) {
parsedResponse[responseParameters[i].split('=')[0]] = responseParameters[i].split('=')[1];
}
if (parsedResponse['access_token'] !== undefined && parsedResponse['access_token'] !== null) {
this.appState.set('accessToken', parsedResponse['access_token']);
this.router.navigate(['oauth']);
}
}
});
}

ngOnInit() {
this.accessToken = this.appState.get('accessToken');
if (this.accessToken) {
this.service.getUserInfo(this.accessToken).subscribe(data => {
this.userInfo = data;
});
} else {
this.router.navigate(['home']);
}
}
}
15 changes: 15 additions & 0 deletions src/app/oauth/oauth.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { AppcommonModule } from './../appcommon/appcommon.module';
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Routes, RouterModule } from '@angular/router';
import { OAuthComponent } from './components/oauth.component';
import { UserInfoService } from './services/userinfo.service';

const routes: Routes = [{ path: '', component: OAuthComponent }];

@NgModule({
imports: [CommonModule, AppcommonModule, RouterModule.forChild(routes)],
providers: [UserInfoService],
declarations: [OAuthComponent]
})
export class OAuthModule {}
12 changes: 12 additions & 0 deletions src/app/oauth/services/userinfo.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { Observable } from 'rxjs/Observable';
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class UserInfoService {
constructor(private http: HttpClient) {}

public getUserInfo(accessToken): Observable<any> {
return this.http.post(`https://www.googleapis.com/oauth2/v3/userinfo?access_token=${accessToken}`, '');
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this URL be externalized in environment file?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Forgot to move it to env file.. will make this change.

}
}
4 changes: 3 additions & 1 deletion src/environments/environment.prod.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
export const environment = {
production: true,
LOG_LEVEL: 'warn'
LOG_LEVEL: 'warn',
AUTH_URL: 'https://accounts.google.com/o/oauth2/v2/auth',
OAUTH_CLIENT_ID: '603712460284-9c20vfg98ra1cecdhu2r84d4ij6erpcr.apps.googleusercontent.com'
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this CLIENT_ID permanent?

Also - can we add this in README.md section on OAuth that such client is needed and how do we register to get it?

};
4 changes: 3 additions & 1 deletion src/environments/environment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,7 @@

export const environment = {
production: false,
LOG_LEVEL: 'debug'
LOG_LEVEL: 'debug',
AUTH_URL: 'https://accounts.google.com/o/oauth2/v2/auth',
OAUTH_CLIENT_ID: '603712460284-9c20vfg98ra1cecdhu2r84d4ij6erpcr.apps.googleusercontent.com'
};