-
Notifications
You must be signed in to change notification settings - Fork 0
/
gmail-sequelize.bsh
399 lines (311 loc) · 15.9 KB
/
gmail-sequelize.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
392
393
394
395
396
397
398
399
#! /bin/bash
## gmail-sequelize.bsh last update: 2018-02-13
##
## Bash script to create a google-gmail authentication with a service,
## using a sequelize 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/
## database credentials
DB_USER='database-username' ;
DB_PASS='database-password' ;
DB_NAME='database-name' ;
DB_SERVER_IP='XXX.XXX.XXX.XXX' ;
MariaDB='MariaDB' ;
CockroachDB='CockroachDB' ;
TYPE=MariaDB ; ## SET THIS LINE FOR YOUR DATABASE CHOICE!
TableName='oauth2Logins' ; ## name of sql table
ServiceName='oauth-2-logins' ; ## service name (same one that feathers will probably convert to
## if a CAPPED letter was used.)
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.0 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;
# build database string
if [ "${TYPE}" = "${MariaDB}" ]; then
SERVER_PORT='3306' ;
CONNECT_STRING="mysql://${DB_USER}:${DB_PASS}@${DB_SERVER_IP}:${SERVER_PORT}/${DB_NAME}" ;
DB_URL="https://mariadb.com/" ;
elif [ "${TYPE}" = "${CockroachDB}" ]; then
SERVER_PORT='26257' ;
PG_SSL_FLAG='true' ;
CONNECT_STRING="postgres://${DB_USER}:${DB_PASS}@${DB_SERVER_IP}:${SERVER_PORT}/${DB_NAME}?ssl=${PG_SSL_FLAG}" ;
DB_URL="https://cockroachlabs.com/" ;
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} ;
npm install path; ## needed for two of the hooks.
. ${commonPath}/createApp.bsh;
if [ "${TYPE}" = "${MariaDB}" ]; then
echo "Setting one uparrow for ${MariaDB}";
export ARROW_DIRECTION=$'\x1b\x5b\x41'; ## up-arrow for MariadbDB
elif [ "${TYPE}" = "${CockroachDB}" ]; then
echo "Setting one downarrow for ${CockroachDB}";
export ARROW_DIRECTION=$'\x1b\x5b\x42'; ## down-arrow for CockroachDB
fi
export TableName;
export ServiceName;
export CONNECT_STRING;
## feathers generate authentication; ## all defaults
expect <(cat <<'END_OF_GENERATE_AUTH'
# generates an authentication for Google
# written from https://docs.feathersjs.com/guides/chat/authentication.html
set timeout -1
set UPARROW \x1B\[A;
set DOWNARROW \x1B\[B;
set SPACE \x20;
set RETURN \x0d;
spawn feathers generate authentication ;
expect -re ".*What authentication strategies do you want to use\?.*"
##send -- "${RETURN}"
send -- "${SPACE}${DOWNARROW}${DOWNARROW}${SPACE}${RETURN}"
## return defaults to Local Storage
## first space to de-select local, DOWNARROW two times, final space to select Google, and return
expect -re ".*What is the name of the user \\\(entity\\\) service.*"
send -- "$env(TableName)${RETURN}"
## default answer is 'users'
expect -re ".*What kind of service is it\?.*"
send -- "${DOWNARROW}${DOWNARROW}${DOWNARROW}${RETURN}"
## defaults to NeDB
## one downarrow selects "MongoDB"
## 2 - Mongoose
## 3 - Sequelize
## 4 - KnexJS
## 5 - RethinDB
## 6 - custom service
expect -re ".*Which database are you connecting to\?.*"
send -- "$env(ARROW_DIRECTION)${RETURN}"
## downarrow for postgres(cockroachdb), uparrow for mariadb
expect -re ".*What is the database connection string\?.*"
send -- "$env(CONNECT_STRING)${RETURN}"
## default answer is nedb://../data
expect eof
END_OF_GENERATE_AUTH
) ## end of feathers generate authentication
## feathers generate hook;
expect <(cat <<'END_OF_GENERATE_SERVICE_BEFORE_CREATE_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;
set SPACE \x20;
set RETURN \x0d;
spawn feathers generate hook ;
expect -re ".*What is the name of the hook\?.*"
send -- "oauth2-login-before-create${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 'oauth2-login'
expect -re "What methods should the hook be for \\\(select none to add it yourself\\\)\?"
send -- "${DOWNARROW}${DOWNARROW}${DOWNARROW}${SPACE}${RETURN}"
## downarrow (3) space downarrow space selects 'create'
expect eof
END_OF_GENERATE_SERVICE_BEFORE_CREATE_HOOK
) ## end of feathers generate hook 'testtable-hook'
## feathers generate hook;
expect <(cat <<'END_OF_GENERATE_SERVICE_BEFORE_UPDATE_PATCH_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;
set SPACE \x20;
set RETURN \x0d;
spawn feathers generate hook ;
expect -re ".*What is the name of the hook\?.*"
send -- "oauth2-login-before-update-patch${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 'oauth2-login'
expect -re "What methods should the hook be for \\\(select none to add it yourself\\\)\?"
send -- "${DOWNARROW}${DOWNARROW}${DOWNARROW}${DOWNARROW}${SPACE}${DOWNARROW}${SPACE}${RETURN}"
## downarrow (4) space downarrow(1) space selects 'update and patch'
expect eof
END_OF_GENERATE_SERVICE_BEFORE_UPDATE_PATCH_HOOK
) ## end of feathers generate hook 'testtable-hook'
## edit the oauth2-login-before-create.js to extract the custom login stuff, like username, first-name, etc
sed --in-place --file=- ./src/hooks/oauth2-login-before-create.js <<END_OF_SED_OAUTH2_BEFORE_CREATE_HOOK ;
3i\
\\
\\
\/* code added by ${FileNameWithExtension} ${TimeStamp} *\/ \\
const path = require('path');\\
const logger = require('winston');\\
const _ = require('lodash');\\
\/* end of code added by ${FileNameWithExtension} ${TimeStamp} *\/ \\
/^ return async context => {$/a\
\/* code added by ${FileNameWithExtension} ${TimeStamp} *\/ \\
context.data.scriptDirName = path.dirname(__filename);\\
context.data.scriptBaseName = path.basename(__filename);\\
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, 'photos' ) ) {\\
context.data.photos = context.data.google.profile.photos.find(photos => photos.value).value;\\
logger.info('photos: ' + context.data.photos);\\
}\\
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_OAUTH2_BEFORE_CREATE_HOOK
sed --in-place --file=- ./src/hooks/oauth2-login-before-update-patch.js <<END_OF_SED_OAUTH2_BEFORE_UPDATE_PATCH_HOOK ;
3i\
\\
\\
\/* code added by ${FileNameWithExtension} ${TimeStamp} *\/ \\
const path = require('path');\\
const logger = require('winston');\\
const _ = require('lodash');\\
\/* end of code added by ${FileNameWithExtension} ${TimeStamp} *\/ \\
/^ return async context => {$/a\
\/* code added by ${FileNameWithExtension} ${TimeStamp} *\/ \\
context.data.scriptDirName = path.dirname(__filename);\\
context.data.scriptBaseName = path.basename(__filename);\\
\/* end of code added by ${FileNameWithExtension} ${TimeStamp} *\/\\
END_OF_SED_OAUTH2_BEFORE_UPDATE_PATCH_HOOK
## 2019-02-18 - changed email to "unique: true" and added password field (not sure if/why the second is required??)
sed --in-place --file=- ./src/models/${ServiceName}.model.js <<END_OF_SED_OAUTH2_LOGIN_MODEL ;
/ googleId: { type: Sequelize.STRING },/ a\
\\
\\
\/* data items added by ${FileNameWithExtension} ${TimeStamp} *\/\\
email: { type: DataTypes.STRING , allowNull: false, unique: true }, \\
displayName: { type: DataTypes.STRING },\\
familyName: { type: DataTypes.STRING },\\
givenName: { type: DataTypes.STRING },\\
photos: { type: DataTypes.STRING },\\
scriptDirName: { type: DataTypes.STRING },\\
scriptBaseName: { type: DataTypes.STRING },\\
\/* end of data items added by ${FileNameWithExtension} ${TimeStamp} *\/\\
/ }, {/a \
\\
\\
\/* added tableName by ${FileNameWithExtension} ${TimeStamp} *\/ \\
tableName : '${TableName}' , \\
freezeTableName : true , \\
\/* end of new items added by ${FileNameWithExtension} ${TimeStamp} *\/\\
\\
END_OF_SED_OAUTH2_LOGIN_MODEL
## 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>\\
\\
<script type="text/javascript" src="//unpkg.com/@feathersjs/client@^3.0.0/dist/feathers.js"></script>\\
<script type="text/javascript" src="//unpkg.com/[email protected]/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('${ServiceName}').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
#