-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
googleStrategy.ts
181 lines (158 loc) · 5.53 KB
/
googleStrategy.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
import { OakContext, Options, AuthData, TokenData } from './types.ts';
/**
* Creates an instance of `GoogleStrategy`.
*
* * Options:
*
* - `clientID`: string Required
* - redirect_uri: string Required
* - response_type: string Required
* - scope: string Required
* - access_type: string Recommended
* - state: string Recommended
* - included_granted_access: string Optional
* - login_hint: string Optional
* - prompt: string Optional
*
* Examples:
*
* dashport.use(new GoogleStrategy({
* authorizationURL: 'https://www.example.com/oauth2/authorize',
* tokenURL: 'https://www.example.com/oauth2/token',
* clientID: '123-456-789',
* clientSecret: 'shhh-its-a-secret'
* callbackURL: 'https://www.example.net/auth/example/callback'
* },
* function(accessToken, refreshToken, profile, done) {
* User.findOrCreate(..., function (err, user) {
* done(err, user);
* });
* }
* ));
*
*/
export default class GoogleStrategy {
name: string = 'google'
options: Options;
uriFromParams:string;
/**
* @constructor
* @param {Object} options
* @api public
*/
constructor (options: Options) {
if (!options.client_id || !options.redirect_uri || !options.response_type || !options.scope || !options.client_secret) {
throw new Error('ERROR in GoogleStrategy constructor: Missing required arguments');
}
this.options = options;
// preStep1 request permission
// CONSTRUCTS THE REDIRECT URI FROM THE PARAMETERS PROVIDED
const paramArray: string[][] = Object.entries(options);
let paramString: string = '';
for (let i = 0; i < paramArray.length; i++) {
let [key, value] = paramArray[i];
if (key === 'client_secret' || key === 'grant_type') continue;
paramString += (key + '=');
if (i < paramArray.length - 1) paramString += (value + '&');
else paramString += value;
}
this.uriFromParams = paramString;
}
async router(ctx: OakContext, next: Function) {
// GO_Step 1 Request Permission
if (!ctx.request.url.search) return await this.authorize(ctx, next);
// GO_Step 2-3 Exchange code for Token
if (ctx.request.url.search.slice(1, 5) === 'code') return this.getAuthToken(ctx, next);
}
// sends the programatically constructed uri to Google's oauth 2.0 server (step 2)
async authorize(ctx: OakContext, next: Function) {
return await ctx.response.redirect('https://accounts.google.com/o/oauth2/v2/auth?' + this.uriFromParams);
}
// handle oauth 2.0 server response (step 4)
async getAuthToken(ctx: OakContext, next: Function) {
const OGURI: string = ctx.request.url.search;
if (OGURI.includes('error')) {
return new Error('ERROR in getAuthToken: Received an error from auth token code request.');
}
// splits the string at the =, storing the first part in URI1[0] and the part we want in URI1[1]
let URI1: string[] = OGURI.split('=');
// splits the string at the ampersand(&), storing the string with the access_token in URI2[0]
// and the other parameters at URI2[n]
const URI2: string[] = URI1[1].split('&');
const code: string = this.parseCode(URI2[0]);
const options: any = {
method: 'POST',
headers: { "content-type": "application/json" },
body: JSON.stringify({
client_id: this.options.client_id,
client_secret: this.options.client_secret,
code: code,
grant_type: this.options.grant_type,
redirect_uri: this.options.redirect_uri
})
}
try {
let data: any = await fetch('https://oauth2.googleapis.com/token', options);
data = await data.json();
return this.getAuthData(data);
} catch(err) {
return new Error(`ERROR in getAuthToken: Unable to obtain token - ${err}`);
}
}
async getAuthData(parsed: TokenData){
const authData: AuthData = {
tokenData: {
access_token: parsed.access_token,
expires_in: parsed.expires_in,
scope: parsed.scope,
token_type: parsed.token_type,
id_token: parsed.id_token
},
userInfo: {
provider: '',
providerUserId: ''
}
};
const options: any = {
headers: { 'Authorization': 'Bearer '+ parsed.access_token }
};
try {
let data: any = await fetch('https://www.googleapis.com/oauth2/v2/userinfo', options);
data = await data.json();
authData.userInfo = {
provider: this.name,
providerUserId: data.id,
displayName: data.name,
name: {
familyName: data.family_name,
givenName: data.given_name,
},
emails: [data.email]
};
return authData;
} catch(err) {
return new Error(`ERROR in getAuthData: Unable to obtain auth data - ${err}`);
}
}
parseCode(encodedCode: string): string {
const replacements: { [name: string] : string } = {
"%24": "$",
"%26": "&",
"%2B": "+",
"%2C": ",",
"%2F": "/",
"%3A": ":",
"%3B": ";",
"%3D": "=",
"%3F": "?",
"%40": "@"
}
const toReplaceArray: string[] = Object.keys(replacements);
for(let i = 0; i < toReplaceArray.length; i++) {
while (encodedCode.includes(toReplaceArray[i])) {
encodedCode = encodedCode.replace(toReplaceArray[i], replacements[toReplaceArray[i]]);
}
}
return encodedCode;
}
}