sync/lib/api.js

710 lines
22 KiB
JavaScript
Raw Normal View History

2013-04-25 16:00:06 +00:00
/*
The MIT License (MIT)
Copyright (c) 2013 Calvin Montgomery
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
2013-07-15 22:57:33 +00:00
var Logger = require("./logger");
2013-05-03 20:53:10 +00:00
var fs = require("fs");
var path = require("path");
2013-08-18 02:00:50 +00:00
var $util = require("./utilities");
2013-05-03 20:53:10 +00:00
2013-07-15 22:57:33 +00:00
module.exports = function (Server) {
2013-08-17 23:44:48 +00:00
var ActionLog = Server.actionlog;
2013-07-28 15:49:29 +00:00
function getIP(req) {
var raw = req.connection.remoteAddress;
var forward = req.header("x-forwarded-for");
2013-09-10 21:11:35 +00:00
if((Server.cfg["trust-x-forward"] || raw === "127.0.0.1") && forward) {
2013-07-28 15:49:29 +00:00
var ip = forward.split(",")[0];
Logger.syslog.log("REVPROXY " + raw + " => " + ip);
return ip;
}
return raw;
}
2013-08-08 03:44:41 +00:00
function getChannelData(channel) {
var data = {
name: channel.name,
loaded: true
};
data.pagetitle = channel.opts.pagetitle;
data.media = channel.playlist.current ?
channel.playlist.current.media.pack() :
{};
data.usercount = channel.users.length;
2013-09-12 03:16:56 +00:00
data.voteskip_eligible = channel.calcVoteskipMax();
2013-08-08 03:44:41 +00:00
data.users = [];
for(var i in channel.users)
if(channel.users[i].name !== "")
data.users.push(channel.users[i].name);
data.chat = [];
for(var i in channel.chatbuffer)
data.chat.push(channel.chatbuffer[i]);
return data;
2013-07-16 15:46:09 +00:00
}
2013-04-25 16:00:06 +00:00
2013-08-08 03:44:41 +00:00
var app = Server.app;
2013-08-16 00:51:03 +00:00
var db = Server.db;
2013-04-25 16:00:06 +00:00
2013-08-11 22:23:20 +00:00
/* <https://en.wikipedia.org/wiki/Hyper_Text_Coffee_Pot_Control_Protocol> */
app.get("/api/coffee", function (req, res) {
Server.stats.record("api", "/api/coffee");
2013-08-11 22:23:20 +00:00
res.send(418); // 418 I'm a teapot
});
2013-08-08 03:44:41 +00:00
/* REGION channels */
2013-08-08 03:44:41 +00:00
/* data about a specific channel */
app.get("/api/channels/:channel", function (req, res) {
Server.stats.record("api", "/api/channels/:channel");
2013-08-08 03:44:41 +00:00
var name = req.params.channel;
if(!$util.isValidChannelName(name)) {
2013-08-08 03:44:41 +00:00
res.send(404);
return;
}
2013-08-08 03:44:41 +00:00
var data = {
name: name,
loaded: false
};
if(Server.channelLoaded(name))
2013-08-12 03:36:42 +00:00
data = getChannelData(Server.getChannel(name));
2013-08-08 03:44:41 +00:00
res.type("application/json");
res.jsonp(data);
});
/* data about all channels (filter= public or all) */
app.get("/api/allchannels/:filter", function (req, res) {
Server.stats.record("api", "/api/allchannels/:filter");
2013-08-08 03:44:41 +00:00
var filter = req.params.filter;
if(filter !== "public" && filter !== "all") {
res.send(400);
return;
}
2013-08-08 03:44:41 +00:00
var query = req.query;
2013-07-15 22:57:33 +00:00
2013-08-08 03:44:41 +00:00
// Listing non-public channels requires authenticating as an admin
if(filter !== "public") {
var name = query.name || "";
var session = query.session || "";
2013-08-16 16:01:31 +00:00
db.userLoginSession(name, session, function (err, row) {
if(err) {
if(err !== "Invalid session" &&
err !== "Session expired") {
res.send(500);
} else {
res.send(403);
}
return;
}
if(row.global_rank < 255) {
res.send(403);
return;
}
var channels = [];
for(var key in Server.channels) {
var channel = Server.channels[key];
channels.push(getChannelData(channel));
}
res.type("application/jsonp");
res.jsonp(channels);
});
2013-08-08 03:44:41 +00:00
}
2013-08-16 16:01:31 +00:00
// If we get here, the filter is public channels
2013-08-08 03:44:41 +00:00
var channels = [];
for(var key in Server.channels) {
var channel = Server.channels[key];
2013-08-16 16:01:31 +00:00
if(channel.opts.show_public)
2013-08-08 03:44:41 +00:00
channels.push(getChannelData(channel));
}
2013-07-15 22:57:33 +00:00
2013-08-08 03:44:41 +00:00
res.type("application/jsonp");
res.jsonp(channels);
});
2013-07-15 22:57:33 +00:00
2013-08-08 03:44:41 +00:00
/* ENDREGION channels */
2013-05-29 15:49:09 +00:00
2013-08-12 02:20:09 +00:00
/* REGION authentication, account management */
2013-08-08 03:44:41 +00:00
/* login */
app.post("/api/login", function (req, res) {
Server.stats.record("api", "/api/login");
2013-08-08 03:44:41 +00:00
res.type("application/jsonp");
2013-08-18 17:21:34 +00:00
res.setHeader("Access-Control-Allow-Origin", "*");
2013-08-08 03:44:41 +00:00
var name = req.body.name;
var pw = req.body.pw;
var session = req.body.session;
// for some reason CyTube previously allowed guest logins
// over the API...wat
if(!pw && !session) {
res.jsonp({
success: false,
error: "You must provide a password"
});
return;
}
2013-08-16 16:01:31 +00:00
db.userLogin(name, pw, session, function (err, row) {
if(err) {
if(err !== "Session expired")
ActionLog.record(getIP(req), name, "login-failure");
2013-08-08 03:44:41 +00:00
res.jsonp({
success: false,
2013-08-16 16:01:31 +00:00
error: err
2013-07-15 22:57:33 +00:00
});
2013-08-08 03:44:41 +00:00
return;
2013-07-15 22:57:33 +00:00
}
2013-08-16 16:01:31 +00:00
// Only record login-success for admins
if(row.global_rank >= 255)
ActionLog.record(getIP(req), name, "login-success");
2013-08-16 16:01:31 +00:00
res.jsonp({
success: true,
name: name,
session: row.session_hash
});
2013-08-08 03:44:41 +00:00
});
});
2013-08-12 02:20:09 +00:00
/* register an account */
app.post("/api/register", function (req, res) {
Server.stats.record("api", "/api/register");
2013-08-12 02:20:09 +00:00
res.type("application/jsonp");
res.setHeader("Access-Control-Allow-Origin", "*");
2013-08-12 02:20:09 +00:00
var name = req.body.name;
var pw = req.body.pw;
var ip = getIP(req);
// Limit registrations per IP within a certain time period
2013-08-16 18:25:36 +00:00
ActionLog.throttleRegistrations(ip, function (err, toomany) {
if(err) {
res.jsonp({
success: false,
error: err
});
return;
}
2013-08-16 18:25:36 +00:00
if(toomany) {
ActionLog.record(ip, name, "register-failure",
"Too many recent registrations");
res.jsonp({
success: false,
error: "Your IP address has registered too many " +
"accounts in the past 48 hours. Please wait " +
"a while before registering another."
});
return;
}
2013-08-12 02:20:09 +00:00
2013-08-16 18:25:36 +00:00
if(!pw) {
// costanza.jpg
res.jsonp({
success: false,
error: "You must provide a password"
});
return;
}
2013-08-16 16:01:31 +00:00
2013-08-12 02:20:09 +00:00
2013-08-16 18:25:36 +00:00
if(!$util.isValidUserName(name)) {
ActionLog.record(ip, name, "register-failure",
2013-08-16 18:25:36 +00:00
"Invalid name");
2013-08-16 16:01:31 +00:00
res.jsonp({
success: false,
2013-08-16 18:25:36 +00:00
error: "Invalid username. Valid usernames must be " +
"1-20 characters long and consist only of " +
"alphanumeric characters and underscores (_)"
2013-08-16 16:01:31 +00:00
});
return;
}
2013-08-12 02:20:09 +00:00
2013-08-16 18:25:36 +00:00
// db.registerUser checks if the name is taken already
db.registerUser(name, pw, function (err, session) {
if(err) {
res.jsonp({
success: false,
error: err
});
return;
}
ActionLog.record(ip, name, "register-success");
res.jsonp({
success: true,
session: session
});
2013-08-12 02:20:09 +00:00
});
});
});
2013-08-11 22:23:20 +00:00
/* password change */
app.post("/api/account/passwordchange", function (req, res) {
Server.stats.record("api", "/api/account/passwordchange");
2013-08-11 22:23:20 +00:00
res.type("application/jsonp");
res.setHeader("Access-Control-Allow-Origin", "*");
2013-08-11 22:23:20 +00:00
var name = req.body.name;
var oldpw = req.body.oldpw;
var newpw = req.body.newpw;
2013-08-11 22:23:20 +00:00
if(!oldpw || !newpw) {
res.jsonp({
success: false,
error: "Password cannot be empty"
});
return;
}
2013-05-30 18:07:29 +00:00
2013-08-16 16:01:31 +00:00
db.userLoginPassword(name, oldpw, function (err, row) {
if(err) {
res.jsonp({
success: false,
error: err
});
return;
}
2013-08-11 22:23:20 +00:00
2013-08-16 16:01:31 +00:00
db.setUserPassword(name, newpw, function (err, row) {
if(err) {
res.jsonp({
success: false,
error: err
});
return;
}
2013-08-11 22:23:20 +00:00
2013-08-16 16:01:31 +00:00
ActionLog.record(getIP(req), name, "password-change");
res.jsonp({
success: true
});
});
2013-08-11 22:23:20 +00:00
});
});
/* password reset */
app.post("/api/account/passwordreset", function (req, res) {
Server.stats.record("api", "/api/account/passwordreset");
2013-08-11 22:23:20 +00:00
res.type("application/jsonp");
res.setHeader("Access-Control-Allow-Origin", "*");
2013-08-11 22:23:20 +00:00
var name = req.body.name;
var email = req.body.email;
var ip = getIP(req);
var hash = false;
2013-08-16 00:51:03 +00:00
db.genPasswordReset(ip, name, email, function (err, hash) {
2013-08-11 22:23:20 +00:00
if(err) {
res.jsonp({
2013-07-15 22:57:33 +00:00
success: false,
2013-08-16 00:51:03 +00:00
error: err
2013-07-15 22:57:33 +00:00
});
2013-08-16 00:51:03 +00:00
return;
}
ActionLog.record(ip, name, "password-reset-generate", email);
if(!Server.cfg["enable-mail"]) {
2013-08-11 22:23:20 +00:00
res.jsonp({
2013-08-16 00:51:03 +00:00
success: false,
error: "This server does not have email recovery " +
"enabled. Contact an administrator for " +
"assistance."
2013-07-15 22:57:33 +00:00
});
2013-08-16 00:51:03 +00:00
return;
2013-07-15 22:57:33 +00:00
}
2013-08-16 00:51:03 +00:00
if(!email) {
res.jsonp({
success: false,
error: "You don't have a recovery email address set. "+
"Contact an administrator for assistance."
});
return;
}
var msg = "A password reset request was issued for your " +
"account '"+ name + "' on " + Server.cfg["domain"] +
2013-08-16 00:51:03 +00:00
". 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: " +
2013-08-16 00:51:03 +00:00
Server.cfg["domain"] + "/reset.html?"+hash;
var mail = {
from: "CyTube Services <" + Server.cfg["mail-from"] + ">",
to: email,
subject: "Password reset request",
text: msg
};
Server.cfg["nodemailer"].sendMail(mail, function (err, response) {
if(err) {
Logger.errlog.log("mail fail: " + err);
res.jsonp({
success: false,
error: "Email send failed. Contact an administrator "+
"if this persists"
});
} else {
res.jsonp({
success: true
});
}
});
2013-08-11 22:23:20 +00:00
});
});
2013-07-15 22:57:33 +00:00
/* password recovery */
app.get("/api/account/passwordrecover", function (req, res) {
Server.stats.record("api", "/api/account/passwordrecover");
res.type("application/jsonp");
var hash = req.query.hash;
var ip = getIP(req);
2013-07-15 22:57:33 +00:00
2013-08-16 00:51:03 +00:00
db.recoverUserPassword(hash, function (err, auth) {
if(err) {
ActionLog.record(ip, "", "password-recover-failure", hash);
res.jsonp({
success: false,
error: err
});
return;
}
2013-09-13 15:24:54 +00:00
ActionLog.record(ip, auth.name, "password-recover-success");
res.jsonp({
2013-08-16 00:51:03 +00:00
success: true,
name: auth.name,
pw: auth.pw
});
2013-08-16 00:51:03 +00:00
});
});
2013-07-15 22:57:33 +00:00
/* profile retrieval */
app.get("/api/users/:user/profile", function (req, res) {
Server.stats.record("api", "/api/users/:user/profile");
res.type("application/jsonp");
var name = req.params.user;
2013-07-15 22:57:33 +00:00
2013-08-16 00:51:03 +00:00
db.getUserProfile(name, function (err, profile) {
if(err) {
res.jsonp({
success: false,
error: err
});
return;
}
res.jsonp({
success: true,
2013-08-16 00:51:03 +00:00
profile_image: profile.profile_image,
profile_text: profile.profile_text
});
2013-08-16 00:51:03 +00:00
});
});
2013-07-15 22:57:33 +00:00
/* profile change */
app.post("/api/account/profile", function (req, res) {
Server.stats.record("api", "/api/account/profile");
res.type("application/jsonp");
res.setHeader("Access-Control-Allow-Origin", "*");
var name = req.body.name;
var session = req.body.session;
var img = req.body.profile_image;
var text = req.body.profile_text;
2013-05-30 01:04:22 +00:00
2013-08-16 16:01:31 +00:00
db.userLoginSession(name, session, function (err, row) {
2013-08-16 00:51:03 +00:00
if(err) {
res.jsonp({
success: false,
error: err
});
return;
}
2013-08-16 18:19:00 +00:00
db.setUserProfile(name, { image: img, text: text },
function (err, dbres) {
if(err) {
res.jsonp({
success: false,
error: err
});
return;
}
2013-05-30 01:04:22 +00:00
2013-08-16 18:19:00 +00:00
res.jsonp({ success: true });
name = name.toLowerCase();
for(var i in Server.channels) {
var chan = Server.channels[i];
for(var j in chan.users) {
var user = chan.users[j];
if(user.name.toLowerCase() == name) {
user.profile = {
image: img,
text: text
};
chan.broadcastUserUpdate(user);
}
2013-08-16 00:51:03 +00:00
}
2013-07-15 22:57:33 +00:00
}
2013-08-16 18:19:00 +00:00
});
2013-08-16 00:51:03 +00:00
});
});
2013-05-29 15:49:09 +00:00
/* set email */
app.post("/api/account/email", function (req, res) {
Server.stats.record("api", "/api/account/email");
res.type("application/jsonp");
res.setHeader("Access-Control-Allow-Origin", "*");
var name = req.body.name;
var pw = req.body.pw;
var email = req.body.email;
2013-05-29 15:49:09 +00:00
if(!email.match(/^[\w_\.]+@[\w_\.]+[a-z]+$/i)) {
res.jsonp({
success: false,
error: "Invalid email address"
});
return;
}
if(email.match(/.*@(localhost|127\.0\.0\.1)/i)) {
res.jsonp({ success: false,
error: "Nice try, but no"
});
return;
}
2013-08-16 18:19:00 +00:00
db.userLoginPassword(name, pw, function (err, row) {
2013-08-16 00:51:03 +00:00
if(err) {
res.jsonp({
success: false,
error: err
});
return;
}
2013-08-16 18:19:00 +00:00
db.setUserEmail(name, email, function (err, dbres) {
if(err) {
res.jsonp({
success: false,
error: err
});
return;
}
ActionLog.record(getIP(req), name, "email-update", email);
res.jsonp({
success: true,
session: row.session_hash
});
});
});
});
2013-08-12 02:20:09 +00:00
/* my channels */
app.get("/api/account/mychannels", function (req, res) {
Server.stats.record("/api/account/mychannels");
2013-08-12 02:20:09 +00:00
res.type("application/jsonp");
var name = req.query.name;
var session = req.query.session;
2013-08-16 18:19:00 +00:00
db.userLoginSession(name, session, function (err, row) {
2013-08-16 15:37:26 +00:00
if(err) {
res.jsonp({
success: false,
2013-08-16 18:19:00 +00:00
error: err
2013-08-16 15:37:26 +00:00
});
return;
}
db.listUserChannels(name, function (err, dbres) {
2013-08-16 18:19:00 +00:00
if(err) {
res.jsonp({
success: false,
channels: []
});
return;
}
res.jsonp({
success: true,
channels: dbres
2013-08-16 18:19:00 +00:00
});
2013-08-16 15:37:26 +00:00
});
2013-08-12 02:20:09 +00:00
});
2013-08-16 18:19:00 +00:00
2013-08-12 02:20:09 +00:00
});
2013-07-15 22:57:33 +00:00
2013-08-12 02:32:02 +00:00
/* END REGION */
2013-08-12 02:20:09 +00:00
2013-08-12 02:32:02 +00:00
/* REGION log reading */
2013-08-12 02:32:02 +00:00
/* action log */
app.get("/api/logging/actionlog", function (req, res) {
Server.stats.record("api", "/api/logging/actionlog");
2013-08-12 02:32:02 +00:00
res.type("application/jsonp");
var name = req.query.name;
var session = req.query.session;
var types = req.query.actions;
2013-07-15 22:57:33 +00:00
2013-08-16 18:19:00 +00:00
db.userLoginSession(name, session, function (err, row) {
if(err) {
if(err !== "Invalid session" &&
err !== "Session expired") {
res.send(500);
} else {
res.send(403);
}
return;
}
2013-05-03 20:53:10 +00:00
2013-08-16 18:19:00 +00:00
if(row.global_rank < 255) {
res.send(403);
return;
}
types = types.split(",");
2013-08-16 18:25:36 +00:00
ActionLog.listActions(types, function (err, actions) {
if(err)
actions = [];
2013-08-16 18:25:36 +00:00
res.jsonp(actions);
});
2013-08-16 18:19:00 +00:00
});
2013-08-12 02:32:02 +00:00
});
/* helper function to pipe the last N bytes of a file */
function pipeLast(res, file, len) {
fs.stat(file, function (err, data) {
if(err) {
res.send(500);
return;
2013-05-03 20:53:10 +00:00
}
2013-08-12 02:32:02 +00:00
var start = data.size - len;
if(start < 0)
2013-08-12 02:32:02 +00:00
start = 0;
var end = data.size - 1;
if(end < 0)
end = 0;
2013-08-12 02:32:02 +00:00
fs.createReadStream(file, { start: start, end: end })
.pipe(res);
});
}
app.get("/api/logging/syslog", function (req, res) {
Server.stats.record("api", "/api/logging/syslog");
2013-08-12 02:32:02 +00:00
res.type("text/plain");
res.setHeader("Access-Control-Allow-Origin", "*");
var name = req.query.name;
var session = req.query.session;
2013-08-16 18:19:00 +00:00
db.userLoginSession(name, session, function (err, row) {
if(err) {
if(err !== "Invalid session" &&
err !== "Session expired") {
res.send(500);
} else {
res.send(403);
}
return;
}
if(row.global_rank < 255) {
res.send(403);
return;
}
2013-08-12 02:32:02 +00:00
pipeLast(res, path.join(__dirname, "../sys.log"), 1048576);
2013-08-16 18:19:00 +00:00
});
2013-08-12 02:32:02 +00:00
});
app.get("/api/logging/errorlog", function (req, res) {
Server.stats.record("api", "/api/logging/errorlog");
2013-08-12 02:32:02 +00:00
res.type("text/plain");
res.setHeader("Access-Control-Allow-Origin", "*");
var name = req.query.name;
var session = req.query.session;
2013-08-16 18:19:00 +00:00
db.userLoginSession(name, session, function (err, row) {
if(err) {
if(err !== "Invalid session" &&
err !== "Session expired") {
res.send(500);
} else {
res.send(403);
}
return;
}
if(row.global_rank < 255) {
res.send(403);
return;
}
2013-08-12 02:32:02 +00:00
pipeLast(res, path.join(__dirname, "../error.log"), 1048576);
2013-08-16 18:19:00 +00:00
});
2013-08-12 02:32:02 +00:00
});
app.get("/api/logging/channels/:channel", function (req, res) {
Server.stats.record("api", "/api/logging/channels/:channel");
2013-08-12 02:32:02 +00:00
res.type("text/plain");
res.setHeader("Access-Control-Allow-Origin", "*");
var name = req.query.name;
var session = req.query.session;
2013-08-16 18:19:00 +00:00
db.userLoginSession(name, session, function (err, row) {
if(err) {
if(err !== "Invalid session" &&
err !== "Session expired") {
res.send(500);
} else {
res.send(403);
}
return;
}
2013-08-12 02:32:02 +00:00
2013-08-16 18:19:00 +00:00
if(row.global_rank < 255) {
res.send(403);
return;
}
2013-08-12 02:32:02 +00:00
2013-08-16 18:19:00 +00:00
var chan = req.params.channel || "";
if(!$util.isValidChannelName(chan)) {
res.send(400);
return;
2013-08-12 02:32:02 +00:00
}
2013-08-16 18:19:00 +00:00
fs.exists(path.join(__dirname, "../chanlogs", chan + ".log"),
function(exists) {
2013-08-16 18:19:00 +00:00
if(exists) {
pipeLast(res, path.join(__dirname, "../chanlogs",
chan + ".log"), 1048576);
2013-08-16 18:19:00 +00:00
} else {
res.send(404);
}
});
2013-08-12 02:32:02 +00:00
});
});
2013-07-16 15:46:09 +00:00
2013-08-08 03:44:41 +00:00
return null;
2013-05-03 20:53:10 +00:00
}