summaryrefslogtreecommitdiff
path: root/modules/todo/todo.js
blob: 8fabc63d71b58c4afa578143fe991ffbd6a085d4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
"use strict";

var cmn=require("../$common.js"),
    persist=require("node-persist"),
    bcrypt=require("bcrypt"),
    basicAuth=require("basic-auth"),
    fs=require("fs");

var bcryptHashRounds=10;

var moddir=null;

persist=persist.create({
	dir:"persist/todo",
	continuous:false,
	interval:false
});
persist.initSync();

//tasks: {"user": [{id: Int,subject: String,repweeks: Int,date: Date}]}
//accounts: {"user": hash (String)}
//repweeks==0 implies no repetition
var nextid=persist.getItemSync("nextid");
if(nextid==null){
	nextid=1;
	persist.setItemSync("nextid",nextid);
}
var tasks=persist.getItemSync("tasks");
(function(){
	if(tasks==null){
		tasks={};
		persist.setItemSync("tasks",tasks);
	} else {
		for(var user in tasks){
			for(var task of tasks[user]){
				task.date=new Date(task.date);
				if(nextid<=task.id)nextid=task.id+1;
			}
		}
		persist.setItemSync("nextid",nextid);
	}
})();
var accounts=persist.getItemSync("accounts");
if(accounts==null){
	accounts={};
	persist.setItemSync("accounts",accounts);
}
var naccounts=0;
(function(){
	var user;
	for(user in accounts)naccounts++;
})();


function shiftDate(date,repweeks){
	var Y=date.getFullYear(),
	    M=date.getMonth(),
	    D=date.getDate(),
	    h=date.getHours(),
	    m=date.getMinutes(),
	    s=date.getSeconds(),
	    ms=date.getMilliseconds();
	return new Date(Y,M,D+7*repweeks,h,m,s,ms);
}


function sendUnauth(res){
	res.set("WWW-Authenticate","Basic realm=Authorization required");
	return res.sendStatus(401);
}

function unknownUserHandler(req,res,next){
	res.sendFile(moddir+"/unknownuser.html");
}

function authMiddleware(req,res,next){
	var user=basicAuth(req);
	req.authuser=null;
	if(!user||!user.name){
		sendUnauth(res);
		return;
	}
	req.authuser=user.name;
	if(accounts[req.authuser]){
		bcrypt.compare(user.pass,accounts[req.authuser],function(err,ok){
			if(ok)next();
			else sendUnauth(res);
		});
	} else {
		unknownUserHandler(req,res,next);
	}
}

function asciiValid(str){
	var i,c;
	for(i=0;i<str.length;i++){
		c=str.charCodeAt(i);
		if(c<32||c>=127)return false;
	}
	return true;
}


module.exports=function(app,io,_moddir){
	moddir=_moddir;

	//first the endpoints that need to bypass authMiddleware
	app.get("/todo/authfail",function(req,res){
		sendUnauth(res);
	});
	app.post("/todo/createuser",function(req,res){
		var user=basicAuth(req);
		if(!user||!user.name){
			res.status(400).send("No credentials sent");
			return;
		}
		if(user.name.length<3||user.name.length>32||!asciiValid(user.name)){
			res.status(400).send("Invalid username");
			return;
		}
		if(user.pass.length<3||user.pass.length>32||!asciiValid(user.pass)){
			res.status(400).send("Invalid password");
			return;
		}
		if(accounts[user.name]){
			res.status(400).send("User already exists");
			return;
		}
		if(naccounts>=20){
			res.status(500).send("Too many accounts created, please contact Tom...");
			return;
		}
		bcrypt.hash(user.pass,bcryptHashRounds,function(err,hash){
			if(!hash){
				res.status(500).send("Something went wrong...");
				console.log(err);
				return;
			}
			accounts[user.name]=hash;
			tasks[user.name]=[];
			persist.setItemSync("accounts",accounts);
			persist.setItemSync("tasks",tasks);
			res.status(200).end();
		});
	});

	app.all(["/todo","/todo/*"],authMiddleware); //for all the other endpoints

	app.get("/todo",function(req,res){
		var contents=fs.readFileSync(moddir+"/todo.html","utf8");
		var replaced=contents.replace("/*REPLACEME*/null/*TODOLIST*/",
		                              JSON.stringify(tasks[req.authuser]));
		res.send(replaced);
	});
	app.get("/todo/list",function(req,res){
		res.json(tasks[req.authuser]);
	});
	app.delete("/todo/task",function(req,res){
		var id=+req.body;
		var i;
		var fail=false;
		var usertasks=tasks[req.authuser];
		if(id<0||~~id!=id||isNaN(id)||!usertasks){
			fail=true;
		} else {
			for(i=0;i<usertasks.length;i++)if(usertasks[i].id==id)break;
			if(i==usertasks.length)fail=true;
			else {
				usertasks.splice(i,1);
				persist.setItemSync("tasks",tasks);
			}
		}
		if(fail)res.status(404).send("Unknown id");
		else res.status(200).end();
	});
	app.post("/todo/task/shiftahead",function(req,res){
		var id=+req.body;
		var i;
		var fail=false;
		var usertasks=tasks[req.authuser];
		var now;
		if(id<0||~~id!=id||isNaN(id)||!usertasks){
			fail=true;
		} else {
			for(i=0;i<usertasks.length;i++)if(usertasks[i].id==id)break;
			if(i==usertasks.length)fail=true;
			else if(usertasks[i].repweeks==0){
				res.status(400).send("Can't shiftahead a non-repeating task");
				return;
			} else {
				now=new Date();
				while(usertasks[i].date<now){ // First move up to now
					usertasks[i].date=shiftDate(usertasks[i].date,usertasks[i].repweeks);
				}
				// Then for the actual shiftahead:
				usertasks[i].date=shiftDate(usertasks[i].date,usertasks[i].repweeks);
				persist.setItemSync("tasks",tasks);
			}
		}
		if(fail)res.status(404).send("Unknown id");
		else res.status(200).end();
	});
	app.post("/todo/task",function(req,res){
		var obj;
		try {
			obj=JSON.parse(req.body);
		} catch(e){
			res.status(400).send("Invalid request");
			return;
		}
		var subject=obj.subject+"",repweeks=+obj.repweeks,date=new Date(obj.date);
		if(subject.length==0||
		   isNaN(repweeks)||repweeks<0||repweeks!=~~repweeks||
		   isNaN(date.getTime())){
			res.status(400).send("Invalid data");
			return;
		}
		if(tasks[req.authuser].length>=40){
			res.status(400).send("Isn't 40 tasks enough for you?");
			return;
		}
		tasks[req.authuser].push({
			id:nextid++,
			subject:subject,
			repweeks:repweeks,
			date:date
		});
		persist.setItemSync("tasks",tasks);
		persist.setItemSync("nextid",nextid);
		res.status(200).end();
	});
};