Merge forename + name into [identifying] 'name' (more general)
[qomet.git] / entities / user.js
CommitLineData
e99c53fb
BA
1const db = require("../utils/database");
2
3const UserEntity =
4{
5 /*
6 * Structure:
7 * _id: BSON id
8 * ** Strings, identification informations:
9 * email
e99c53fb
BA
10 * name
11 * initials : computed, Benjamin Auder --> ba ...etc
12 * loginToken: {
13 * value: string
14 * timestamp: datetime (validity)
15 * ip: address of requesting machine
16 * }
17 * sessionTokens (array): cookie identification
18 */
19
20 getInitialsByPrefix: function(prefix, cb)
21 {
22 db.users.find(
23 { initials: new RegExp("^" + prefix) },
24 { initials: 1, _id: 0 },
25 cb
26 );
27 },
28
29 insert: function(newUser, cb)
30 {
31 db.users.insert(Object.assign({},
32 newUser,
33 {
34 loginToken: { },
35 sessionTokens: [ ],
36 }),
37 cb
38 );
39 },
40
41 getByLoginToken: function(token, cb)
42 {
43 db.users.findOne(
44 { "loginToken.value": token },
45 cb
46 );
47 },
48
49 getBySessionToken: function(token, cb)
50 {
51 db.users.findOne(
52 { sessionTokens: token},
53 cb
54 );
55 },
56
57 getById: function(uid, cb)
58 {
59 db.users.findOne(
60 { _id: uid },
61 cb
62 );
63 },
64
65 getByEmail: function(email, cb)
66 {
67 db.users.findOne(
68 { email: email },
69 cb
70 );
71 },
72
73 getByInitials: function(initials, cb)
74 {
75 db.users.findOne(
76 { initials: initials },
77 cb
78 );
79 },
80
81 getUnlogged: function(cb)
82 {
83 var tsNow = new Date().getTime();
84 // 86400000 = 24 hours in milliseconds
85 var day = 86400000;
86 db.users.find({}, (err,userArray) => {
87 let unlogged = userArray.filter( u => {
88 return u.sessionTokens.length==0 && u._id.getTimestamp().getTime() + day < tsNow;
89 });
90 cb(err, unlogged);
91 });
92 },
93
94 getAll: function(cb)
95 {
96 db.users.find({}, cb);
97 },
98
99 setLoginToken: function(token, uid, ip, cb)
100 {
101 db.users.update(
102 { _id: uid },
103 { $set: { loginToken: {
104 value: token,
105 timestamp: new Date().getTime(),
106 ip: ip,
107 }}
108 },
109 cb
110 );
111 },
112
113 setSessionToken: function(token, uid, cb)
114 {
115 // Also empty the login token to invalidate future attempts
116 db.users.update(
117 { _id: uid },
118 {
119 $set: { loginToken: {} },
120 $push: { sessionTokens: {
121 $each: [token],
122 $slice: -7 //only allow 7 simultaneous connections per user (TODO?)
123 }}
124 },
125 cb
126 );
127 },
128
129 removeToken: function(uid, token, cb)
130 {
131 db.users.update(
132 { _id: uid },
133 { $pull: {sessionTokens: token} },
134 cb
135 );
136 },
137
138 // TODO: later, allow account removal
139 remove: function(uids)
140 {
141 db.users.remove({_id: uids});
142 },
143}
144
145module.exports = UserEntity;