-
Notifications
You must be signed in to change notification settings - Fork 0
/
gmail-service.bsh
391 lines (316 loc) · 14.4 KB
/
gmail-service.bsh
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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
#! /bin/bash
## gmail-service.bsh last update: 2018-02-13
##
## Bash script to create a google-gmail authentication with a service,
## using the default NeDB database.
##
## Be sure to run the feathers install gist first!
## a special shout-out THANK you to feathers slackware Freeline for providing me the code to retrieve the login information.
## ./config/default.json changes -- YOU WILL NEED TO CHANGE THESE!
HOST='fastfeathers.website' ;
GOOGLE_KEY='119068144580-gpeiXXXXXXXXXXXXXXXXXXXXXXXXXXgs.apps.googleusercontent.com' ;
GOOGLE_SECRET='m-RXXXXXXXXXXXXXpJIajwpN' ;
### get credentials here: https://console.developers.google.com/apis/credentials/
echo -n 'node version: ' ; node --version ; ## 8.15 at the time of this writing
if [ $? -ne 0 ]; then
echo 'Node has not yet been installed!';
exit 1;
fi
echo -n 'npm version: ' ; npm --version ; ## 6.7.0 at the time of this writing
if [ $? -ne 0 ]; then
echo 'NPM has not yet been installed!';
exit 1;
fi
echo -n 'feathers version: ' ; feathers --version ; ## 3.9 at the time of this writing
if [ $? -ne 0 ]; then
echo 'Feathers has not yet been installed!';
exit 1;
fi
echo 'get your authentication information from https://console.developers.google.com/apis/credentials/oauthclient/';
## prompt for any/all constant-variable changes
read -p "Enter HOST or blank to use '$HOST': " tmpHost;
if [ ! -z "$tmpHost" ]; then
HOST=$tmpHost;
fi;
read -p "Enter GOOGLE_KEY or blank to use '$GOOGLE_KEY': " tmpGOOGLE_KEY;
if [ ! -z "$tmpGOOGLE_KEY" ]; then
GOOGLE_KEY=$tmpGOOGLE_KEY;
fi;
read -p "Enter GOOGLE_SECRET or blank to use '$GOOGLE_SECRET': " tmpGOOGLE_SECRET;
if [ ! -z "$tmpGOOGLE_SECRET" ]; then
GOOGLE_SECRET=$tmpGOOGLE_SECRET;
fi;
THIS_IPADDR=$(dig +short myip.opendns.com @resolver1.opendns.com. ;);
export HOST;
DOMAIN_IP=$(dig ${HOST} | grep "$(printf '\t')IN$(printf '\t')A$(printf '\t')" | grep -oE '((1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\.){3}(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])');
FileNameWithExtension=${0##*/} ;
FileNameWithoutExtension=${FileNameWithExtension%.*} ;
TimeStamp=$(date "+%Y-%m-%d %r") ;
commonPath="$(readlink -f $0 | xargs dirname)"/common;
rm -Rf ./${FileNameWithoutExtension} ; ## just in case one already exists.
mkdir ./${FileNameWithoutExtension} && cd ./${FileNameWithoutExtension} ;
. ${commonPath}/createApp.bsh;
. ${commonPath}/gmailNedbAuth.bsh;
## feathers generate hook for user "service";
expect <(cat <<'END_OF_GENERATE_BEFORE_HOOK'
# generates a "BEFORE--CREATE/UPDATE" hook named "user-hook" for the "users" service for Google
# written from https://docs.feathersjs.com/api/authentication/oauth2.html#customizing-the-oauth-response
set timeout -1
set UPARROW \x1B\[A;
set DOWNARROW \x1B\[B;
set SPACE \x20;
set RETURN \x0d;
spawn feathers generate hook ;
expect -re ".*What is the name of the hook\?.*"
send -- "user-hook${RETURN}"
expect -re "What kind of hook should it be\?"
send -- "${DOWNARROW}${RETURN}"
## downarrow return selects 'before'
expect -re "What service\\\(s\\\) should this hook be for \\\(select none to add it yourself\\\)\?"
send -- "${DOWNARROW}${SPACE}${RETURN}"
## downarrow space return selects 'users'
expect -re "What methods should the hook be for \\\(select none to add it yourself\\\)\?"
send -- "${DOWNARROW}${DOWNARROW}${DOWNARROW}${SPACE}${DOWNARROW}${SPACE}${RETURN}"
## downarrow (3 times) space downarrow(1) space selects 'create' and 'update'
expect eof
END_OF_GENERATE_BEFORE_HOOK
) ## end of feathers generate hook
## edit the user-hook.js to extract the custom login stuff, like username, first-name, etc
sed --in-place --file=- ./src/hooks/user-hook.js <<END_OF_SED_USER_HOOK ;
3i\
\\
\\
\/* code added by ${FileNameWithExtension} ${TimeStamp} *\/ \\
const logger = require('winston');\\
const _ = require('lodash');\\
\/* end of code added by ${FileNameWithExtension} ${TimeStamp} *\/ \\
/^ return async context => {$/a\
\/* code added by ${FileNameWithExtension} ${TimeStamp} *\/ \\
if ( _.has(context, 'data.google.profile') ){\\
if ( _.has(context.data.google.profile, 'displayName' ) ) {\\
context.data.displayName = context.data.google.profile.displayName;\\
logger.info('displayName: ' + context.data.displayName); \\
}\\
if ( _.has(context.data.google.profile, 'emails' ) ) {\\
context.data.email = context.data.google.profile.emails.find(email => email.value).value;\\
logger.info('email: ' + context.data.email);\\
}\\
if ( _.has(context.data.google.profile, 'name' ) ) {\\
['familyName', 'givenName'].forEach( (val) => {\\
if ( _.has(context.data.google.profile.name, val ) ) {\\
context.data[val] = context.data.google.profile.name[val];\\
logger.info(val + ': ' + context.data[val]);\\
}\\
})\\
}\\
} // end if has data.google.profile\\
\/* end of code added by ${FileNameWithExtension} ${TimeStamp} *\/\\
END_OF_SED_USER_HOOK
############ future use for sql based example
###sed --in-place --file=- ./src/models/users.model.js <<END_OF_SED_USER_MODEL ;
###/ googleId: { type: Sequelize.STRING },/ a\
###\\
###\\
### \/* data items added by ${FileNameWithExtension} ${TimeStamp} *\/\\
### email: { type: DataTypes.STRING }, \\
### displayName: { type: DataTypes.STRING },\\
### familyName: { type: DataTypes.STRING },\\
### givenName: { type: DataTypes.STRING },\\
### \/* end of data items added by ${FileNameWithExtension} ${TimeStamp} *\/\\
###END_OF_SED_USER_MODEL
## feathers generate service; ## all defaults except for the service name - "testtable"
expect <(cat <<'END_OF_GENERATE_SERVICE'
## creates a service: testtable (all the defaults)
## written from: https://docs.feathersjs.com/guides/chat/service.html
set UPARROW \x1B\[A;
set DOWNARROW \x1B\[B;
set timeout -1
spawn feathers generate service;
expect -re ".*What kind of service is it\?.*"
send -- "${RETURN}"
## defaults to NeDB
## one downarrow selects "MongoDB"
## 2 - Mongoose
## 3 - Sequelize
## 4 - KnexJS
## 5 - RethinDB
## 6 - custom service
expect -re ".*What is the name of the service\?.*"
send -- "testtable${RETURN}"
## testtable
expect -re ".*Which path should the service be registered on\?.*"
send -- "${RETURN}"
## defaults to /testtable
expect -re ".*Does the service require authentication\?.*"
send -- "y${RETURN}"
## y for 'yes' and return
expect eof
END_OF_GENERATE_SERVICE
) ## end of feathers generate service
#######################################################################################################
##
## THIS MAY NOT BE REQUIRED WHEN USING SEQUELIZE (BELOW)
##
########################################################################################################
## feathers generate hook for service "testtable";
expect <(cat <<'END_OF_GENERATE_TESTTABLE_HOOK'
# generates a "BEFORE--CREATE/UPDATE" hook named "testtable-hook" for the "testtable" service for Google
# written from https://docs.feathersjs.com/api/authentication/oauth2.html#customizing-the-oauth-response
set timeout -1
set UPARROW \x1B\[A;
set DOWNARROW \x1B\[B;
spawn feathers generate hook ;
expect -re ".*What is the name of the hook\?.*"
send -- "testtable-hook${RETURN}"
expect -re "What kind of hook should it be\?"
send -- "${DOWNARROW}${RETURN}"
## downarrow return selects 'before'
expect -re "What service\\\(s\\\) should this hook be for \\\(select none to add it yourself\\\)\?"
send -- "${DOWNARROW}${SPACE}${RETURN}"
## downarrow space return selects 'testtable', 'users' is now the third on the list!
expect -re "What methods should the hook be for \\\(select none to add it yourself\\\)\?"
send -- "${DOWNARROW}${DOWNARROW}${DOWNARROW}${SPACE}${DOWNARROW}${SPACE}${RETURN}"
## downarrow (3) space downarrow space selects BOTH 'create' AND 'update'
expect eof
END_OF_GENERATE_TESTTABLE_HOOK
) ## end of feathers generate hook
## edit testtable-hook.js
sed --in-place --file=- ./src/hooks/testtable-hook.js <<END_OF_SED_TESTTABLE_HOOK ;
3s?^?\\n//const logger = require('winston'); // added by bash script \\n\\n?;
/^ return async context => {$/a\
\ \ \ \ context.data[options] = new Date(); \/\/ include 'createdAt' and 'updatedAt' in record on create and update.\\
\ \ \ \ \/\/logger.info(context.data); // uncomment out to inspect the results.
END_OF_SED_TESTTABLE_HOOK
sed --in-place --file=- ./src/services/testtable/testtable.hooks.js <<END_OF_SED_TESTTABLE_HOOKS ;
s? create: \[testtableHook()],? create: \[testtableHook('createdAt')],?;
s? update: \[testtableHook()],? create: \[testtableHook('updatedAt')],?;
END_OF_SED_TESTTABLE_HOOKS
#######################################################################################################
##
## THIS MAY NOT BE REQUIRED WHEN USING SEQUELIZE (ABOVE)
##
########################################################################################################
## modify the default.json file if you are using google (you will have to change these values!)
## values came from https://console.developers.google.com/apis/api under credidentials
sed --in-place --file=- ./config/default.json << END_OF_SED_CONFIG_DEFAULT ;
s/"host": "localhost",/"host": "${HOST}",/;
s/<google oauth key>/${GOOGLE_KEY}/;
s/"secret": "<google oauth secret>"/"secret": "${GOOGLE_SECRET}",\n" scope": [ "profile openid email"]/;
END_OF_SED_CONFIG_DEFAULT
echo " dont forget to change the IP ## in both the ./config/default.json *AND* the google-applications page (make sure they match)";
sed --in-place --file=- ./public/index.html << END_OF_INDEX_HTML ;
/<h2 class="center-text">A REST and realtime API layer for modern applications.<\/h2>/ a\
<p class="center-text"><br\/>\\
<a href="/oauth/connect/google">Login With Google<\/a>\\
\\
<a href="javascript: feathersClient.logout(); Cookies.remove('feathers-jwt'); window.location.reload(true);">Log Out Of Google<\/a>\\
<br /><br />\\
Run the following commands in the console:\\
<\/p>\\
<div style='margin-left:50px;'>\\
<ul>\\
<li>\\
const findResult = await feathersClient.service('testtable').find(); \\
<\/li>\\
<li>\\
console.log( JSON.stringify(findResult), { colors:true, depth: 5 });\\
<\/li>\\
\\
<li>\\
var firstInsertResult = await feathersClient.service('testtable').create({ text: 'First Data Inserted' });\\
<\/li>\\
\\
<li>\\
var secondInsertResult = feathersClient.service('testtable').create({ text: 'Second Data Inserted' });\\
<\/li>\\
\\
<li>\\
var queryResults = feathersClient.service('testtable').find( {query: { text: 'Second Data Inserted'}})\\
<\/li>\\
\\
<li>\\
await feathersClient.service('testtable').find().then( (result) => console.log( JSON.stringify(result), { colors:true, depth: 5 })) ;\\
<\/li>\\
\\
<li>\\
var getResult = feathersClient.service('testtable').get('enter key here');\\
<\/li>\\
\\
<li>\\
var updateResult = feathersClient.service('testtable').update('enter key here', { moreText: 'Data added!'} );\\
<\/li>\\
\\
<li>\\
var patchResult = feathersClient.service('testtable').patch('enter key here', { text: 'Data Changed!'} );\\
<\/li>\\
\\
<li>\\
var removeResult = feathersClient.service('testtable').remove('enter key here');\\
<\/li>\\
\\
<\/ul>\\
<\/div>\\
<br \/>\\
<br \/>\\
<pre>\\
await feathersClient.service('testtable').find()\\
.then( (pageKeyList) => {\\
for ( var pageKey in pageKeyList ) {\\
if ( pageKey === 'data' ) {\\
for ( var dataKey in pageKeyList.data) {\\
console.log( pageKeyList.data[dataKey] );\\
} \/* end for *\/\\
} else {\\
console.log(pageKey, pageKeyList[pageKey]);\\
} \/* end if *\/\\
} \/* end for *\/\\
}) \/* end then *\/\\
<\/pre>\\
<script type="text/javascript" src="//unpkg.com/@feathersjs/client@^3.0.0/dist/feathers.js"></script>\\
<script type="text/javascript" src="//unpkg.com/socket.io-client@1.7.3/dist/socket.io.js"></script>\\
<!-- added for google logout -->\\
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>\\
<script type="text/javascript" src="//cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script>\\
<!-- end of added for google logout -->\\
<script>\\
// Socket.io is exposed as the \`io\` global.\\
var socket = io(':3030', {transports: ['websocket']});\\
// feathers-client is exposed as the \`feathers\` global.\\
var feathersClient = feathers()\\
//.configure(feathers.hooks()) commented out with 3.0\\
.configure(feathers.socketio(socket))\\
.configure(feathers.authentication({\\
cookie: 'feathers-jwt'\\
}));\\
\\
var setUserInfo = (async () => {\\
// a special thanks to feathers-slack "freeline" for providing this code \\
var response = await feathersClient.authenticate();\\
var payload = await feathersClient.passport.verifyJWT(response.accessToken);\\
var user = await feathersClient.service('users').get(payload.userId);\\
feathersClient.set('user', user); // feathersClient.get('user').email to get email address \\
console.log('you logged in as: ' + feathersClient.get('user').email); // display what is now in user in the console.\\
})\\
\\
feathersClient.authenticate()\\
.then(response => {\\
console.info('Feathers Client has Authenticated with the JWT access token!');\\
console.log(response);\\
setUserInfo();\\
})\\
.catch(error => {\\
console.info("We have not logged in with OAuth, yet. This means there's no cookie storing the accessToken. As a result, feathersClient.authenticate() failed.");\\
console.log(error);\\
});\\
</script>\\
END_OF_INDEX_HTML
dig ${HOST} | grep 'A';
cat <<END_OF_SCRIPT;
Host: ${HOST} points to ${DOMAIN_IP}
Does ${HOST} resolve to ${THIS_IPADDR} ?
Feathers google app should now be built. Please confirm your ./config/default.json values.
Client id in your ./config/default.json values file: ${GOOGLE_KEY}
Client secret in your ./config/default.json values file: ${GOOGLE_SECRET}
Now run ' cd ./${FileNameWithoutExtension}/ ; npm start; ' to try it out.
END_OF_SCRIPT
#