This repository has been archived by the owner on Jun 9, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathserver.py
executable file
·300 lines (270 loc) · 10 KB
/
server.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
300
#!/usr/bin/env python3
import os
import urllib.parse
import cleancss
import tornado.gen
import tornado.escape
import tornado.httpclient
import tornado.ioloop
import tornado.web
from config import web as config
import github
import db
class BaseHandler(tornado.web.RequestHandler):
def render(self, *args, **kwargs):
kwargs['host'] = config.host
return super(BaseHandler, self).render(*args, **kwargs)
def render_string(self, *args, **kwargs):
s = super(BaseHandler, self).render_string(*args, **kwargs)
return s.replace(b'\n', b'') # this is like Django's {% spaceless %}
def get_current_user(self):
github_id = self.get_secure_cookie('github_id')
if github_id is not None:
return {
'github_id': int(github_id),
'is_mentor': int(self.get_secure_cookie('is_mentor')),
'username': self.get_secure_cookie('username'),
'avatar_url': self.get_secure_cookie('avatar_url'),
}
@property
def db(self):
return self.application.db
class MainHandler(BaseHandler):
@tornado.gen.coroutine
def get(self):
self.render('home.html')
class LoginHandler(BaseHandler, github.GithubMixin):
@tornado.gen.coroutine
def get(self):
if self.get_argument('code', False):
github_user = yield self.get_authenticated_user(
redirect_uri=config.host + '/github_oauth',
code=self.get_argument('code'),
)
exists = yield self.db.update_access_token(github_user)
if exists:
yield self.create_session(github_user['id'])
self.redirect('/')
else: # new user
yield self.db.create_user(github_user)
emails = yield self.github_request('/user/emails', github_user['access_token'],
headers={'Accept': 'application/vnd.github.v3'})
for email in emails:
if email['verified']:
break
yield self.db.set_contact_info(github_user['id'], db.ContactInfoType.EMAIL, email['email'])
yield self.create_session(github_user['id'])
self.redirect('/account')
else:
self.authorize_redirect(
redirect_uri=config.host + '/github_oauth',
scope=['user:email'],
)
@tornado.gen.coroutine
def create_session(self, github_id):
user = yield self.db.get_user(github_id)
email = yield self.db.get_contact_info(github_id, db.ContactInfoType.EMAIL)
self.set_secure_cookie('github_id', str(user['github_id']))
self.set_secure_cookie('is_mentor', str(user['is_mentor']))
self.set_secure_cookie('username', user['username'])
self.set_secure_cookie('avatar_url', self.avatar_url(user['username'], email))
class GithubEmailsHandler(BaseHandler, github.GithubMixin):
@tornado.web.authenticated
@tornado.gen.coroutine
def get(self):
user = yield self.db.get_user(self.current_user['github_id'])
emails = yield self.github_request('/user/emails', user['access_token'],
headers={'Accept': 'application/vnd.github.v3'})
rval = []
for email in emails:
if email['verified']:
del email['verified']
rval.append(email)
self.set_header('Content-Type', 'application/json')
self.write(tornado.escape.json_encode(rval))
class LogoutHandler(BaseHandler):
def get(self):
self.clear_all_cookies()
self.redirect('/')
class UserListHandler(BaseHandler, github.GithubMixin):
@tornado.gen.coroutine
def get(self):
user_rows = yield self.db.get_userlist()
users = []
is_mentor = (self.current_user and self.current_user['is_mentor'])
for user in user_rows:
user = user.copy()
user['avatar_url'] = self.avatar_url(user['username'], user['info'])
if not is_mentor:
user['note'] = None
users.append(user)
self.render('users.html', users=users)
class MailHandler(BaseHandler):
@tornado.web.authenticated
@tornado.gen.coroutine
def post(self, username):
from_user = self.current_user
from_email = yield self.db.get_contact_info(from_user['github_id'], db.ContactInfoType.EMAIL)
from_username = from_user['username'].decode('utf-8')
to_user = yield self.db.get_user_by('username', username)
to_email = yield self.db.get_contact_info(to_user['github_id'], db.ContactInfoType.EMAIL)
data = {
'from': '%s <%s>' % (from_username, from_email),
'to': '%s <%s>' % (username, to_email),
'subject': 'lpmc message from %s' % from_username,
'text': self.get_body_argument('body'),
}
request = tornado.httpclient.HTTPRequest(
method='POST',
url='https://api.mailgun.net/v2/lpmc.io/messages',
auth_username='api',
auth_password=config.mailgun_api_key,
body=urllib.parse.urlencode(data),
)
response = yield tornado.httpclient.AsyncHTTPClient().fetch(request)
data = tornado.escape.json_decode(response.body)
self.render('mail.html', username=username, message=data['message'])
class ClaimHandler(BaseHandler):
@tornado.web.authenticated
@tornado.gen.coroutine
def post(self, username):
if not self.current_user['is_mentor']:
raise tornado.web.HTTPError(403)
mentee = yield self.db.get_user_by('username', username)
if mentee['is_mentor']:
raise tornado.web.HTTPError(403)
yield self.db.create_mentorship(mentee['github_id'], self.current_user['github_id'])
self.redirect('/users/' + username)
class UnclaimHandler(BaseHandler):
@tornado.web.authenticated
@tornado.gen.coroutine
def post(self, username):
if not self.current_user['is_mentor']:
raise tornado.web.HTTPError(403)
mentee = yield self.db.get_user_by('username', username)
yield self.db.remove_mentorship(mentee['github_id'], self.current_user['github_id'])
self.redirect('/users/' + username)
class NoteHandler(BaseHandler):
@tornado.web.authenticated
@tornado.gen.coroutine
def post(self, username):
if not self.current_user['is_mentor']:
raise tornado.web.HTTPError(403)
user = yield self.db.get_user_by('username', username)
yield self.db.update_note(user['github_id'], self.get_argument('note'))
self.redirect('/users/' + username)
class ProfileHandler(BaseHandler, github.GithubMixin):
@tornado.gen.coroutine
def get(self, username):
user = yield self.db.get_user_by('username', username)
github_id = user['github_id']
contact_info = yield self.db.get_contact_info(github_id)
avatar_url = self.avatar_url(user['username'], contact_info[db.ContactInfoType.EMAIL])
irc_nick = contact_info.get(db.ContactInfoType.IRC)
mentor = questions = answers = None
mentees = []
if user['is_mentor']:
mentees = yield self.db.get_mentees(user)
else:
mentor = yield self.db.get_mentor(github_id)
if self.current_user and self.current_user['is_mentor']:
questions, answers = yield self.db.get_questionnaire(github_id)
self.render('profile.html', user=user, avatar_url=avatar_url, mentor=mentor, mentees=mentees,
questions=questions, answers=answers, note=user['note'], irc_nick=irc_nick)
class AccountHandler(BaseHandler):
@tornado.web.authenticated
@tornado.gen.coroutine
def get(self):
github_id = self.current_user['github_id']
contact_info = yield self.db.get_contact_info(github_id)
questions, answers = yield self.db.get_questionnaire(github_id)
self.render('account.html', contact_info=contact_info, questions=questions, answers=answers,
ContactInfoType=db.ContactInfoType)
class ContactInfoHandler(BaseHandler):
@tornado.web.authenticated
@tornado.gen.coroutine
def post(self):
info_type = int(self.get_argument('info_type'))
info = self.get_argument('info')
yield self.db.set_contact_info(self.current_user['github_id'], info_type, info)
self.set_header('Content-Type', 'application/json')
self.write('true')
class QuestionnaireHandler(BaseHandler):
@tornado.web.authenticated
@tornado.gen.coroutine
def post(self):
answers = []
for i in range(1, 6):
answers.append(self.get_argument('q%d' % i, None))
yield self.db.update_questionnaire(self.current_user['github_id'], *answers)
self.redirect('/account')
class DeleteAccountHandler(BaseHandler):
@tornado.web.authenticated
def get(self):
self.render('delete_account.html')
@tornado.web.authenticated
@tornado.gen.coroutine
def post(self):
yield self.db.delete_user(self.current_user['github_id'])
self.redirect('/logout')
class AdminHandler(BaseHandler):
@tornado.web.authenticated
@tornado.gen.coroutine
def get(self):
if not self.current_user['is_mentor']:
raise tornado.web.HTTPError(403)
user_rows = yield self.db.get_userlist()
self.render('admin.html', users=user_rows)
@tornado.web.authenticated
@tornado.gen.coroutine
def post(self):
if not self.current_user['is_mentor']:
raise tornado.web.HTTPError(403)
add_mentor_set = set(int(x) for x in self.request.arguments.keys())
user_rows = yield self.db.get_user_ids()
users = []
for user in user_rows:
users.append(user['github_id'])
remove_mentor_set = set(users) - add_mentor_set
remove_mentor_set.discard(self.current_user['github_id'])
if len(add_mentor_set) > 0:
self.db.update_is_mentor(add_mentor_set, 1)
if len(remove_mentor_set) > 0:
self.db.update_is_mentor(remove_mentor_set, 0)
self.redirect('/admin')
class CSSHandler(tornado.web.RequestHandler):
def get(self, css_path):
css_path = os.path.join(os.path.dirname(__file__), 'static', css_path) + '.ccss'
with open(css_path, 'r') as f:
self.set_header('Content-Type', 'text/css')
self.write(cleancss.convert(f))
if __name__ == '__main__':
app = tornado.web.Application(
handlers=[
(r'/', MainHandler),
(r'/github_oauth', LoginHandler),
(r'/github_emails', GithubEmailsHandler),
(r'/logout', LogoutHandler),
(r'/users', UserListHandler),
(r'/users/(.*)/mail', MailHandler),
(r'/users/(.*)/claim', ClaimHandler),
(r'/users/(.*)/unclaim', UnclaimHandler),
(r'/users/(.*)/note', NoteHandler),
(r'/users/(.*)', ProfileHandler),
(r'/account', AccountHandler),
(r'/account/contact_info', ContactInfoHandler),
(r'/account/questionnaire', QuestionnaireHandler),
(r'/account/delete', DeleteAccountHandler),
(r'/admin', AdminHandler),
(r'/(css/.+)\.css', CSSHandler),
],
template_path=os.path.join(os.path.dirname(__file__), 'templates'),
static_path=os.path.join(os.path.dirname(__file__), 'static'),
login_url='/github_oauth',
cookie_secret=config.cookie_secret,
debug=config.debug,
)
app.listen(config.port)
app.db = db.MomokoDB()
print('listening on :%d' % config.port)
tornado.ioloop.IOLoop.instance().start()