-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathadmin_webinterface.py
executable file
·276 lines (210 loc) · 9.17 KB
/
admin_webinterface.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
#!/usr/bin/python
from cgi import parse_qs, escape
import re
import sys
import os
import datetime, time
import json
if os.path.dirname(__file__) != '':
sys.path.append(os.path.dirname(__file__))
os.chdir(os.path.dirname(__file__))
from config import *
from ldaputils import *
html_header = \
"""<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<style type="text/css">
.pageinput{ width:3em }
</style>
</head>
<body>
"""
html_footer = \
"""
</body>
</html>
"""
# TODO: Remove user_interface once physdash is the default method for retrieving printing quota
# via the getquota API
def user_interface(env, start_response):
setup_testing_defaults(env)
try:
request_body_size = int( env.get( 'CONTENT_LENGTH', 0 ) )
except ValueError:
request_body_size = 0
request_body = env['QUERY_STRING']
d = parse_qs( request_body )
username = escape( d.get( 'username', [''] )[0] )
pagecount, pagequota = ('', '')
current_time = datetime.datetime.now()
first_of_next_month = datetime.datetime(current_time.year +current_time.month//12, (current_time.month+1) if current_time.month < 12 else 1, 1, 0, 0, 0, 0)
lastupdate, = db_cursor.execute( 'SELECT value FROM config WHERE key="lastupdate";' ).fetchone()
if len( username ) > 0:
try:
pagecount, pagequota, lastjob = db_cursor.execute( 'SELECT pagecount, pagequota, lastjob FROM users WHERE username = ?;', [username] ).fetchone()
no_such_user = False
except:
no_such_user = True
else:
no_such_user = True
status = '200 OK'
headers = [ ('Content-type', 'text/html') ]
start_response( status, headers )
html = []
html.append( html_header )
html.append( """<form method="get">""" )
html.append( """<p>Please input your username to query your leftover page quota.</p>""" )
html.append( """<input type="text" name="username" value="%s"/>""" % (username) )
if (pagecount != '' and pagequota != ''):
if pagecount > pagequota:
html.append( """<p>User <b>%s</b> is <b>%s</b> pages over quota. Printing is therefore <b>disabled</b>.<br />""" % (username, pagecount-pagequota) )
else:
html.append( """<p>User <b>%s</b> has <b>%s</b> pages left. """ % (username, pagequota-pagecount) )
html.append( "The last print job was executed on %s.<br />" % datetime.datetime.fromtimestamp(int(lastjob)).strftime("%Y-%m-%d") )
html.append( "Your quota will be automatically increased by %d pages on %s. " % ( monthly_pagenumber_decrease if int(pagecount)-monthly_pagenumber_decrease>0 else pagecount, first_of_next_month.strftime('%Y-%m-%d')))
html.append( "It was last increased on %s.</p>" % datetime.datetime.fromtimestamp(lastupdate).strftime("%Y-%m-%d") )
elif (no_such_user and len(username) > 0):
html.append( """<p>User <b>%s</b> is not in our system.</p>""" % (username) )
html.append( """</form>""" )
html.append( html_footer )
return html
def getquota(env, start_response):
setup_testing_defaults(env)
try:
request_body_size = int( env.get( 'CONTENT_LENGTH', 0 ) )
except ValueError:
request_body_size = 0
request_body = env['QUERY_STRING']
d = parse_qs( request_body )
username = escape( d.get( 'username', [''] )[0] )
pagecount, pagequota = ('', '')
current_time = datetime.datetime.now()
first_of_next_month = datetime.datetime(current_time.year +current_time.month//12, (current_time.month+1) if current_time.month < 12 else 1, 1, 0, 0, 0, 0)
lastupdate, = db_cursor.execute( 'SELECT value FROM config WHERE key="lastupdate";' ).fetchone()
if len( username ) > 0:
try:
pagecount, pagequota, lastjob = db_cursor.execute( 'SELECT pagecount, pagequota, lastjob FROM users WHERE username = ?;', [username] ).fetchone()
no_such_user = False
except:
no_such_user = True
else:
no_such_user = True
status = '200 OK'
headers = [ ('Content-type', 'application/json'), ('Access-Control-Allow-Origin', '*') ]
start_response( status, headers )
res = {}
if (pagecount != '' and pagequota != ''):
res["pagequota"] = pagequota
res["pagecount"] = pagecount
res["lastjob"] = datetime.datetime.fromtimestamp(int(lastjob)).strftime("%Y-%m-%d")
res["increasecount"] = monthly_pagenumber_decrease if int(pagecount) - monthly_pagenumber_decrease > 0 else pagecount
res["nextincrease"] = first_of_next_month.strftime('%Y-%m-%d')
elif (no_such_user and len(username) > 0):
res["error"] = "USER_NOT_FOUND"
else:
res["error"] = "OTHER"
return json.dumps(res) + '\n'
def admin_interface(env, start_response):
setup_testing_defaults(env)
try:
request_body_size = int( env.get( 'CONTENT_LENGTH', 0 ) )
except ValueError:
request_body_size = 0
request_body = env['wsgi.input'].read( request_body_size )
d = parse_qs( request_body )
username = escape( d.get( 'username', [''] )[0] )
try:
pagecount = int( d.get( 'pagecount', [''] )[0] )
except ValueError:
pagecount = 0
try:
pagequota = int( d.get( 'pagequota', [''] )[0] )
except ValueError:
pagequota = 0
if len( username ) > 0:
db_cursor.execute( 'UPDATE users set pagequota = ?, pagecount = ? WHERE username = ?;', ( pagequota, pagecount, username ) );
db_conn.commit()
if pagequota > pagecount:
enablePrinting(username)
else:
disablePrinting(username)
status = '200 OK'
headers = [ ('Content-type', 'text/html') ]
start_response( status, headers )
html = []
html.append( html_header )
html.append( """<table>""" )
html.append( """<tr><th>User name</th><th>Full name</th><th>Quota used/available</th><th>Last print job</th><th>noprinting member</th></tr>""" )
# Retrieve list of users from LDAP for full names
uid2attribs = get_ldap_userlist()
for entry in db_cursor.execute('SELECT username, pagecount, pagequota, lastjob FROM users ORDER BY username ASC'):
# Make table row red if printing is disabled
if entry[1] > entry[2]:
html.append( """<tr style='background-color: red'>""" )
else:
html.append( """<tr>""" )
# Try to constrcut user's full name from LDAP userlist
fullname = ""
if entry[0] in uid2attribs and "sn" in uid2attribs[entry[0]] and "givenName" in uid2attribs[entry[0]]:
fullname = "%s, %s" % (uid2attribs[entry[0]]["sn"], uid2attribs[entry[0]]["givenName"])
# Username
html.append( """<td>""" )
html.append( str( entry[0] ) )
html.append( """</td>""" )
# Full name
html.append( """<td>""" )
html.append( fullname )
html.append( """</td>""" )
# Quota used / available
html.append( """<td>""" )
html.append( """<form method="post">""" )
html.append( """<input type="text" name="pagecount" value="%s" class="pageinput"> / <input type="text" name="pagequota" value="%s" class="pageinput"> """ % ( str( entry[1] ), str( entry[2] ) ) )
html.append( """<input type="hidden" name="username" value="%s">""" % ( str( entry[0] ) ) )
html.append( """<input type="submit" value="save">""" )
html.append( """</form>""" )
html.append( """</td>""" )
# Last print job
if time.time() - int(entry[3]) < 60*60*12: # printed in the last 12 hours
html.append("""<td style="background-color: green">""")
else:
html.append("""<td>""")
html.append(datetime.datetime.fromtimestamp(int(entry[3])).strftime("%Y-%m-%d %H:%M:%S"))
html.append("""</td>""")
# noprinting group membership
if entry[0] in uid2attribs:
if uid2attribs[entry[0]]["noprinting_member"]:
html.append("""<td align="center" style="background-color: red">yes""")
else:
html.append("""<td align="center" style="background-color: white">no""")
html.append( """</td>""" )
html.append( """</tr>""" )
html.append( """</table>""" )
html.append( html_footer )
return html
def not_found(env, start_response):
start_response('404 NOT FOUND', [('Content-Type', 'text/plain')])
return ['Not Found']
def application(env, start_response):
urls = [
(r'^$', user_interface),
(r'^admin/?$', admin_interface),
(r'^getquota/?$', getquota)
]
path = env.get('PATH_INFO', '').lstrip('/')
for regex, callback in urls:
match = re.search(regex, path)
if match is not None:
env['myapp.url_args'] = match.groups()
return callback(env, start_response)
return not_found(env, start_response)
if __name__ == '__main__':
from wsgiref.simple_server import make_server
from wsgiref.util import setup_testing_defaults
httpd = make_server( '', webinterface_port, application )
print "Serving on port 8000..."
httpd.serve_forever()
else:
def setup_testing_defaults(env):
pass