-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathlcserver.py
executable file
·5392 lines (4428 loc) · 183 KB
/
lcserver.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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python3
# vim: set ts=4 sw=4 et :
#
# lcserver.py - LabControl server CGI script
#
# Copyright 2020 Sony
#
# Implementation notes:
# data directory = place where json object files are stored
# files directory = place where file bundles are stored
# pages directory = place where web page templates are stored
#
# The server implements three interfaces:
# 1. the human user interace (web pages showing objects and available
# actions)
# 2. a human user interace showing raw object (files and json contents)
# 3. the computer ReST interface (used for sending, modifying and
# retrieving the data in the store, and for performing REST API actions
# on the objects)
#
# The server currently supports the top-level "pages":
# boards, resources, requests, logs, users
#
# The REST API specified with Timesys uses urls like this:
# /api/v0.2/devices/bbb/power/reboot
# I'm calling this the 'path api'
#
# To do:
# - convert everything over to the path api
# + list devices
# - actions:
# - upload - need to parse multi-part forms
# - queries:
# - handle regex wildcards instead of just start/end wildcards
# - objects:
# - support board registration - put-board
# - support resource registration - put-resource
# - support host registration
# - support user registration
# - requests:
# - security:
# - add otp authentication to all requests
# - check host's otp file for specified key
# - erase key after use
# - add hosts (or users)
# - so we can: 1) save an otp file, 2) validate requests?
# - see also items marked with FIXTHIS
#
import sys
import os
import time
import cgi
import re
import tempfile
#import urllib
import urllib.parse
import uuid
import datetime
# simplejson loads faster than json, use that if available
try:
import simplejson as json
except ImportError:
import json
# import yaml as needed
#import yaml
import copy
import shlex
import subprocess
import signal
import threading # used for Timer objects
debug = False
#debug = True
debug_api_response = False
# uncomment this to dump response data to the log file
#debug_api_response = True
# global used to store messages about reading config
config_msg = ""
# Keep track of which getstatusoutput I'm using
using_commands_gso = False
try:
from subprocess import getstatusoutput
except:
from commands import getstatusoutput
using_commands_gso = True
VERSION=(0,6,5)
SERVER_CONF_FILENAME="/etc/lcserver.conf"
# stub class for storing incoming POST data of type application/json
# This works around a bug in the python cgi module handling this type of
# data.
# see https://github.com/webpy/webpy/issues/574#issuecomment-549070996
# and https://bugs.python.org/issue27777
# Use this instead of cgi.FieldStorage() class
# Right now, the only attributes used are form.value and form.getfirst()
class mycgiform_class:
def __init__(self, data):
self.value = data
def getfirst(self, attr, default=None):
if attr=="action":
return "api"
return default
# define a class for config vars
class config_class:
def __init__(self):
global config_msg
# attempt to auto-detect several config values
if os.path.exists("/usr/lib/cgi-bin/lcserver.py"):
self.url_base = "/cgi-bin/lcserver.py"
else:
self.url_base = "/lcserver.py"
self.url_prefix = "http://localhost/"
self.files_url_base = "/lc-data"
self.lab_name = "mylab"
self.admin_contact_str = "<Please set the admin_contact_str in lcserver.conf>"
# if not defined in lcserver.conf, try finding base_dir automatically
# Precedence of installation locations:
# 2. local lcserver in Fuego container
# 3. test lcserver on Tim's private server machine (birdcloud.org)
# 4. test lcserver on Tim's home desktop machine (timdesk)
self.base_dir = "/home/ubuntu/work/labcontrol/lc-data"
if not os.path.exists(self.base_dir):
self.base_dir = "/usr/local/lib/labcontrol/lc-data"
if not os.path.exists(self.base_dir):
self.base_dir = "/home/tbird/work/labcontrol/lc-data"
self.default_reservation_duration = "forever"
self.default_video_recording_duration = "10"
# #### this is the end of the defaults section ####
# settings after this will not be overridden by the config file
# allow items in the server config file to override default
# or detected values
#config_msg = "reading config file...<br>\n"
if os.path.isfile(SERVER_CONF_FILENAME):
data = open(SERVER_CONF_FILENAME, "r").read()
for line in data.splitlines():
#config_msg += "config line='%s'<br>\n" % line
if not line.strip():
continue
if line.startswith("#"):
continue
if "=" in line:
name, value = line.split("=",1)
config_msg += "setting config %s='%s'<br>\n" % (name, value)
self.__dict__[name] = value
self.data_dir = self.base_dir + "/data"
self.files_dir = self.base_dir + "/files"
self.page_dir = self.base_dir + "/pages"
config_msg += "config='%s'" % self.__dict__
def __getitem__(self, name):
return self.__dict__[name]
# load the configuration data
config = config_class()
# if the file 'debug' exists in the lc-data directory, then
# turn on the debug flag (for extra logging)
if os.path.exists(config.base_dir + "/debug"):
debug = True
RSLT_FAIL="fail"
RSLT_OK="success"
# this is used for debugging only
def log_this(msg):
global config
with open(config.base_dir+"/lcserver.log" ,"a") as f:
f.write("[%s] %s\n" % (get_timestamp(), msg))
def dlog_this(msg):
global debug
global config
if debug:
with open(config.base_dir+"/lcserver.log" ,"a") as f:
f.write("[%s] %s\n" % (get_timestamp(), msg))
# this class has data that can be included on a page
# using %(varname)s. This includes things like login forms,
# search forms, menus, variable data, etc.
#
# items available to use are:
# url_base, page_url, page_name, asctime, timestamp, version
# version, git_commit, git_describe, body_attrs
# login_link (and a bunch more)
class page_data_class:
def __init__(self, req, init_data = {} ):
self.data = init_data
self.req = req
self.cookies = ""
def __getitem__(self, key):
# return value for key
# if the value is callable, return the string returned by calling it
if key in self.data:
item = self.data[key]
elif hasattr(self, key):
item = getattr(self, key)
else:
if "default" in self.data:
item = self.data["default"]
else:
item = self.req.html_error('<missing data value for key "%s">' % key)
if callable(item):
return item()
else:
return item
# this allows for getting arbitrary information for the system
# using an external command
# use with caution: try to prevent something like 'cat /etc/passwd'
# !! never call this with user-provided data !!
# this is for internal use only (e.g. see git_commit)
def external_info(self, cmd, new_dir=None):
saved_cur_dir = os.getcwd()
try:
if new_dir:
os.chdir(new_dir)
status, output = getstatusoutput(cmd)
if status==0:
output
else:
self.req.add_to_message("problem executing command: '%s'" % cmd)
output = "#no data#"
except:
output = "#no data#"
self.req.add_msg_and_traceback('exception in %s' % cmd)
if new_dir:
os.chdir(saved_cur_dir)
return output
def url_base(self):
return self.req.config.url_base
def files_url_base(self):
return self.req.config.files_url_base
def page_url(self):
return self.req.page_url
def page_name(self):
return self.req.page_name
def admin_page_link(self):
if self.req.user.admin:
return 'Click to go to the <a href="%s">Admin</a> page' % \
self.req.make_url("Admin")
else:
return ""
def asctime(self):
return time.asctime()
def timestamp(self):
return get_timestamp()
def version(self):
return "%d.%d.%d" % VERSION
def git_commit(self):
cmd = 'git log -n 1 --format="%h"'
html = self.external_info(cmd, config.base_dir)
return '#' + html.strip()
def git_describe(self):
cmd = 'git describe'
html = self.external_info(cmd, config.base_dir)
return html
def user_name(self):
return self.req.user.name
def user_admin(self):
return str(self.req.user.admin)
def lab_name(self):
return str(self.req.config.lab_name)
def admin_contact_str(self):
return str(self.req.config.admin_contact_str)
# support edit action on a double-click on the page
# FIXTHIS - the 'edit' action for a page is not currently supported
def edit_on_dblclick(self):
html = """ondblclick="location.href='%s?action=edit'" """ % self.req.page_url
return ""
return html
def login_link(self):
if self.req.user.name=="not-logged-in":
html = """<a href="%s?action=login_form">Login</a>""" % (self.req.page_url)
else:
html = """<a href="%s?action=edit_user_user_form">%s</a><br>
<a href="%s?action=logout">Logout</a>""" % \
(self.req.page_url, self.req.user.name, self.req.page_url)
return html
def login_link_nobr(self):
if self.req.user.name=="not-logged-in":
return self.login_link()
else:
html = """<a href="%s?action=edit_user_user_form">%s</a> <a href="%s?action=logout">Logout</a>""" % (self.req.page_url, self.req.user.name, self.req.page_url)
return html
def logout_link(self):
return """<a href="%s?action=logout">Logout</a>""" % \
(self.req.page_url)
def search_form(self):
html = """<FORM METHOD="POST" ACTION="%s?action=search">
<table id=search_table><tr><td align=right>
<INPUT type="text" name="search_string" width=15></input>
</td></tr><tr><td align=right>
<INPUT type="submit" name="search" value="Search"></input>
</td></tr></table></FORM>
""" % self.req.page_url
return html
def search_form_nobr(self):
html = """<FORM METHOD="POST" ACTION="%s?action=search">
<INPUT type="text" name="search_string" width=15></input>
<INPUT type="submit" name="search" value="Search"></input>
</FORM>
""" % self.req.page_url
return html
def message(self):
if self.req.message and not self.req.message_hold:
html = """<table border=1 bgcolor=lightgreen width=100%%>
<tr><td>%s</td></tr>
</table>""" % self.req.message
req.message = ""
else:
html = ""
return html
class user_class:
def __init__(self):
self.name = "not-logged-in"
self.admin = False
class req_class:
def __init__(self, config, form):
self.config = config
self.data = page_data_class(self)
self.header_shown = False
self.footer_shown = False
self.message = ""
self.page_name = ""
self.page_url = "page_name_not_set_error"
self.form = form
self.html = []
self.api_path = ""
self.obj_path = ""
self.user = None
def set_page_name(self, page_name):
page_name = re.sub(" ","_",page_name)
self.page_name = page_name
self.page_url = self.make_url(page_name)
def set_obj_type(self, page_path):
page_path = re.sub(" ","_",page_path)
if page_path and page_path[0] == "/":
page_path = page_path[1:]
if page_path and page_path[-1] == "s":
page_path = page_path[:-1]
self.obj_type = page_path
def page_filename(self):
if not hasattr(self, "page_name"):
raise AttributeError("Missing attribute")
return self.config.page_dir+os.sep+self.page_name
def read_page(self, page_name=""):
if not page_name:
page_filename = self.page_filename()
else:
page_filename = self.config.page_dir+os.sep+page_name
return open(page_filename).read()
def make_url(self, page_name):
page_name = re.sub(" ","_",page_name)
return self.config.url_base+"/"+page_name
def html_escape(self, str, quote=False):
str = re.sub("&","&",str)
str = re.sub("<","<",str)
str = re.sub(">",">",str)
str = re.sub('"',""",str)
str = re.sub("'","'",str)
return str
def add_to_message(self, msg):
self.message += msg + "<br>\n"
def add_msg_and_traceback(self, msg):
self.add_to_message(msg)
import traceback
tb = traceback.format_exc()
self.add_to_message("<pre>\n%s\n</pre>\n" % tb)
def show_message(self):
if self.message:
self.html.append("<h2>lcserver message(s):</h2>")
self.html.append(self.message)
def show_html_header(self, title):
if self.header_shown:
return
# new system
self.header = """Content-type: text/html\n"""
if self.data.cookies:
self.header += self.data.cookies + "\n\n"
else:
self.header += "\n"
# render the header markup
self.html.append(self.header)
self.html.append("""<head>
<meta charset="utf-8">
<title>%s</title>
<style>
body {
padding-top: 5px;
margin-bottom: 100px;
}
html {
position: relative;
min-height: 100%%;
}
table {
border-collapse: collapse;
}
th, td {
border: 1px solid black;
padding: 3px 5px 3px;
}
#navbar{width:100%%;}
.alignleft {
background-color:#0fffff;
width:180px;
vertical-align:middle;
float:left;
}
.alignright {
background-color:#b0ffb0;
vertical-align:middle;
float:right;
}
.center {
/* background-color:#ff0000; */
vertical-align:middle;
width:400px;
margin:0 auto;
}
</style>
</head>
<body>
""" % title)
self.header_shown = True
def show_footer(self):
if self.footer_shown:
return
self.show_message()
ver_str = self.data.version()
self.html.append('<hr>\n<p>\n<div align="center"><font size="-2">LabControl server v. %s</font></div>' % ver_str)
self.html.append("</body>")
self.footer_shown = True
def html_error(self, msg):
return "<font color=red>" + msg + "</font><BR>"
def send_response(self, result, data):
self.html.append("Content-type: text/plain\n\n%s\n" % result)
self.html.append(data)
# API responses: return python dictionary as json data
def send_api_response(self, result, data = {}):
global debug, debug_api_response
data["result"] = result
if result == RSLT_FAIL and debug:
msg = ""
if "message" in data:
msg = ": " + data["message"]
dlog_this("Sending failure response%s" % msg)
json_data = json.dumps(data, sort_keys=True, indent=4,
separators=(',', ': '))
if debug_api_response:
log_this("response json_data=%s" % json_data)
self.html.append("Content-type: text/plain\n\n")
self.html.append(json_data)
def send_api_response_msg(self, result, msg):
self.send_api_response(result, { "message": msg })
def send_api_list_response(self, data):
resp_data = { "result": "success", "data": data }
json_data = json.dumps(resp_data, sort_keys=True, indent=4,
separators=(',', ': '))
self.html.append("Content-type: text/plain\n\n")
self.html.append(json_data)
def get_user(self):
return self.user.name
def set_user(self):
# look up the user using the authorization token and set req.user
# FIXTHIS (low) - should have a reverse index from auth-token to user name
# to speed this up. For now a linear scan of file contents is OK.
self.user = user_class()
# There are two ways to set the token, one via the AUTH_TYPE and
# HTTP_AUTHORIZATION, and the other via HTTP_COOKIE
# either is valid
http_auth = self.environ.get("HTTP_AUTHORIZATION", "")
HTTP_COOKIE = self.environ.get("HTTP_COOKIE", "")
cookie_token = ""
auth_token = ""
auth_type = ""
if "auth_token=" in HTTP_COOKIE:
cookie_token = HTTP_COOKIE.split("auth_token=")[1]
if ";" in cookie_token:
cookie_token = cookie_token.split(";")[0]
if http_auth:
auth_type, auth_token = http_auth.split(" ", 1)
if auth_type != "token":
auth_token=""
# scan user files for matching authentication token
if auth_token == "not-a-valid-token":
log_this("Error: HTTP_AUTHORIZATOIN 'not-a-valid-token'")
return
dlog_this("cookie_token=%s" % cookie_token)
dlog_this("auth_token=%s" % auth_token)
user_dir = self.config.data_dir + "/users"
try:
user_files = os.listdir( user_dir )
except:
log_this("Error: could not read user files from " + user_dir)
return
found_match = False
for ufile in user_files:
upath = user_dir + "/" + ufile
try:
ufd = open(upath)
except:
log_this("Error opening upath %s" % upath)
continue
try:
udata = json.load(ufd)
except:
ufd.close()
log_this("Error reading json data from file %s" % upath)
continue
dlog_this("in get_user: udata= %s" % udata)
utoken = udata.get("auth_token", "not-a-valid-token")
if cookie_token:
if cookie_token == utoken:
found_match = True
break
elif auth_token == utoken:
# only check auth_token if cookie_token is not set
# lc never sets the cookie, only the auth_token
found_match = True
break
if found_match:
try:
self.user.name = udata["name"]
except KeyError:
log_this("Error: missing 'name' field in user data file %s, in req.set_user()" % upath)
admin = udata.get("admin","")
if admin == "True":
self.user.admin = True
else:
self.user.admin = False
dlog_this("in req.set_user: user=%s" % str(self.user.name))
def show_live_stream(self, cam_map):
try:
url = cam_map["live_stream_url"]
self.html.append("Content-type: text/html\n")
self.html.append('<a href="%s">live_stream</a>' % url)
self.html.append('<br>')
except KeyError:
self.html.append("Content-type: text/html\n")
self.html.append("Error: missing 'live_stream_url' in resource")
self.html.append('<br>')
# end of req_class
#######################
# response objects are dictionaries with the following schema:
# { "result" : "success" (RSLT_OK),
# "data" : <command-specific> }
# { "result" : "fail",
# "message": "reason for failure" }
def show_env(req, env, full=0):
env_keys = list(env.keys())
env_keys.sort()
env_filter=["PATH_INFO", "QUERY_STRING", "REQUEST_METHOD", "SCRIPT_NAME"]
req.html.append("Here is the environment:")
req.html.append("<ul>")
for key in env_keys:
if full or key in env_filter:
req.html.append("<li>%s=%s" % (key, env[key]))
req.html.append("</ul>")
CGI_VARS=["CONTENT_TYPE", "CONTENT_LENGTH", "DOCUMENT_ROOT",
"HTTP_COOKIE", "HTTP_HOST", "HTTP_REFERER", "HTTP_USER_AGENT",
"AUTH_TYPE", "HTTP_AUTHORIZATION",
"HTTPS", "PATH", "QUERY_STRING", "REMOTE_ADDR",
"REMOTE_HOST", "REMOTE_PORT", "REMOTE_USER", "REQUEST_METHOD",
"REQUEST_URI", "SCRIPT_FILENAME", "SCRIPT_NAME", "SERVER_ADMIN",
"SERVER_NAME", "SERVER_PORT", "SERVER_SOFTWARE"]
def show_header(req, title):
if req.header_shown:
req.html.append("<h1>" + title + "</h1>")
return
req.show_html_header(title)
# show global navigation bar (including login)
## start navbar div
req.html.append('<div id="navbar" height="100px" width="100%%">')
# put login link, with float attribute to right, first
req.html.append("""<div class="alignleft"><font size="6"><b>
<a href="%(url_base)s">[LC - logo]</b></font></a> """ % req.config)
req.html.append('</div>')
# show object menus
req.html.append("""<div class="alignright">%(login_link_nobr)s</div>""" % req.data)
req.html.append('<div class="center">')
req.html.append('<a href="%(url_base)s/boards">Boards</a> ' % req.config)
req.html.append('<a href="%(url_base)s/resources">Resources</a> ' % req.config)
req.html.append('<a href="%(url_base)s/users">Users</a> ' % req.config)
req.html.append('<a href="%(url_base)s/requests">Requests</a> ' % req.config)
req.html.append('<a href="%(url_base)s/logs">Logs</a> ' % req.config)
req.html.append("</div>")
# close navbar
req.html.append('</div style="clear: both;">')
# show page title / page trail
req.html.append('<h2 id="page_title">%s</h2><hr>' % title)
def log_env(req, varnames=[]):
env_keys = list(req.environ.keys())
if varnames:
env_keys = [item for item in env_keys if item in varnames]
env_keys.sort()
log_this("Here is the environment:")
for key in env_keys:
log_this("%s=%s" % (key, req.environ[key]))
def do_login_form(req):
# show user login form
show_header(req, "LabControl User login")
req.html.append("""<FORM METHOD="POST" ACTION="%s?action=login">
<table id=loginform><tr><td>
Name:</td><td align="right"><INPUT type="text" name="name" width=15></input></td></tr>
<tr><td>Password:</td><td align="right"><INPUT type="password" name="password" width=15></input>
</td></tr><tr><td> </td><td align="right">
<INPUT type="submit" name="login" value="Login"></input>
</td></tr></table></FORM>""" % req.page_url)
req.html.append("""<br>Please contact %s if you want to create an account""" % req.config.admin_contact_str)
req.html.append("</td></tr></table>")
def do_login(req):
# process user login
name = req.form.getfirst("name", "")
password = req.form.getfirst("password")
#req.add_to_message("processing login form: name=%s<br>" % name)
# check user name and password
token, reason = authenticate_user(req, name, password)
# set cookie expiration (to about 1 week - in seconds)
# FIXTHIS - have authentication cookies last a configured amount of time
max_age = 604800
cookies = "auth_token=0;"
html = ""
if token:
html += '<H1 align="center">You successfully logged in!</H1><p>\n'
html += 'Click to return to <a href="%s">%s</a>' % \
(req.page_url, req.page_name)
cookies = "auth_token=%s; Max-Age=%s;" % (token, max_age)
else:
html += req.html_error("Invalid login: account or password did not match")
# send cookies back to user
req.data.cookies = "Set-Cookie: %s" % cookies
# process user login
show_header(req, "LabControl User login")
req.html.append(html)
def do_logout(req):
html = '<h1 align="center">You have been logged out</h1>\n'
html += 'Click here to return to <a href="%s/Main">Main</a>' % req.config.url_base
cookies = "auth_token=0; expires=Thu, Jan 01 1970 00:00:00 UTC;"
# send cookies back to user
req.data.cookies = "Set-Cookie: %s" % cookies
show_header(req, "LabControl User Account logout")
req.html.append(html)
return
################################################################
# user management
def do_manage_users(req):
# show a list of users, with edit and remove buttons
# also show a link for adding a user
users = get_object_list(req, "user")
show_header(req, "Manage users")
req.html.append("""Manage LabControl user accounts using the table below.<p>""")
# show a list of users, with edit and remove buttons
req.html.append('<table class="users_table">\n<tr>\n')
req.html.append(' <th>Name</th><th>Is Admin?</th><th>Action:</th></tr>\n')
for user in users:
umap = get_object_map(req, "user", user)
edit_link = req.config.url_base + "/Admin?action=edit_user_admin_form&user=" + user
remove_link = req.config.url_base + "/Admin?action=remove_user_confirm&user=" + user
view_link = req.config.url_base + "/Admin?action=view_user_config&user=" + user
req.html.append('<tr><td valign="top" align="center"><b>%s</b></td>\n' % user)
admin = umap.get("admin", "False")
if admin == "True":
admin_str = "yes"
else:
admin_str = ""
req.html.append(' <td valign="top" align="center"><b>%s</b></td>\n' % admin_str)
req.html.append(' <td valign="top"><a href="%s">View</a> | <a href="%s">Edit</a> | <a href="%s">Remove</a></td>\n' % (view_link, edit_link, remove_link))
req.html.append("</tr>\n")
req.html.append("</table>")
req.html.append('<p>Or, you can: <a href="%s?action=add_user_form">Add a User</a>' % req.page_url)
req.html.append('<p><hr><p>Click to return to <a href="%s">%s</a> page' % \
(req.page_url, req.page_name))
req.show_footer()
return
def do_view_user_config(req):
show_header(req, "View User Config")
manage_url = "%s?action=manage_users" % req.page_url
err_close_msg = "<p>Could not view user account.\n<p>" + \
'Click to return to <a href="%s">Manage Users</a> page' % \
manage_url
user = req.form.getfirst("user", "")
if not user:
msg = "Error: Missing user"
req.html.append(req.html_error(msg))
req.html.append(err_close_msg)
return
umap = get_object_map(req, "user", user)
admin = umap.get("admin", "False")
if admin == "True":
admin_str = "yes"
else:
admin_str = "no"
auth_token = umap.get("auth_token", "<missing>")
edit_link = req.config.url_base + "/Admin?action=edit_user_admin_form&user=" + user
remove_link = req.config.url_base + "/Admin?action=remove_user_confirm&user=" + user
# show user account data
req.html.append("Account data for user '<b>%s</b>'" % user)
req.html.append('<table class="users_table">')
req.html.append("""
<tr><td>Name</td><td>%s</td></tr>
<tr><td>Password</td><td>XXXXXXXX</td></tr>
<tr><td>Is Admin</td><td>%s</td></tr>
<tr><td>Auth Token</td><td>%s</td></tr>
</table>
""" % (user, admin_str, auth_token))
req.html.append('<p><a href="%s">Edit User account</a> | <a href="%s">Remove this User account</a>\n' % (edit_link, remove_link))
req.html.append('<p><hr><p>Click to return to <a href="%s">Manage Users</a> page' % manage_url)
return
# The user is not allowed to edit everything the admin can edit
# and the info on a 'create' form is different than the info on
# an 'edit' form. This makes this routine a bit tricky.
def user_form(req, action, umap, user_is_self=False):
html = """<FORM METHOD="POST" ACTION="%s?action=%s">
<table id=create_user_form>
""" % (req.page_url, action)
if action == "add_user":
html += """<tr><td>Name:</td><td><INPUT type="text" name="name" width=30></input></td></tr>"""
button_label = "Create User Account"
else:
name = umap["name"]
html += """<tr><td>Name:</td><td><b>%s</b>
<INPUT type="hidden" name="name" value="%s"></input>
</td></tr>\n""" % (name, name)
button_label = "Update User Account"
admin = umap.get("admin", "False")
if admin == "True":
admin_str = "checked"
else:
admin_str = ""
auth_token = umap.get("auth_token", "")
html += """<tr><td>Password:</td><td>
<INPUT type="password" name="password" width=30></input>
</td></tr>
<tr><td>Password (repeat):</td><td>
<INPUT type="password" name="password2" width=30></input>
</td></tr>"""
if user_is_self:
# user can't change their own admin status
html += "<tr><td>Is Admin?</td><td>%s</td></tr>" % admin
else:
html += """
<tr><td>Is Admin?</td><td>
<INPUT type="checkbox" name="admin" value="True" %s></input>
</td></tr>""" % admin_str
# On create, an auth_token is generated by do_add_user()
# so, it's not displayed on the 'create' form
if action == "update_user":
if user_is_self:
# The user can't update the token themselves, but can see it.
html += """<tr><td>Auth Token:</td><td>%s</td></tr>""" % auth_token
else:
# an administrator can edit it
html += """<tr><td>Auth Token:</td><td align="right">
<INPUT type="text" name="auth_token" value="%s" width=60></input>
</td></tr>\n""" % auth_token
html += """
<tr><td> </td>
<td> <INPUT type="submit" value="%s"></input>
<a href="%s">Cancel</a></input></td></tr>
</table></FORM>""" % (button_label, req.page_url)
return html
def do_add_user_form(req):
# show create user login form
show_header(req, "Create LabControl User Account")
req.html.append("""Please enter the data for the new user.
<p>Note: Names may only include letters, numbers, and the following
characters: '_', '-', '.', '@'
<p>
""")
umap = { "name": "" }
req.html.append(user_form(req, "add_user", umap))
req.html.append('<p>Click to return to <a href="%s/Admin">Admin</a> page.' %
(req.page_url))
def do_edit_user_admin_form(req):
# show user edit form
show_header(req, "LabControl User Account edit")
name = req.form.getfirst("user", "")
if not name:
msg = "Error: missing user name"
log_this(msg)
req.html.append(req.html_error(req.html_escape(msg)))
req.html.append(err_msg)
return
req.html.append("""Edit the user by editing the fields below.<br>
If the password fields are left blank, the password is not changed.<br>
To generate a new random Auth Token, put the word 'new' in the input
field.""")
umap = get_object_map(req, "user", name)
req.html.append(user_form(req, "update_user", umap, False))
req.html.append('<p><hr>Click to return to <a href="%s?action=manage_users">Manage Users</a> page' % req.page_url)
req.html.append('<p>Return to <a href="%s/Admin">Admin</a> page.' %
(req.page_url))
def do_edit_user_user_form(req):
# show user edit form
# this can only be used for changing a user's own attributes
show_header(req, "LabControl User Account edit")
req.html.append("""Edit the user by editing the fields below.<br>
If the password fields are left blank,
the password is not changed.""")
name = req.user.name
umap = get_object_map(req, "user", name)
req.html.append(user_form(req, "update_user", umap, True))
req.html.append('<p><hr>Return to <a href="%s">%s</a> page.' %
(req.page_url, req.page_name))
def do_add_user(req):
show_header(req, "LabControl Create User")
manage_url = "%s?action=manage_users" % req.page_url
err_close_msg = "<p>Could not create user.\n<p>" + \
'Go "Back" to return to the "add user" form<br>' \
'Or click to return to <a href="%s">Manage Users</a> page' % \
manage_url
# process create user action
name = req.form.getfirst("name", "")
password = req.form.getfirst("password", "not-provided")
password2 = req.form.getfirst("password2", "not-provided2")
admin = req.form.getfirst("admin", "False")
dlog_this("name=%s" % name)
dlog_this("admin=%s" % admin)
# check user name and password
# see if user name has weird chars
still_ok = True