91 lines
1.6 KiB
JavaScript
91 lines
1.6 KiB
JavaScript
const debug = require('debug')('recv:JsonUserDatabase');
|
|
const uuidv4 = require('uuid/v4');
|
|
const fs = require('mz/fs');
|
|
const mkdir = require('mkdir-promise');
|
|
const path = require('path');
|
|
|
|
|
|
class JsonUserDatabase
|
|
{
|
|
constructor(path)
|
|
{
|
|
this.path = path;
|
|
|
|
this.codes = {};
|
|
this.users = {};
|
|
}
|
|
|
|
|
|
async load()
|
|
{
|
|
debug('loading database from ' + this.path);
|
|
|
|
try
|
|
{
|
|
var files = await fs.readdir(this.path);
|
|
}
|
|
catch(err)
|
|
{
|
|
if (err.code == 'ENOENT')
|
|
// Path does not exist, no worries
|
|
files = null;
|
|
else
|
|
throw err;
|
|
}
|
|
|
|
if (!files)
|
|
return;
|
|
|
|
for (var i = 0; i < files.length; i++)
|
|
{
|
|
var fullPath = path.join(this.path, files[i]);
|
|
var stats = await fs.lstat(fullPath);
|
|
|
|
if (stats.isFile())
|
|
{
|
|
debug('loading ' + fullPath);
|
|
try
|
|
{
|
|
var userInfo = JSON.parse(await fs.readFile(fullPath));
|
|
if (userInfo.type !== 'user')
|
|
throw new Error('unsupported file type: ' + userInfo.type);
|
|
|
|
this.users[userInfo.uid] = userInfo;
|
|
}
|
|
catch (err)
|
|
{
|
|
console.error('error while loading file ' + fullPath + ', skipped:');
|
|
console.error(err);
|
|
}
|
|
}
|
|
}
|
|
|
|
debug(Object.keys(this.users).length + ' user(s) loaded');
|
|
}
|
|
|
|
|
|
addUser(info)
|
|
{
|
|
var userId = uuidv4();
|
|
|
|
// TODO add user
|
|
// TODO save file
|
|
|
|
return userId;
|
|
}
|
|
|
|
|
|
isValidCode(code)
|
|
{
|
|
debug('validating code: ' + code);
|
|
|
|
// TODO check code
|
|
var valid = true;
|
|
|
|
debug('valid = ' + valid);
|
|
return valid;
|
|
}
|
|
}
|
|
|
|
|
|
module.exports = JsonUserDatabase; |