forked from GetStream/stream-react-example
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathusers.js
More file actions
356 lines (316 loc) · 8.89 KB
/
users.js
File metadata and controls
356 lines (316 loc) · 8.89 KB
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
'use strict';
/**
* Module Dependencies
*/
var stream = require('getstream'),
jwt = require('jsonwebtoken'),
async = require('async'),
FB = require('fb'),
algoliaSearch = require('algoliasearch');
/**
* Get user by id
* URL: /users/:id
* Method: GET
* Auth Required: Yes
* @param {string} user_id This required param specifies the user id to filter by
* @returns {object} Returns a 200 status code with the user object
*/
server.get('/users/:id', function(req, res, next) {
// extract params
var params = req.params || {};
// empty array to hold bindings
var bindings = [];
// base sql query
var sql = '';
// if a user id exists
if (params.user_id) {
// build sql query
sql = `
SELECT
users.id AS id,
users.fb_uid AS fb_uid,
users.first_name AS first_name,
users.last_name AS last_name,
MD5(users.email) AS email_md5,
users.created_at AS created_at,
users.modified_at AS modified_at,
IF(
(SELECT
1 AS following
FROM followers
WHERE user_id = ?
AND follower_id = users.id
),
true, false
) AS following,
IF(
(SELECT
1 AS following
FROM followers
WHERE follower_id = ?
AND user_id = users.id
),
true, false
) AS follower,
(SELECT COUNT(id) FROM followers WHERE user_id = users.id) AS following_count,
(SELECT COUNT(id) FROM followers WHERE follower_id = ?) AS follower_count
FROM users
WHERE id = ?
OR fb_uid = ?
OR email = ?
`;
// push query params into bindings array
bindings = [
params.user_id,
params.user_id,
params.id,
params.id,
params.id,
params.id,
];
// select user based off of provided fb_uid or email
} else {
// build sql
sql = `
SELECT
users.id AS id,
users.fb_uid AS fb_uid,
users.first_name AS first_name,
users.last_name AS last_name,
MD5(users.email) AS email_md5,
users.created_at AS created_at,
users.modified_at AS modified_at
FROM users
WHERE id = ?
OR fb_uid = ?
OR email = ?
`;
// push query params into bindings array
bindings = [params.id, params.id, params.id];
}
// execute query
db.query(sql, bindings, function(err, result) {
// catch all errors
if (err) {
// use global logger to log to console
log.error(err);
// return error message to client
return next(new restify.InternalError(err.message));
}
// use object.assign to merge stream tokens
result = Object.assign({}, result[0]);
// send response to client
res.send(200, result);
return next();
});
});
/**
* Create user or return the user object if they already exist
* URL: /users
* Method: POST
* Auth Required: Yes
* @param {string} fb_uid A unique Facebook user id to associate with the user (aka app specific fb uid)
* @param {string} first_name The users first name
* @param {string} last_name The users last name
* @param {string} email A unique email address to associate with the user
* @returns {object} Returns a 201 or 200 status code with the user object
*/
server.post('/users', function(req, res, next) {
// extract data from body
var data = req.body || {};
var fbUserId = data.fb_user_id;
var accessToken = data.token;
var options = {
appId: '1714548178824131',
xfbml: true,
version: 'v2.6',
status: true,
cookie: true,
};
var fb = new FB.Facebook(options);
fb.setAccessToken(accessToken);
async.waterfall([
function(cb) {
// query the userdata from FB
fb.api(
'/me',
'get',
{ fields: 'id,name,email, first_name, last_name' },
function(facebookUserData) {
cb(null, facebookUserData);
},
);
},
function(facebookUserData, cb) {
// build the data we're going to insert
var data = {};
data.email = facebookUserData.email;
data.fb_uid = facebookUserData.id;
data.first_name = facebookUserData.first_name;
data.last_name = facebookUserData.last_name;
// try select first
db.query(
'SELECT * FROM users WHERE email=' + db.escape(data.email),
function(err, result) {
if (err) {
log.error(err);
return next(new restify.InternalError(err.message));
}
// instantiate a new client (server side)
var streamClient = stream.connect(
config.stream.key,
config.stream.secret,
);
// generate jwt
var jwtToken = jwt.sign(
{
request: {
email: data.email,
},
},
config.jwt.secret,
);
// if user exists, return result
if (result.length) {
var userId = result[0].id;
// get tokens from stream client
var tokens = {
timeline: {
flat: streamClient.getReadOnlyToken(
'timeline_flat',
userId,
),
aggregated: streamClient.getReadOnlyToken(
'timeline_aggregrated',
userId,
),
},
notification: streamClient.getReadOnlyToken(
'notification',
userId,
),
};
// user object.assign to insert tokens from stream and jwt
result = Object.assign(
{},
result[0],
{ tokens: tokens },
{ jwt: jwtToken },
);
// send response to client
res.send(200, result);
return next();
}
// execute query
db.query('INSERT INTO users SET ?', data, function(
err,
result,
) {
if (err) {
log.error(err);
return next(new restify.InternalError(err.message));
}
// user object.assign to insert new row id and tokens from stream
result = Object.assign(
{},
{ id: result.insertId },
data,
tokens,
);
// initialize algolia
var algolia = algoliaSearch(
config.algolia.appId,
config.algolia.apiKey,
);
// initialize algoia index
var index = algolia.initIndex('cabin');
// add returned database object for indexing
index.addObject(result);
// use object.assign insert jwt
result = Object.assign({}, result, { jwt: jwtToken });
var userId = result.id;
// auto follow user id 1 (a.k.a stream cabin)
db.query(
'INSERT INTO followers SET user_id=?, follower_id=?',
[userId, 1],
function(err, result) {
// instantiate a new client (server side)
var streamClient = stream.connect(
config.stream.key,
config.stream.secret,
);
// instantiate a feed using feed class 'user' and the user id from the database
var userFeed = streamClient.feed(
'user',
userId,
);
// build activity object for stream feed
var activity = {
actor: `user:${userId}`,
verb: 'follow',
object: `user:${1}`,
foreign_id: `follow:${userId}`,
time: data['created_at'],
to: [`notification:${1}`],
};
// instantiate a feed using feed class 'timeline_flat' and the user id from the database
var timeline = streamClient.feed(
'timeline_flat',
userId,
);
timeline.follow('user_posts', 1);
// instantiate a feed using feed class 'timeline_aggregated' and the user id from the database
var timelineAggregated = streamClient.feed(
'timeline_aggregated',
userId,
);
timelineAggregated.follow('user', 1);
// add activity to the feed
userFeed
.addActivity(activity)
.then(function(response) {
// send response to client
res.send(201, result);
return next();
})
.catch(function(reason) {
log.error(reason);
return next(
new restify.InternalError(
reason.error,
),
);
});
},
);
});
},
);
},
]);
});
/**
* Delete an existing user
* URL: /users
* Method: DELETE
* Auth Required: Yes
* @param {string} user_id A unique database user id to to delete
* @returns {object} Returns a 204 status code
*/
server.del('/users/:user_id', function(req, res, next) {
var params = req.params || {};
db.query('DELETE FROM users WHERE id = ?', [params.user_id], function(
err,
result,
) {
// catch all errors
if (err) {
// use global logger to log to console
log.error(err);
// return error message to client
return next(new restify.InternalError(err.message));
}
res.send(204);
return next();
});
});