forked from theodi/nodejs-oauth-template
-
Notifications
You must be signed in to change notification settings - Fork 1
/
userHandler.js
80 lines (75 loc) · 2.32 KB
/
userHandler.js
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
const { Parser } = require('@json2csv/plainjs'); // Library to create CSV for output
exports.insertUser = function(res,dbo,profile) {
profile.suspended = false;
profile.userType = "user";
var dbConnect = dbo.getDb();
dbConnect
.collection("Users")
.insertOne(profile);
}
exports.updateLastLoginTime = function(res,dbo,email) {
var date = new Date().toISOString();
var dbConnect = dbo.getDb();
dbConnect
.collection("Users")
.updateOne({'emails.0.value': email}, { $set: { lastLogin: date }});
}
exports.getUsers = function(req,res,dbo,format) {
var dbConnect = dbo.getDb();
dbConnect
.collection("Users")
.find()
.toArray(function(err,items) {
if (format=="text/csv") {
const parser = new Parser({ header: true });
const csv = parser.parse(makeCSVOutput(items));
res.set('Content-Type', 'text/csv');
res.send(csv);
} else {
res.set('Content-Type', 'application/json');
res.send(JSON.stringify(items, null, 4));
}
});
}
exports.getUser = function(req,res,dbo,id,format) {
var dbConnect = dbo.getDb();
dbConnect
.collection("Users")
.find({'id': id})
.toArray(function(err,items) {
if (format=="text/csv") {
const parser = new Parser({ header: true });
const csv = parser.parse(makeCSVOutput(items[0]));
res.set('Content-Type', 'text/csv');
res.send(csv);
} else {
res.set('Content-Type', 'application/json');
res.send(JSON.stringify(items[0], null, 4));
}
});
}
exports.updateUser = function(req,res,dbo,id) {
var updateRole = req.body.Role;
var updateSuspended = req.body.Suspended;
var dbConnect = dbo.getDb();
dbConnect
.collection("Users")
.updateOne({'id': id}, { $set: { suspended: updateSuspended, userType: updateRole }},
function(err,result) {
res.locals.pageTitle = "Edit user";
res.render('pages/editUserProfile', {userid: id, msg: "User updated"});
});
}
function makeCSVOutput(users) {
var output = [];
for(i=0;i<users.length;i++) {
var user = {};
user = users[i]._json;
user.suspended = users[i].suspended;
user.type = users[i].userType;
user.lastLogin = users[i].lastLogin;
output.push(user);
}
console.log(output);
return output;
}