framez-server/Server/API/Routers/AccountRouter.js

122 lines
3.4 KiB
JavaScript
Raw Permalink Normal View History

const express = require("express");
const DBUtils = require('../../Utils/DBUtil');
const Config = require('../../Config/Config');
const AuthUtil = require('../../Utils/AuthUtil');
// Logger
const Logger = require('../../Utils/Logger');
const TAG = '[AccountRouter]'
const router = express.Router();
router.post('/create/', (req, res) => {
const body = req.body;
Logger.debug(TAG, 'POST: /create/');
if (!body.username || !body.password) {
res.status(400).json({
message: 'username and password are required'
});
} else if (body.username.length < Config.validators.account.username_min_length) {
res.status(400).json({
message: `username must be at least ${Config.validators.account.username_min_length} chars long`
});
} else if (body.password.length < Config.validators.account.password_min_length) {
res.status(400).json({
message: `password must be at least ${Config.validators.account.password_min_length} chars long`
});
} else {
// Create a new Account - status 201
// create a user a new user
const account = new DBUtils.Models.Account({
username: body.username,
password: body.password,
});
account.save((err, doc) => {
if (err) {
res.status(400).json({
message: "Failed to save account in DB, username taken"
})
} else {
// create an empty user object
const user = new DBUtils.Models.User({
account_id: account._id,
nickname: account.username
});
user.save((err, doc) => {
if (err) {
//TODO delete the created account....
res.status(400).json({
message: "Failed to save account in DB, username taken"
}); //FIXME - Lies!!!
} else {
res.status(201).json({
user: doc.toObject(),
token: account.auth_token
});
}
})
}
});
}
});
router.post('/login/', (req, res) => {
Logger.debug(TAG, 'POST: /login/');
const body = req.body;
DBUtils.Models.Account.findOne({
username: body.username
}, (err, account) => {
if (err) {
Logger.error(TAG, 'Failed to query DB. ERROR:', err);
res.status(500).json({
message: err.message
});
}
else if (account) {
// test a matching password
account.comparePassword(body.password, account.password, (err, isMatch) => {
if (err) {
Logger.error(TAG, 'Failed to query DB. ERROR:', err);
res.status(500).json({
message: err.message
});
}
else if (!isMatch) {
Logger.warn(TAG, 'Authentication Fail');
res.status(401).json({
message: 'Authentication Fail'
});
return;
}else {
AuthUtil.getUserByAccountId(account._id).then(user => {
let responseObj = {
user: user.toObject(),
token: account.auth_token
}
Logger.debug(TAG, 'Authentication success', JSON.stringify(responseObj, null, 2));
res.json(responseObj);
})
.catch(reason=>{
res.status(400).json({
message: reason
});
})
}
});
} else {
Logger.warn(TAG, 'Authentication Fail');
res.status(401).json({
message: 'Authentication Fail'
});
}
});
});
module.exports = router;