-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbookmarks.py
299 lines (257 loc) · 11.4 KB
/
bookmarks.py
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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2011 Stanley Cai
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import json
import time
import os
import tornado.auth
import tornado.escape
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from tornado.options import define, options
import database
define("port", default=8888, help="run on the given port", type=int)
# TODO update the functions to use exception
# TODO add MYSQL support
BOOKMARKS_DB = database.Connection("bookmarks.db")
class Application(tornado.web.Application):
def __init__(self):
handlers = [
(r"/", MainHandler),
(r"/(\w+)/bookmarks/([0-9]*)", BookmarkHandler),
(r"/upload", UploadHandler),
(r"/setting", SettingHandler),
(r"/auth/login", AuthLoginHandler),
(r"/auth/logout", AuthLogoutHandler),
(r"/auth/signup", AuthSignupHandler),
]
settings = dict(
# TODO update cookie secret
cookie_secret="32oETzKXQAGaYdkL5gEmGeJJFuYh7EQnp2XdTP1o/Vo=",
login_url="/auth/login",
template_path= os.path.join(os.path.dirname(__file__), "templates"),
static_path = os.path.join(os.path.dirname(__file__), "static"),
ui_modules = {"Entry": EntryModule },
)
tornado.web.Application.__init__(self, handlers, **settings)
class BaseHandler(tornado.web.RequestHandler):
# TODO validate the user name from remote
def is_valid_username(self, name):
return True
# TODO validate the email address from remote
def is_valid_email(self, email):
return True
# TODO validate the password from remote
def is_valid_password(self, password):
return True
def get_current_user(self):
user_id = self.get_secure_cookie("user")
if not user_id:
return None
else:
return BOOKMARKS_DB.get("SELECT * FROM users WHERE id = %d" % int(user_id))
def get_user_from_alias(self, user_alias):
return BOOKMARKS_DB.get("SELECT * FROM users WHERE alias=\"%s\"" % user_alias)
class AuthSignupHandler(BaseHandler):
def _generate_alias(self, name, email):
s = hashlib.sha1()
s.update(name)
s.update(email)
s.update(str(time.time()))
return s.hexdigest()[:6]
def post(self):
username = self.get_argument("username")
email = self.get_argument("email")
password = self.get_argument("password")
if not self.is_valid_username(username) or \
not self.is_valid_email(email) or \
not self.is_valid_password(password):
self.render("login_or_signup.html", error_message = "Invalid email or user name")
else:
user = BOOKMARKS_DB.get("SELECT * FROM users WHERE email=\"%s\"" %
email)
if not user:
BOOKMARKS_DB.execute( "INSERT INTO users (username, email, password, alias) \
VALUES (\"%s\", \"%s\", \"%s\")" % \
(username, email, password, \
self._generate_alias(username, email)))
user = BOOKMARKS_DB.get("SELECT * FROM users WHERE email=\"%s\"" %
email)
BOOKMARKS_DB.commit()
self.set_secure_cookie("user", str(user.id))
self.redirect("/")
else:
self.render("login_or_signup.html", error_message = "This email is registered.")
def get(self):
user = self.get_current_user()
if user:
self.clear_secure_cookie("user")
self.render("login_or_signup.html")
class AuthLoginHandler(BaseHandler):
def post(self):
username_or_email = self.get_argument("username_or_email")
password = self.get_argument("password")
if not self.is_valid_username(username_or_email) and \
not self.is_valid_email(username_or_email):
self.render("login_or_signup.html", error_message = "Invalid email or username")
else:
user = BOOKMARKS_DB.get("SELECT * FROM users WHERE email=\"%s\" and password=\"%s\"" %
(username_or_email, password))
if not user:
user = BOOKMARKS_DB.get("SELECT * FROM users WHERE username=\"%s\" and password=\"%s\"" %
(username_or_email, password))
if not user:
self.render("login_or_signup.html", error_message = "No such user")
return
self.set_secure_cookie("user", str(user.id))
self.redirect("/")
def get(self):
user = self.get_current_user()
if user:
self.clear_secure_cookie("user")
self.render("login_or_signup.html") # need render this page?
class AuthLogoutHandler(BaseHandler):
def get(self):
user = self.get_current_user()
if user:
self.clear_cookie("user")
self.redirect("/")
class MainHandler(BaseHandler):
def get(self):
user = self.get_current_user()
print user
if not user:
self.render("login_or_signup.html")
else:
entries = []
results = BOOKMARKS_DB.query("SELECT * FROM bookmarks WHERE user_id=\"%s\" ORDER BY modified_at DESC" % user.id)
for record in results:
entries.append((record.title, record.url, record.modified_at))
# TODO update the main page (including logout link and setting link)
self.render("main.html", user = user, entries = entries)
class SettingHandler(BaseHandler):
def get(self):
user = self.get_current_user()
if not user:
self.render("login_or_signup.html")
else:
# TODO Polish setting page
self.render("setting.html", user = user)
def post(self):
user = self.get_current_user()
if not user:
self.render("login_or_signup.html")
else:
username = self.get_argument('username')
password1 = self.get_argument('password1')
password2 = self.get_argument('password2')
if username != user.username or password1 != password2:
raise Exception()
return
BOOKMARKS_DB.execute('UPDATE users SET password=\"%s\" WHERE id=\"%d\"' % (password1, user.id))
BOOKMARKS_DB.commit()
self.redirect("/")
class UploadHandler(BaseHandler):
def get(self):
user = self.get_current_user()
if not user:
self.render("login_or_signup.html")
else:
title = self.get_argument('title')
url = self.get_argument('url')
date = int(time.time())
record = BOOKMARKS_DB.get('SELECT * FROM bookmarks WHERE user_id=\"%d\" AND title=\"%s\" AND url=\"%s\"' % (user.id, title, url))
if record is None:
BOOKMARKS_DB.execute('INSERT INTO bookmarks (title, url, modified_at, user_id, tag) VALUES (\"%s\", \"%s\", \"%d\", \"%d\", 0)' % (title, url, date, user.id))
else:
BOOKMARKS_DB.execute('UPDATE bookmarks SET modified_at=\"%d\" WHERE title=\"%s\" and url=\"%s\"' % (date, title, url))
BOOKMARKS_DB.commit()
# TODO test all the REST APIs
class BookmarkHandler(BaseHandler):
def get(self, user_alias, bookmark_id):
user = self.get_user_from_alias(user_alias)
if not user:
raise Exception()
return
try:
index = int(bookmark_id)
records = BOOKMARKS_DB.query('SELECT * FROM bookmarks WHERE user_id=\"%d\" ORDER BY modified_at DESC' % user.id)
if records is None:
raise Exception()
if index >= len(records):
return
self.write(json.dumps((records[index].title, record[index].url, record[index].last_modified)))
except ValueError:
results = []
records = BOOKMARKS_DB.query('SELECT * FROM bookmarks WHERE user_id=\"%d\" ORDER BY modified_at DESC' % user.id)
for record in records:
results.append((record.title, record.url, record.last_modified))
self.write(json.dumps(results))
def put(self, user_alias, bookmark_id):
current_user_id = self.get_secure_cookie("user")
if not current_user_id:
self.render("login_or_signup.html")
user = self.get_user_from_alias(user_alias)
if not user or user.id != current_user_id:
raise Exception()
return
title, url = json.loads(self.request.body)
date = int(time.time())
try:
index = int(bookmark_id)
records = BOOKMARKS_DB.query('SELECT * FROM bookmarks WHERE user_id=\"%d\" ORDER BY modified_at DESC' % user.id)
if records is None:
raise Exception()
if index >= len(records):
raise ValueError()
record = BOOKMARKS_DB.get('SELECT * FROM bookmarks WHERE id=\"%d\"' % records[index].id)
if record is not None:
BOOKMARKS_DB.execute('UPDATE bookmarks SET title=\"%s\", url=\"%s\", modified_at=\"%d\" WHERE id = \"%d\"' % (title, url, date, record.id))
except ValueError:
BOOKMARKS_DB.execute('INSERT INTO bookmarks (title, url, modified_at, tag, user_id) VALUES (\"%s\", \"%s\", \"%d\", 0, \"%d\")' % (title, url, date, user.id))
finally:
BOOKMARKS_DB.commit()
def delete(self, user_id, bookmark_id):
current_user_id = self.get_secure_cookie("user")
if not current_user_id:
self.render("login_or_signup.html")
user = self.get_user_from_alias(user_alias)
if not user or user.id != current_user_id:
raise Exception()
return
try:
index = int(bookmark_id)
records = BOOKMARKS_DB.query('SELECT * FROM bookmarks WHERE user_id=\"%d\" ORDER BY modified_at DESC' % user_id)
if records is None:
raise Exception()
if index >= len(records):
raise ValueError()
BOOKMARKS_DB.execute('DELETE FROM bookmarks WHERE id=\"%d\"' % records[index].id)
BOOKMARKS_DB.commit()
except ValueError:
self.write("Invalid bookmark_id")
class EntryModule(tornado.web.UIModule):
def render(self, entry, isAdmin=False):
return self.render_string("modules/entry.html", entry=entry, isAdmin=isAdmin)
def main():
tornado.options.parse_command_line()
http_server = tornado.httpserver.HTTPServer(Application())
http_server.listen(options.port)
tornado.ioloop.IOLoop.instance().start()
if __name__ == "__main__":
main()