sync/src/web/account.js

675 lines
19 KiB
JavaScript
Raw Normal View History

/**
* web/account.js - Webserver details for account management
*
* @author Calvin Montgomery <cyzon@cyzon.us>
*/
var webserver = require("./webserver");
var sendPug = require("./pug").sendPug;
var Logger = require("../logger");
var db = require("../database");
var $util = require("../utilities");
var Config = require("../config");
var Server = require("../server");
2015-02-15 21:56:00 -06:00
var session = require("../session");
2015-02-22 18:15:22 -06:00
var csrf = require("./csrf");
2016-12-13 22:44:23 -08:00
const url = require("url");
2017-04-04 23:02:31 -07:00
2017-07-08 20:11:54 -07:00
const LOGGER = require('@calzoneman/jsli')('database/accounts');
2017-08-15 18:23:03 -07:00
let globalMessageBus;
/**
* Handles a GET request for /account/edit
*/
function handleAccountEditPage(req, res) {
2014-01-22 21:12:43 -06:00
if (webserver.redirectHttps(req, res)) {
return;
}
sendPug(res, "account-edit", {});
}
/**
* Handles a POST request to edit a user"s account
*/
function handleAccountEdit(req, res) {
2015-02-22 18:15:22 -06:00
csrf.verify(req);
var action = req.body.action;
switch(action) {
case "change_password":
handleChangePassword(req, res);
break;
case "change_email":
handleChangeEmail(req, res);
break;
default:
res.send(400);
break;
}
}
/**
* Handles a request to change the user"s password
*/
async function handleChangePassword(req, res) {
var name = req.body.name;
var oldpassword = req.body.oldpassword;
var newpassword = req.body.newpassword;
if (typeof name !== "string" ||
typeof oldpassword !== "string" ||
typeof newpassword !== "string") {
res.send(400);
return;
}
if (newpassword.length === 0) {
sendPug(res, "account-edit", {
errorMessage: "New password must not be empty"
});
return;
}
const reqUser = await webserver.authorize(req);
if (!reqUser) {
sendPug(res, "account-edit", {
2015-02-15 21:56:00 -06:00
errorMessage: "You must be logged in to change your password"
});
return;
}
newpassword = newpassword.substring(0, 100);
db.users.verifyLogin(name, oldpassword, function (err, user) {
if (err) {
sendPug(res, "account-edit", {
errorMessage: err
});
return;
}
db.users.setPassword(name, newpassword, function (err, dbres) {
if (err) {
sendPug(res, "account-edit", {
errorMessage: err
});
return;
}
2015-02-15 21:56:00 -06:00
2015-10-27 23:54:32 -07:00
Logger.eventlog.log("[account] " + req.realIP +
2014-01-27 18:37:48 -06:00
" changed password for " + name);
2015-02-15 21:56:00 -06:00
db.users.getUser(name, function (err, user) {
if (err) {
return sendPug(res, "account-edit", {
2015-02-15 21:56:00 -06:00
errorMessage: err
});
}
var expiration = new Date(parseInt(req.signedCookies.auth.split(":")[1]));
session.genSession(user, expiration, function (err, auth) {
if (err) {
return sendPug(res, "account-edit", {
2015-02-15 21:56:00 -06:00
errorMessage: err
});
}
webserver.setAuthCookie(req, res, expiration, auth);
2015-02-15 21:56:00 -06:00
sendPug(res, "account-edit", {
2015-02-15 21:56:00 -06:00
successMessage: "Password changed."
});
});
});
});
});
}
/**
* Handles a request to change the user"s email
*/
function handleChangeEmail(req, res) {
var name = req.body.name;
var password = req.body.password;
var email = req.body.email;
if (typeof name !== "string" ||
typeof password !== "string" ||
typeof email !== "string") {
res.send(400);
return;
}
2014-01-27 18:37:48 -06:00
if (!$util.isValidEmail(email) && email !== "") {
sendPug(res, "account-edit", {
errorMessage: "Invalid email address"
});
return;
}
db.users.verifyLogin(name, password, function (err, user) {
if (err) {
sendPug(res, "account-edit", {
errorMessage: err
});
return;
}
db.users.setEmail(name, email, function (err, dbres) {
if (err) {
sendPug(res, "account-edit", {
errorMessage: err
});
return;
}
2015-10-27 23:54:32 -07:00
Logger.eventlog.log("[account] " + req.realIP +
2014-01-27 18:37:48 -06:00
" changed email for " + name +
" to " + email);
sendPug(res, "account-edit", {
successMessage: "Email address changed."
});
});
});
}
/**
* Handles a GET request for /account/channels
*/
async function handleAccountChannelPage(req, res) {
2014-01-22 21:12:43 -06:00
if (webserver.redirectHttps(req, res)) {
return;
}
const user = await webserver.authorize(req);
// TODO: error message
if (!user) {
return sendPug(res, "account-channels", {
2015-02-15 21:56:00 -06:00
channels: []
});
}
db.channels.listUserChannels(user.name, function (err, channels) {
sendPug(res, "account-channels", {
2015-02-15 21:56:00 -06:00
channels: channels
});
2015-02-15 21:56:00 -06:00
});
}
/**
* Handles a POST request to modify a user"s channels
*/
function handleAccountChannel(req, res) {
2015-02-22 18:15:22 -06:00
csrf.verify(req);
var action = req.body.action;
switch(action) {
case "new_channel":
handleNewChannel(req, res);
break;
case "delete_channel":
handleDeleteChannel(req, res);
break;
default:
res.send(400);
break;
}
}
/**
* Handles a request to register a new channel
*/
async function handleNewChannel(req, res) {
var name = req.body.name;
if (typeof name !== "string") {
res.send(400);
return;
}
const user = await webserver.authorize(req);
// TODO: error message
if (!user) {
return sendPug(res, "account-channels", {
channels: []
});
}
2015-02-15 21:56:00 -06:00
db.channels.listUserChannels(user.name, function (err, channels) {
if (err) {
sendPug(res, "account-channels", {
channels: [],
newChannelError: err
});
return;
}
2014-01-20 12:42:20 -06:00
2015-02-15 21:56:00 -06:00
if (name.match(Config.get("reserved-names.channels"))) {
sendPug(res, "account-channels", {
2015-02-15 21:56:00 -06:00
channels: channels,
newChannelError: "That channel name is reserved"
});
return;
}
2014-02-05 18:05:52 -06:00
if (channels.length >= Config.get("max-channels-per-user")
&& user.global_rank < 255) {
sendPug(res, "account-channels", {
2015-02-15 21:56:00 -06:00
channels: channels,
newChannelError: "You are not allowed to register more than " +
Config.get("max-channels-per-user") + " channels."
});
return;
}
db.channels.register(name, user.name, function (err, channel) {
2015-02-15 21:56:00 -06:00
if (!err) {
Logger.eventlog.log("[channel] " + user.name + "@" +
2015-10-27 23:54:32 -07:00
req.realIP +
2015-02-15 21:56:00 -06:00
" registered channel " + name);
globalMessageBus.emit('ChannelRegistered', {
channel: name
});
2015-02-15 21:56:00 -06:00
channels.push({
name: name
});
}
sendPug(res, "account-channels", {
2015-02-15 21:56:00 -06:00
channels: channels,
newChannelError: err ? err : undefined
});
});
});
}
/**
* Handles a request to delete a new channel
*/
async function handleDeleteChannel(req, res) {
var name = req.body.name;
if (typeof name !== "string") {
res.send(400);
return;
}
const user = await webserver.authorize(req);
// TODO: error
if (!user) {
return sendPug(res, "account-channels", {
channels: [],
});
}
2015-02-15 21:56:00 -06:00
db.channels.lookup(name, function (err, channel) {
if (err) {
sendPug(res, "account-channels", {
channels: [],
deleteChannelError: err
});
return;
}
2014-01-20 12:42:20 -06:00
if ((!channel.owner || channel.owner.toLowerCase() !== user.name.toLowerCase()) && user.global_rank < 255) {
db.channels.listUserChannels(user.name, function (err2, channels) {
sendPug(res, "account-channels", {
2015-02-15 21:56:00 -06:00
channels: err2 ? [] : channels,
deleteChannelError: "You do not have permission to delete this channel"
2014-01-26 00:01:36 -06:00
});
2015-02-15 21:56:00 -06:00
});
return;
}
2014-01-26 00:01:36 -06:00
2015-02-15 21:56:00 -06:00
db.channels.drop(name, function (err) {
if (!err) {
Logger.eventlog.log("[channel] " + user.name + "@" +
2015-10-27 23:54:32 -07:00
req.realIP + " deleted channel " +
2015-02-15 21:56:00 -06:00
name);
}
2014-02-07 10:45:28 -06:00
globalMessageBus.emit('ChannelDeleted', {
channel: name
});
db.channels.listUserChannels(user.name, function (err2, channels) {
sendPug(res, "account-channels", {
2015-02-15 21:56:00 -06:00
channels: err2 ? [] : channels,
deleteChannelError: err ? err : undefined
});
});
});
});
}
/**
* Handles a GET request for /account/profile
*/
async function handleAccountProfilePage(req, res) {
2014-01-22 21:12:43 -06:00
if (webserver.redirectHttps(req, res)) {
return;
}
const user = await webserver.authorize(req);
// TODO: error message
if (!user) {
return sendPug(res, "account-profile", {
profileImage: "",
profileText: ""
});
2015-02-15 21:56:00 -06:00
}
db.users.getProfile(user.name, function (err, profile) {
2015-02-15 21:56:00 -06:00
if (err) {
sendPug(res, "account-profile", {
2015-02-15 21:56:00 -06:00
profileError: err,
profileImage: "",
profileText: ""
});
2015-02-15 21:56:00 -06:00
return;
}
sendPug(res, "account-profile", {
2015-02-15 21:56:00 -06:00
profileImage: profile.image,
profileText: profile.text,
profileError: false
});
2015-02-15 21:56:00 -06:00
});
}
2016-12-13 22:44:23 -08:00
function validateProfileImage(image, callback) {
var prefix = "Invalid URL for profile image: ";
var link = image.trim();
if (!link) {
process.nextTick(callback, null, link);
} else {
var data = url.parse(link);
if (!data.protocol || data.protocol !== 'https:') {
process.nextTick(callback,
new Error(prefix + " URL must begin with 'https://'"));
} else if (!data.host) {
process.nextTick(callback,
new Error(prefix + "missing hostname"));
} else {
process.nextTick(callback, null, link);
}
}
}
/**
* Handles a POST request to edit a profile
*/
async function handleAccountProfile(req, res) {
2015-02-22 18:15:22 -06:00
csrf.verify(req);
const user = await webserver.authorize(req);
// TODO: error message
if (!user) {
return sendPug(res, "account-profile", {
2014-01-20 12:42:20 -06:00
profileImage: "",
profileText: "",
profileError: "You must be logged in to edit your profile",
});
}
2016-12-13 22:44:23 -08:00
var rawImage = String(req.body.image).substring(0, 255);
var text = String(req.body.text).substring(0, 255);
validateProfileImage(rawImage, (error, image) => {
if (error) {
db.users.getProfile(user.name, function (err, profile) {
2016-12-13 22:44:23 -08:00
var errorMessage = err || error.message;
sendPug(res, "account-profile", {
profileImage: profile ? profile.image : "",
profileText: profile ? profile.text : "",
profileError: errorMessage
});
2014-01-20 12:42:20 -06:00
});
return;
}
db.users.setProfile(user.name, { image: image, text: text }, function (err) {
2016-12-13 22:44:23 -08:00
if (err) {
sendPug(res, "account-profile", {
profileImage: "",
profileText: "",
profileError: err
});
return;
}
2017-08-15 18:23:03 -07:00
globalMessageBus.emit('UserProfileChanged', {
user: user.name,
profile: {
image,
text
}
});
2016-12-13 22:44:23 -08:00
sendPug(res, "account-profile", {
profileImage: image,
profileText: text,
profileError: false
});
2014-01-20 12:42:20 -06:00
});
});
}
2014-01-23 22:59:08 -06:00
/**
* Handles a GET request for /account/passwordreset
*/
function handlePasswordResetPage(req, res) {
if (webserver.redirectHttps(req, res)) {
return;
}
sendPug(res, "account-passwordreset", {
2014-01-23 22:59:08 -06:00
reset: false,
resetEmail: "",
resetErr: false
});
}
/**
2014-02-01 13:03:08 -06:00
* Handles a POST request to reset a user's password
2014-01-23 22:59:08 -06:00
*/
function handlePasswordReset(req, res) {
2015-02-22 18:15:22 -06:00
csrf.verify(req);
2014-01-23 22:59:08 -06:00
var name = req.body.name,
email = req.body.email;
if (typeof name !== "string" || typeof email !== "string") {
res.send(400);
return;
}
if (!$util.isValidUserName(name)) {
sendPug(res, "account-passwordreset", {
2014-01-23 22:59:08 -06:00
reset: false,
resetEmail: "",
resetErr: "Invalid username '" + name + "'"
});
return;
}
db.users.getEmail(name, function (err, actualEmail) {
if (err) {
sendPug(res, "account-passwordreset", {
2014-01-23 22:59:08 -06:00
reset: false,
resetEmail: "",
resetErr: err
});
return;
}
if (actualEmail !== email.trim()) {
sendPug(res, "account-passwordreset", {
2014-01-23 22:59:08 -06:00
reset: false,
resetEmail: "",
resetErr: "Provided email does not match the email address on record for " + name
});
return;
} else if (actualEmail === "") {
sendPug(res, "account-passwordreset", {
2014-01-23 22:59:08 -06:00
reset: false,
resetEmail: "",
resetErr: name + " doesn't have an email address on record. Please contact an " +
"administrator to manually reset your password."
});
return;
}
var hash = $util.sha1($util.randomSalt(64));
// 24-hour expiration
var expire = Date.now() + 86400000;
2015-10-27 23:54:32 -07:00
var ip = req.realIP;
db.addPasswordReset({
ip: ip,
name: name,
email: email,
hash: hash,
expire: expire
}, function (err, dbres) {
if (err) {
sendPug(res, "account-passwordreset", {
reset: false,
resetEmail: "",
resetErr: err
});
return;
}
2014-01-27 18:37:48 -06:00
Logger.eventlog.log("[account] " + ip + " requested password recovery for " +
name + " <" + email + ">");
if (!Config.get("mail.enabled")) {
sendPug(res, "account-passwordreset", {
reset: false,
resetEmail: email,
resetErr: "This server does not have mail support enabled. Please " +
"contact an administrator for assistance."
});
return;
}
var msg = "A password reset request was issued for your " +
"account `"+ name + "` on " + Config.get("http.domain") +
". This request is valid for 24 hours. If you did "+
"not initiate this, there is no need to take action."+
" To reset your password, copy and paste the " +
"following link into your browser: " +
2014-02-01 13:03:08 -06:00
Config.get("http.domain") + "/account/passwordrecover/"+hash;
var mail = {
from: Config.get("mail.from-name") + " <" + Config.get("mail.from-address") + ">",
to: email,
subject: "Password reset request",
text: msg
};
2014-02-28 16:20:58 -06:00
Config.get("mail.nodemailer").sendMail(mail, function (err, response) {
if (err) {
2017-04-04 23:02:31 -07:00
LOGGER.error("mail fail: " + err);
sendPug(res, "account-passwordreset", {
reset: false,
2014-03-01 17:37:59 -06:00
resetEmail: email,
resetErr: "Sending reset email failed. Please contact an " +
"administrator for assistance."
});
} else {
sendPug(res, "account-passwordreset", {
reset: true,
2014-03-01 17:37:59 -06:00
resetEmail: email,
resetErr: false
});
}
});
2014-01-23 22:59:08 -06:00
});
});
}
/**
2014-02-01 13:03:08 -06:00
* Handles a request for /account/passwordrecover/<hash>
*/
function handlePasswordRecover(req, res) {
2014-02-01 13:03:08 -06:00
var hash = req.params.hash;
if (typeof hash !== "string") {
res.send(400);
return;
}
2015-10-27 23:54:32 -07:00
var ip = req.realIP;
db.lookupPasswordReset(hash, function (err, row) {
if (err) {
sendPug(res, "account-passwordrecover", {
recovered: false,
2015-02-15 21:56:00 -06:00
recoverErr: err
});
return;
}
if (Date.now() >= row.expire) {
sendPug(res, "account-passwordrecover", {
recovered: false,
recoverErr: "This password recovery link has expired. Password " +
"recovery links are valid only for 24 hours after " +
2015-02-15 21:56:00 -06:00
"submission."
});
return;
}
var newpw = "";
const avail = "abcdefgihkmnpqrstuvwxyz0123456789";
for (var i = 0; i < 10; i++) {
newpw += avail[Math.floor(Math.random() * avail.length)];
}
db.users.setPassword(row.name, newpw, function (err) {
if (err) {
sendPug(res, "account-passwordrecover", {
recovered: false,
recoverErr: "Database error. Please contact an administrator if " +
2015-02-15 21:56:00 -06:00
"this persists."
});
return;
}
db.deletePasswordReset(hash);
2014-02-07 10:45:28 -06:00
Logger.eventlog.log("[account] " + ip + " recovered password for " + row.name);
sendPug(res, "account-passwordrecover", {
recovered: true,
2015-02-15 21:56:00 -06:00
recoverPw: newpw
});
});
});
}
module.exports = {
/**
* Initialize the module
*/
2017-08-15 18:23:03 -07:00
init: function (app, _globalMessageBus) {
globalMessageBus = _globalMessageBus;
app.get("/account/edit", handleAccountEditPage);
app.post("/account/edit", handleAccountEdit);
app.get("/account/channels", handleAccountChannelPage);
app.post("/account/channels", handleAccountChannel);
app.get("/account/profile", handleAccountProfilePage);
app.post("/account/profile", handleAccountProfile);
2014-01-23 22:59:08 -06:00
app.get("/account/passwordreset", handlePasswordResetPage);
app.post("/account/passwordreset", handlePasswordReset);
2014-02-01 13:03:08 -06:00
app.get("/account/passwordrecover/:hash", handlePasswordRecover);
2014-02-05 18:08:20 -06:00
app.get("/account", function (req, res) {
res.redirect("/login");
});
}
};