91 lines
2.4 KiB
JavaScript
91 lines
2.4 KiB
JavaScript
const express = require("express");
|
|
const DBUtils = require('../../Utils/DBUtil');
|
|
const Config = require('../../Config/Config');
|
|
|
|
|
|
const router = express.Router();
|
|
|
|
router.post('/create/', (req, res) => {
|
|
const body = req.body;
|
|
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: user,
|
|
token: account.auth_token
|
|
});
|
|
}
|
|
})
|
|
|
|
}
|
|
});
|
|
}
|
|
|
|
});
|
|
|
|
router.post('/login/', (req, res) => {
|
|
const body = req.body;
|
|
DBUtils.Models.Account.findOne({
|
|
username: body.username
|
|
}, (err, account) => {
|
|
if (err) throw err;
|
|
if (account) {
|
|
// test a matching password
|
|
account.comparePassword(body.password, account.password, (err, isMatch) => {
|
|
if (err) throw err;
|
|
if (!isMatch) {
|
|
res.status(401).json({
|
|
message: 'Authentication Fail'
|
|
});
|
|
return;
|
|
}
|
|
res.json({
|
|
token: account.auth_token
|
|
});
|
|
});
|
|
} else {
|
|
res.status(401).json({
|
|
message: 'Authentication Fail'
|
|
});
|
|
}
|
|
|
|
|
|
});
|
|
});
|
|
|
|
module.exports = router;
|