Making a Heroku with a basic user ID system using shortid

When making some kind of full stack node.js application I will want to have some kind of way to make it so I can have at least something that can work as user accounts. Maybe it would be best to have some kind of system that authenticates by way of doing something with oAuth, but maybe not, maybe I just want some kind of basic user id system, I see some projects that do that.

The reason why I just got into doing this is because I have just started making full stack apps that I can host on heroku.

Well I have found a great node.js solution that can be used to generate user ids called shortid.

Basic short id example

For a basic example of using shortId I just put together something that just responds to a request with a new id each time.

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
// using the http module
let http = require('http'),
shortId = require('shortid'),
// look for PORT environment variable,
// else look for CLI argument,
// else use hard coded value for port 8080
port = process.env.PORT || process.argv[2] || 8080,
// create a simple server
let server = http.createServer(function (req, res) {
res.writeHead(200, {
'Content-Type': 'text/plain'
});
res.write('id: ' + shortId.generate(), 'utf-8');
res.end();
});
// listen on the port
server.listen(port, function () {
console.log('app up on port: ' + port);
});

My user system so far

So My actual user account system is a little more advanced.

  • A client system is delivered to the client.
  • The client system makes a post request to the back end with a user id if stored in local storage
  • If the client system does not have a user id is sends a post request with a user id of undefined
  • If the back end gets a user id it checks if it has a *.json file that corresponds to that id.
  • If the back end has a *.json file for that id it will update, and respond with that record.
  • If it does not have a record that corresponds to the given id, or it is given undefined it will generated and return a new record, and id.

So for now I have this all in one index.js file.

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
// using the http module
let http = require('http'),
fs = require('fs-extra'),
path = require('path'),
shortId = require('shortid'),
// hard coded conf object
conf = {
// look for PORT environment variable,
// else look for CLI argument,
// else use hard coded value for port 8080
port: process.env.PORT || process.argv[2] || 8080,
// max body length for posts
maxBodyLength: 100
},
// basic request check
checkReq = function (req) {
return new Promise(function (resolve, reject) {
if (req.method != 'POST') {
reject('not a post request');
}
resolve({
success: true,
mess: 'request has passed request check'
})
});
},
// parse body of request
parseReq = function (req) {
return new Promise(function (resolve, reject) {
// the array of buffer chunks
let body = [];
// as chunks start coming in
req.on('data', function (chunk) {
// push the next chunk
body.push(chunk);
// kill the connection if someone is posting a large
// amount of data for whatever reason
if (body.length > conf.maxBodyLength) {
req.connection.destroy();
reject('Please do not do that, thank you. ( body length limit: ' +
conf.maxBodyLength + ')');
}
});
// when the post is received
req.on('end', function () {
body = Buffer.concat(body).toString();
try {
body = JSON.parse(body);
resolve({
mess: 'body parsed',
success: true,
body: body
});
} catch (e) {
reject('could not parse body.');
}
});
});
},
// write user to it's file
writeToUser = function (user) {
return new Promise(function (resolve, reject) {
let dir = path.join('./users', 'user_' + user.id + '.json');
fs.writeFile(dir, JSON.stringify(user), 'utf-8').then(function () {
resolve(user);
}).catch (function (e) {
reject(e.message);
});
});
},
// update users data
updateUser = function (user) {
return new Promise(function (resolve, reject) {
let dir = path.join('./users', 'user_' + user.id + '.json');
fs.readFile(dir, 'utf-8').then(function (user) {
user = JSON.parse(user);
user.visit.count += 1;
user.visit.last = new Date();
return writeToUser(user);
}).then(function (user) {
resolve(user);
}).catch (function (mess) {
reject(mess);
});
});
},
// check for the given id
idCheck = function (id) {
return new Promise(function (resolve, reject) {
fs.ensureDir('./users').then(function () {
let dir = path.join('./users', 'user_' + id + '.json');
fs.readFile(dir, 'utf-8').then(function (user) {
resolve(JSON.parse(user));
}).catch (function (e) {
reject(e.message);
});
}).catch (function (e) {
reject(e.message);
});
});
},
// check for the given id
idNew = function () {
return new Promise(function (resolve, reject) {
return fs.ensureDir('./users').then(function () {
let id = shortId.generate(),
now = new Date(),
user = {
id: id,
visit: {
count: 1,
first: now,
last: now
}
},
dir = path.join('./users', 'user_' + id + '.json');
return fs.writeFile(dir, JSON.stringify(user), 'utf-8').then(function () {
resolve(user);
}).catch (function (e) {
reject(e.message);
});
}).catch (function (e) {
reject(e.message);
});
});
},
// check Body
checkBody = function (body) {
return new Promise(function (resolve, reject) {
if (body.action) {
// if log set action
if (body.action === 'log-set') {
if (body.id) {
// check for that id
idCheck(body.id).then(function (user) {
return updateUser(user);
}).then(function (user) {
resolve({
success: true,
mess: 'log-set action.',
id: user.id,
user: user
});
}).catch (function (e) {
// new user
idNew().then(function (user) {
resolve({
success: true,
mess: 'log-set action.',
id: user.id,
user: user
});
}).catch (function (mess) {
reject(mess);
});
});
} else {
// new user
idNew().then(function (user) {
resolve({
success: true,
mess: 'log-set action.',
id: user.id,
user: user
});
}).catch (function (mess) {
reject(mess);
});
}
} else {
reject('unkown action.')
}
} else {
reject('no action given')
}
});
},
// create a simple server
server = http.createServer(function (req, res) {
if (req.method === 'POST') {
checkReq(req).then(function () {
return parseReq(req);
}).then(function (result) {
return checkBody(result.body);
}).then(function (result) {
res.writeHead(200, {
'Content-Type': 'text/plain'
});
res.write(JSON.stringify(result), 'utf-8');
res.end();
}).catch (function (mess) {
res.writeHead(200, {
'Content-Type': 'text/plain'
});
res.end(JSON.stringify({
success: false,
mess: mess,
id: '',
user: ''
}));
});
} else {
if (req.method === 'GET' && req.url === '/') {
fs.readFile('./public/index.html', 'utf-8').then(function (html) {
res.writeHead(200, {
'Content-Type': 'text/html'
});
res.write(html, 'utf-8');
res.end();
}).catch (function (e) {
res.writeHead(200, {
'Content-Type': 'text/plain'
});
res.end(JSON.stringify({
success: false,
mess: e.message,
id: '',
user: ''
}));
});
} else {
res.end();
}
}
});
// listen on the port
server.listen(conf.port, function () {
console.log('app up on port: ' + conf.port);
});

I am also making use of a simple client system in a public folder that just consists of a sinle index.html file that makes a post request to the back end.

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
<!doctype html>
<html>
<head>
<title>heroku short id</title>
</head>
<body>
<h1>Heroku short id system</h1>
<textarea id="out" cols="60" rows="15">
</textarea>
<script>
var postIt = function (argu) {
var xhr = new XMLHttpRequest();
if(typeof argu != 'object'){
argu = {data : argu};
}
argu.url = argu.url || window.location.href;
argu.data = argu.data || {};
argu.beforeSend = argu.beforeSend || function(xhr,next){
next();
};
argu.done = argu.done || function (res) {
console.log(res);
};
argu.fail = argu.fail || function (res) {
console.log(res);
};
xhr.open('post', argu.url);
xhr.onreadystatechange = function () {
if (this.readyState === 4) {
if (this.status === 200) {
argu.done(this);
} else {
argu.fail(this);
}
}
};
argu.beforeSend(xhr, function(){
xhr.send(argu.data);
});
};
// login, or setup if no user_id
var logSet = function(){
postIt({
// try to login with the given id, or undefined from local storage
data : JSON.stringify({
action : 'log-set',
id : window.localStorage['user_id']
}),
done : function(res){
var result = JSON.parse(res.response),
text = '';
text += 'mess : ' + result.mess + '; \n';
text += 'success : ' + result.success + '; \n';
text += 'id : ' + result.id + '; \n';
text += JSON.stringify(result.user) + '; \n';
text += '********** \n'
document.getElementById('out').innerText += text;
if(result.id){
window.localStorage['user_id'] = result.id;
}
}
});
};
logSet();
</script>
</body>
</html>

So far the system works as expected, but I have not at all put it threw a meat grinder. One thing that bothers me with it so far is that I will end up with thousands of *.json files in the users folder, but when I think about it a lot of data will have to be stored some how. In any case I am not attached to the way that the user accounts are stored.

Conclusion

I might work on this more, because I would like a system like this for when making some kind of full stack application, but it might just end up being yet another one of my little prototypes.