-
Notifications
You must be signed in to change notification settings - Fork 1
/
admin.py
427 lines (414 loc) · 20.4 KB
/
admin.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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
import string
import random
import os
import re
import time
import copy
#tornadoweb
import tornado.escape
import tornado.web
#lxml
import lxml
from lxml.html import builder as E
from lxml.builder import ElementMaker as EM
#sqlalchemy
from sqlalchemy.orm import sessionmaker
#my modules
import config
import initiate
def login_page_gen():
html = E.HTML(
E.HEAD(
E.LINK(rel="stylesheet", href="/css/deeplight.css", type="text/css"),
E.TITLE("Administration and moderation")
),
E.BODY(
E.H1(E.CLASS("heading"), "Farlight Engine Imageboard"),
E.P(E.CLASS("loginmessage"), "You need to login"),
E.FORM(E.CLASS("loginform"),
E.TABLE(
E.TR(E.TD('LOGIN'),
E.TD(E.INPUT(type = 'text', name = 'login', value = ''))
),
E.TR(E.TD('PASSWORD'),
E.TD(E.INPUT(type = 'text', name = 'password', value = ''))
),
),
E.INPUT(type = 'submit', value = 'LOGIN'),
method = 'POST',
action = '/admin/login'
)
)
)
return lxml.html.tostring(html)
def main_page_gen():
html = E.HTML(
E.HEAD(
E.LINK(rel="stylesheet", href="/css/deeplight.css", type="text/css"),
E.TITLE("Administration and moderation")
),
E.BODY(
E.DIV(
E.DIV(E.CLASS('logout'), E.A('Logout', href='/admin/logout')),
E.H2(E.CLASS("heading"), "Admin menu"),
),
E.P(E.CLASS("loginmessage"), "You are logged in"),
E.DIV(E.CLASS('adminmainmenu'),
E.A("create board", href = '?action=create&instance=board'),
E.A("manage boards", href = '?action=list&list=boards&purpose=admin'),
E.A("manage bans", href = '?action=list&list=bans&purpose=moderator'),
E.A("manage users", href = '?action=list&list=users&purpose=admin'),
E.A("change password", href = '?action=change&instance=password'),
)
)
)
return lxml.html.tostring(html)
def board_creation_menu(): #here is the html board creation menu
html = E.HTML(
E.HEAD(
E.LINK(rel="stylesheet", href="/css/deeplight.css", type="text/css"),
E.TITLE("Creating board")
),
E.BODY(
E.DIV(E.CLASS('adminupdiv'),
E.DIV(E.CLASS('logout'), E.A('Logout', href='/admin/logout')),
E.H2(E.CLASS("heading"), "Create new board"),
),
E.DIV(E.CLASS("boardcreateform"),
E.FORM(
E.INPUT(type = 'hidden', name = 'action', value = 'create'),
E.INPUT(type = 'hidden', name = 'instance', value = 'board'),
E.TABLE(
E.TR(E.TD('Address'),
E.TD(E.INPUT(type = 'text', name = 'address', value = ''))
),
E.TR(E.TD('Tablename'),
E.TD(E.INPUT(type = 'text', name = 'tablename', value = ''))
),
E.TR(E.TD('Name'),
E.TD(E.INPUT(type = 'text', name = 'name', value = ''))
),
E.TR(E.TD('Fullname'),
E.TD(E.INPUT(type = 'text', name = 'fullname', value = ''))
),
E.TR(E.TD('Description'),
E.TD(E.INPUT(type = 'text', name = 'description', value = ''))
),
E.TR(E.TD('Pics number'),
E.TD(E.INPUT(type = 'number', name = 'picsnum', value = '', min = '0', max = '10'))
),
E.TR(E.TD('Bumplimit'),
E.TD(E.INPUT(type = 'number', name = 'bumplimit', value = '', min = '0'))
),
E.TR(E.TD('Max threads'),
E.TD(E.INPUT(type = 'number', name = 'maxthreads', value = '', min = '-1'))
),
E.TR(E.TD(E.INPUT(type='checkbox', name='delposts', value='1', checked='checked'), 'Удаление постов', colspan='2', style='text-align:center;')),
E.TR(E.TD(E.INPUT(type='checkbox', name='delopposts', value='1', checked='checked'), 'Удаление тредов', colspan='2', style='text-align:center;')),
),
E.INPUT(type = 'submit', value = 'Create'),
method='POST',
action='/admin/'
)
)
)
)
return lxml.html.tostring(html)
def list_boards_menu(board_list, purpose):
"""need to put boards table creating to a separate function in future"""
posts_num_cell = E.DIV(E.SPAN('????', style = 'display:inline-block; width:4em; text-align:center;'),
E.INPUT(type='number', size='6', min='0', value='1', style = 'width: 6em;'),
E.SELECT(E.OPTION('Секунды', value='1'),
E.OPTION('Минуты', value='60'),
E.OPTION('Часы', value='3600'),
E.OPTION('Дни', value='86400', selected='')
),
E.BUTTON('GET', onclick='get_posts_num_from_time(this)', type = 'button'))
tablerows = [E.TR(E.TD(E.A(b.address, href = '/'+b.address)),
E.TD(b.tablename),
E.TD(str(b.name)),
E.TD(str(b.fullname)),
E.TD(str(b.description)),
E.TD(str(b.category)),
E.TD(str(b.pictures)),
E.TD(str(b.bumplimit)),
E.TD(str(b.maxthreads)),
E.TD(copy.copy(posts_num_cell))
)for b in board_list]
#purpose will be applyed later
html = E.HTML(
E.HEAD(
E.LINK(rel="stylesheet", href="/css/deeplight.css", type="text/css"),
E.TITLE("Creating board"),
E.SCRIPT(type = 'text/javascript', src = '/adminscript.js') #js
),
E.BODY(
E.DIV(E.CLASS('adminupdiv'),
E.DIV(E.CLASS('logout'), E.A('Logout', href='/admin/logout')),
E.H2(E.CLASS("heading"), "Listing boards"),
),
E.TABLE(
E.CLASS("boardstable"),
E.TR(E.TH('Адрес'),
E.TH('Таблица'),
E.TH('Название'),
E.TH('Полное название'),
E.TH('Описание'),
E.TH('Категория'),
E.TH('Максимум картинок'),
E.TH('Бамплимит'),
E.TH('Максимум тредов'),
E.TH('Постов за последнее время')
),
*tablerows
)
)
)
return lxml.html.tostring(html)
def list_bans_menu(ban_list, purpose):
"""need to put bans and boards table creating to a joint function in future"""
tablerows = [E.TR(E.TD(str(b.id)),
E.TD(b.ip),
E.TD(b.initiator),
E.TD(time.strftime('%d/%m/%Y %H:%M', time.localtime(b.date))),
E.TD(str(b.level)),
E.TD(E.BUTTON('Снять', type = 'button', onclick = 'remove_ban(this);'))
)for b in ban_list]
#purpose will be applyed later
html = E.HTML(
E.HEAD(
E.LINK(rel="stylesheet", href="/css/deeplight.css", type="text/css"),
E.TITLE("Creating board"),
E.SCRIPT(type = 'text/javascript', src = '/adminscript.js') #js
),
E.BODY(
E.DIV(E.CLASS('adminupdiv'),
E.DIV(E.CLASS('logout'), E.A('Logout', href='/admin/logout')),
E.H2(E.CLASS("heading"), "Listing bans"),
),
E.TABLE(
E.CLASS("boardstable"),
E.TR(E.TH('ID'),
E.TH('IP'),
E.TH('Забанивший'),
E.TH('Дата'),
E.TH('Уровень'),
E.TH('')
),
*tablerows
)
)
)
return lxml.html.tostring(html)
def password_change_menu():
html = E.HTML(
E.HEAD(
E.LINK(rel="stylesheet", href="/css/deeplight.css", type="text/css"),
E.TITLE("Administration and moderation")
),
E.BODY(
E.H1(E.CLASS("heading"), "Farlight Engine Imageboard"),
E.P(E.CLASS("loginmessage"), "Change your password"),
E.FORM(E.CLASS("loginform"),
E.INPUT(type = 'hidden', name = 'action', value = 'change'),
E.INPUT(type = 'hidden', name = 'instance', value = 'password'),
E.TABLE(
E.TR(E.TD('OLD PASSWORD'),
E.TD(E.INPUT(type = 'password', name = 'old_passwd', value = ''))
),
E.TR(E.TD('NEW PASSWORD'),
E.TD(E.INPUT(type = 'password', name = 'new_passwd', value = ''))
),
E.TR(E.TD('NEW PASSWORD AGAIN'),
E.TD(E.INPUT(type = 'password', name = 'new_passwd_again', value = ''))
),
),
E.INPUT(type = 'submit', value = 'LOGIN'),
method = 'POST',
action = '/admin'
)
)
)
return lxml.html.tostring(html)
def admin(requesth):
if requesth.current_user is None:
requesth.set_header('Location', '/admin/login')
requesth.set_status(302)
return 'Redirecting to login'
actions = requesth.get_query_arguments('action')
if actions == []:
return main_page_gen()
elif actions == ['list']:
what_to_list = requesth.get_query_argument('list')
purpose = requesth.get_query_argument('purpose')
#add purpose checking
if what_to_list == 'boards': #here we list boards for management
board_list = initiate.sess.query(initiate.Board).all()
return list_boards_menu(board_list, purpose)
elif what_to_list == 'users':#here we list users for management
return 'users list'
elif what_to_list == 'bans':
ban_list = initiate.sess.query(initiate.Ban).all()
return list_bans_menu(ban_list, purpose)
else:
return 'No such list'
elif actions == ['create']:
create = requesth.get_query_argument('instance')
if create == 'board':
return board_creation_menu()
else:
return 'There are other create menu'
elif actions == ['change']:
change = requesth.get_query_argument('instance')
if change == 'password':
return password_change_menu()
else:
return 'Changing anything than password not implemented'
else:
requesth.write_error(400)
def admin_login(requesth):
Session = sessionmaker(bind=initiate.engine)
session = Session()
result = session.query(initiate.Admin).filter(initiate.Admin.login == requesth.get_body_argument('login')).first()
if result is None:
return 'Incorrect Login\Password'
if requesth.get_body_argument('password') != result.password:
return 'Incorrect Login\Password'
#запилить проверку результата
requesth.set_secure_cookie("user", tornado.escape.xhtml_escape(requesth.get_body_argument('login')))
requesth.set_header('Location', '/admin/')
requesth.set_status(302)
return 'Logged successfully' #checking should be added
def json_answer(requesth):
received_objects = tornado.escape.json_decode(requesth.request.body)
if received_objects['action'] == 'get num of posts during last':
board = received_objects['board']
if board not in initiate.board_cache: #all of this should be redone, it is fucking not good code
return 'error'
from_time = received_objects['from_time']
if not isinstance(from_time, int):
return 'Incorrect time!'
from_time = int(time.time()) - from_time
p_class = initiate.board_cache[board].post_class
return_object = initiate.sess.query(p_class).filter(p_class.post_time >= from_time).count()
return tornado.escape.json_encode(return_object)
elif received_objects['action'] == 'remove ban by id':
ban_id = received_objects['id']
if not isinstance(ban_id, int):
return 'Incorrect id'
removed = initiate.sess.query(initiate.Ban).filter(initiate.Ban.id == ban_id).delete(synchronize_session='fetch')
initiate.sess.commit()
if removed > 0:
return 'Succesfully removed ban'
else:
return 'No such ban existed'
else:
return 'incorrect action'
def admin_post(requesth):
if requesth.current_user is None:
requesth.set_header('Location', '/admin/login')
requesth.set_status(302)
return 'Redirecting to login'
else:
try:
content_type = requesth.request.headers['Content-Type']
except KeyError:
pass
else:
if 'application/json' in content_type:
return json_answer(requesth)#here we work we json requests
action = requesth.get_body_argument('action')
if action == 'login':#what we do to login
return 'TO DO'
elif action == 'create':#here it goes when we create smth
instance = requesth.get_body_argument('instance')
if instance == 'board': #we create the board here
#to do the board creation
match = re.match('[a-z0-9]+', requesth.get_body_argument('address'))
if match is None or match.group() != requesth.get_body_argument('address'):
return 'Incorrect address'
match = re.match('[a-z0-9]+', requesth.get_body_argument('tablename'))
if match is None or match.group() != requesth.get_body_argument('tablename'):
return 'Incorrect tablename'
try:
picsnum = int(requesth.get_body_argument('picsnum'))
if picsnum < 0 or picsnum > 10: #should add limit from config
return 'Incorrect pictures number!'
except ValueError:
return 'Incorrect pictures number!'
try:
bumplimit = int(requesth.get_body_argument('bumplimit'))
if bumplimit < 0: #should add limit from config
return 'Incorrect bumplimit!'
except ValueError:
return 'Incorrect bumplimit!'
try:
maxthreads = int(requesth.get_body_argument('maxthreads'))
if maxthreads < -1: #should add limit from config
return 'Incorrect maximum number of threads!'
except ValueError:
return 'Incorrect maximum number of threads!'
bool_settings = 0
try:
if requesth.get_body_argument('delposts') == '1':
#bool_settings = other_settings | 1
bool_settings = bool_settings | 1
except tornado.web.MissingArgumentError:
pass
try:
if requesth.get_body_argument('delthreads') == '1':
#bool_settings = other_settings | 2
bool_settings = bool_settings | 2
except tornado.web.MissingArgumentError:
pass
board_list = initiate.sess.query(initiate.Board).filter(initiate.Board.address==requesth.get_body_argument('address')).all()
if board_list: #need to add the checking of 'forbidden pages'
return 'board with such address exists!'
board_list = initiate.sess.query(initiate.Board).filter(initiate.Board.tablename==requesth.get_body_argument('tablename')).all()
if board_list or requesth.get_body_argument('tablename') in initiate.engine.table_names():
return 'table with such name exists!'
#we checked, now we should add this to board cache, create table and write down it to database
new_board = initiate.Board(address = requesth.get_body_argument('address'),
tablename = requesth.get_body_argument('tablename'),
name = requesth.get_body_argument('name'),
fullname = requesth.get_body_argument('fullname'),
description = requesth.get_body_argument('description'),
pictures = picsnum,
bumplimit = bumplimit,
maxthreads = maxthreads,
bool_settings = bool_settings) #creating new board in Boards table
try:
os.makedirs(os.path.join('content', new_board.address, 'img'))
os.makedirs(os.path.join('content', new_board.address, 'thumbs'))
except OSError:
return 'Failed to create folders'
initiate.sess.add(new_board)
initiate.board_cache[requesth.get_body_argument('address')] = initiate.board_cache_class(new_board, table_exists = False)
#initiate.board_cache[requesth.get_body_argument('address')] = (requesth.get_body_argument('tablename'), requesth.get_body_argument('name'), requesth.get_body_argument('fullname'), requesth.get_body_argument('description'), type(requesth.get_body_argument('description'), (initiate.Post,initiate.Base), {'__tablename__':requesth.get_body_argument('tablename')}))#add to boardcache and creating the table class
initiate.board_cache[requesth.get_body_argument('address')].post_class.__table__.create(bind = initiate.engine)#creating table
initiate.sess.commit()#committing changes to boards table
initiate.renew_board_cache(renew_cache_dict=False) #here we fuck with the board cache again
return 'created board successfully<br><a href = "/'+new_board.address+'">'+new_board.address+'</a>' #add redirection
else:
requesth.write_error(400)#probably should describe the error
#it goes when instance creation is not supported
elif action == 'change':
instance = requesth.get_body_argument('instance')
if instance == 'password': #we create the board here
if requesth.get_body_argument('new_passwd') == requesth.get_body_argument('new_passwd_again'):
user = initiate.sess.query(initiate.Admin).filter(initiate.Admin.login == requesth.current_user).first()
if user.password != requesth.get_body_argument('old_passwd'):
return 'Incorrect old password!'
initiate.sess.query(initiate.Admin).filter(initiate.Admin.login == requesth.current_user).update({initiate.Admin.password : requesth.get_body_argument('new_passwd')})
initiate.sess.commit()
return 'Password changed successfully<br><a href = "/admin">return</a>'
else:
return 'New password is entered incorrect'
else:
requesth.write_error(400)#probably should describe the error
else:
requesth.write_error(400)#probably should describe the error
#it goes when action is not supported
return 'TO DO'
if __name__ == '__main__':
print(admin(''))