-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRegServ.py
executable file
·310 lines (256 loc) · 10.9 KB
/
RegServ.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
301
302
303
304
305
306
307
308
309
310
#!/usr/bin/env python3
import collections
import hashlib
import json
import logging
import os
import re
import socket
import sys
import time
import tornado.gen
import tornado.ioloop
import tornado.options
import tornado.process
import tornado.web
# Constants
REGSERV_ADDRESS = '127.0.0.1'
REGSERV_PORT = 9667
REGSERV_URL = 'https://regserv.ndlug.org'
HASHCODE_TIMEOUT = 60 * 60 # 1 Hour
# Functions
def checksum(s):
return hashlib.sha1(s.encode()).hexdigest()
def is_valid_email(e):
return re.match(r'.+@.+', e) # TODO: improve regex
# Handlers
class RegServHandler(tornado.web.RequestHandler):
@tornado.gen.coroutine
def get(self, hashcode=None):
if not hashcode:
return self.render('index.html')
if hashcode not in self.application.hashes:
return self.render('error.html',
summary = 'Invalid Registration Link',
description = f'''
The link you used is invalid. Please return to the registration page to send a new link.
''')
timestamp = self.application.hashes[hashcode].get('timestamp', 0)
if (time.time() - timestamp) >= HASHCODE_TIMEOUT:
del self.application.hashes[hashcode]
self.application.checkpoint()
return self.render('error.html',
summary = 'Expired Registration Link',
description = f'''
The link you used has expired. Please return to the registration page to send a new link.
''')
email = self.application.hashes[hashcode].get('email')
if not email:
del self.application.hashes[hashcode]
self.application.checkpoint()
return self.render('error.html',
summary = 'Invalid Registration Link',
description = f'''
The link you used does not have an associated email. Please return to the registration page to try again.
''')
return self.render('register.html', email=email)
@tornado.gen.coroutine
def post(self, hashcode=None):
if hashcode == 'email':
email = self.get_argument('email', None)
if not is_valid_email(email):
return self.render('error.html',
summary = 'Invalid Registration Email',
description = f'''
The email you used is invalid. Please return to the registration page to try again.
''')
if email not in self.application.emails:
self.application.emails[email] = {'last_emailed': 0, 'nicks': []}
last_emailed = self.application.emails[email].get('last_emailed', 0)
if (time.time() - last_emailed) < HASHCODE_TIMEOUT:
return self.render('error.html',
summary = 'Already Sent Registration Link',
description = f'''
A registration link has already been sent. Please check your mailbox for the link.
''')
hashcode = checksum(f'{email} + {str(time.time())}')
stream = tornado.process.Subprocess.STREAM
command = ['msmtp', '-C' 'configs/msmtprc', email]
process = tornado.process.Subprocess(command, stdin=stream)
result = yield process.stdin.write(
# TODO: Give deadline in human readable format
# TODO: Make this parameterizable
f'''Subject: [RegServ] Registration Link for chat.ndlug.org
Use the following link to create or reset an IRC account on chat.ndlug.org:
{REGSERV_URL}/{hashcode}
This link will be valid for 1 hour.
'''.encode())
process.stdin.close()
try:
yield process.wait_for_exit()
except tornado.process.CalledProcessError as e:
self.application.logger.error(e)
return self.render('error.html',
summary = 'Unable to Send Registration Link',
description = f'''
We were unable to send a registration link to <a href="mailto:{ email }">{ email }</a>:
<pre>
{ e }
</pre>
''')
self.application.emails[email]['last_emailed'] = time.time()
self.application.hashes[hashcode] = {'email': email, 'timestamp': time.time()}
self.application.checkpoint()
return self.render('success.html',
summary = 'Registration Link Sent',
description = f'''
A registration link was sent to <a href="mailto:{ email }">{ email }</a>. This
link will expire within <b>one hour</b>.
''')
elif hashcode in self.application.hashes:
email = self.application.hashes[hashcode].get('email')
if not email:
return self.render('error.html',
summary = 'Invalid Registration Link',
description = f'''
The link you used does not have an associated email. Please return to the registration page to try again.
''')
timestamp = self.application.hashes[hashcode].get('timestamp', 0)
if (time.time() - timestamp) >= HASHCODE_TIMEOUT:
return self.render('error.html',
summary = 'Expired Registration Link',
description = f'''
The link you used has expired. Please return to the registration page to send a new link.
''')
nickname = self.get_argument('nickname', None)
password = self.get_argument('password', None)
if ' ' in nickname:
return self.render('error.html',
summary = 'Invalid Registration Nickname',
description = f'''
You cannot have spaces in your nickname. Please try again.
''')
if not password:
return self.render('error.html',
summary = 'Invalid Registration Password',
description = f'''
You must enter in a valid password. Please try again.
''')
# TODO: Check if nickname belongs to email address
unclaimed = any(nickname.lower() in d['nicks'] for e, d in self.application.emails.items() if email != e)
if unclaimed:
# TODO: delete old hash
return self.render('error.html',
summary = 'Claimed Account',
description = f'''
The nickname you are trying to register or update is associated with another
email address. Please register another nickname or use the appropriate email
address.
''')
stream = tornado.process.Subprocess.STREAM
environ = dict(os.environ, **{'USER_NICKNAME': nickname, 'USER_PASSWORD': password})
command = './scripts/irc_account.py'
process = tornado.process.Subprocess(command, stderr=stream, env=environ)
result1 = yield process.stderr.read_until_close()
try:
yield process.wait_for_exit()
except tornado.process.CalledProcessError as e:
self.application.logger.error(e)
return self.render('error.html',
summary = 'Unable to Register or Update IRC Account',
description = f'''
There was a problem registering or updating the IRC account:
<pre>
{ e }
</pre>
''')
command = './scripts/lounge_account.py'
process = tornado.process.Subprocess(command, stderr=stream, env=environ)
result2 = yield process.stderr.read_until_close()
try:
yield process.wait_for_exit()
except tornado.process.CalledProcessError as e:
self.application.logger.error(e)
return self.render('error.html',
summary = 'Unable to Register or Update Lounge Account',
description = f'''
There was a problem registering or updating the Lounge account:
<pre>
{ e }
</pre>
<pre>
{ result2.decode() }
</pre>
''')
del self.application.hashes[hashcode]
if nickname.lower() not in self.application.emails[email]['nicks']:
self.application.emails[email]['nicks'].append(nickname.lower())
self.application.emails[email]['last_emailed'] = 0
self.application.checkpoint()
return self.render('success.html',
summary = 'Account Registered or Updated',
description = f'''
Congratulations! We have updated the account information for { nickname }.
Feel free to login to <a href="https://chat.ndlug.org">chat.ndlug.org</a>.
</p>
</div>
<div>
<p>
If this is your first time logging into the server, then you will need to make
the following changes in the initial <b>Network Settings</b> page as shown below:
</p>
<ol>
<li>Replace the <b><tt>Nick</tt></b> and <tt>Username</tt> fields with <b>{ nickname }</b>.
<li>Replace the <b><tt>Password</tt></b> field with the registered <b>password</b>.</li>
</ol>
<p class="text-center">
<img class="img-fluid img-thumbnail rounded" src="https://yld.me/raw/VjT.png">
''')
else:
return self.render('error.html',
summary = 'Invalid Registration Link',
description = f'''
The link you used is invalid. Please return to the registration page to send a new link.
''')
# Application
class RegServApplication(tornado.web.Application):
def __init__(self, **settings):
tornado.web.Application.__init__(self, template_path='templates', **settings)
self.logger = logging.getLogger()
self.address = settings.get('address') or self.address
self.port = settings.get('port') or self.port
try:
# TODO: parameterize
json_data = json.load(open('data/RegServ.json'))
self.emails = json_data.get('emails', {})
self.hashes = json_data.get('hashes', {})
except IOError:
self.emails = {}
self.hashes = {}
self.add_handlers('.*', [
(r'.*/(.*)', RegServHandler),
])
def run(self):
try:
self.listen(self.port, self.address)
except socket.error as e:
self.logger.fatal(f'Unable to listen on {self.address}:{self.port} = {e}')
sys.exit(1)
self.logger.info(f'Listening on {self.address}:{self.port}')
tornado.ioloop.IOLoop.current().start()
def checkpoint(self):
# TODO: parameterize
with open('data/RegServ.json', 'w') as stream:
json.dump({
'emails': self.emails,
'hashes': self.hashes,
}, stream)
# Main Execution
if __name__ == '__main__':
tornado.options.define('address', default=REGSERV_ADDRESS, help='Address to listen on.')
tornado.options.define('port' , default=REGSERV_PORT , help='Port to listen on.')
tornado.options.define('debug' , default=False , help='Enable debugging mode.')
tornado.options.parse_command_line()
options = tornado.options.options.as_dict()
RegServ = RegServApplication(**options)
RegServ.run()