-
Notifications
You must be signed in to change notification settings - Fork 56
/
SimpleHttpsAuthServer.py
66 lines (55 loc) · 1.99 KB
/
SimpleHttpsAuthServer.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
import BaseHTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler
import sys
import os
import base64
import ssl
import SocketServer
key = ""
CERTFILE_PATH = "/root/server.pem"
class AuthHandler(SimpleHTTPRequestHandler):
''' Main class to present webpages and authentication. '''
def do_HEAD(self):
print "send header"
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
def do_AUTHHEAD(self):
print "send header"
self.send_response(401)
self.send_header('WWW-Authenticate', 'Basic realm=\"Test\"')
self.send_header('Content-type', 'text/html')
self.end_headers()
def do_GET(self):
global key
''' Present frontpage with user authentication. '''
if self.headers.getheader('Authorization') == None:
self.do_AUTHHEAD()
self.wfile.write('no auth header received')
pass
elif self.headers.getheader('Authorization') == 'Basic '+key:
SimpleHTTPRequestHandler.do_GET(self)
pass
else:
self.do_AUTHHEAD()
self.wfile.write(self.headers.getheader('Authorization'))
self.wfile.write('not authenticated')
pass
def serve_https(https_port=80, HandlerClass = AuthHandler,
ServerClass = BaseHTTPServer.HTTPServer):
httpd = SocketServer.TCPServer(("", PORT), HandlerClass)
httpd.socket = ssl.wrap_socket (httpd.socket, certfile=CERTFILE_PATH, server_side=True)
sa = httpd.socket.getsockname()
print "Serving HTTP on", sa[0], "port", sa[1], "..."
httpd.serve_forever()
if __name__ == '__main__':
if len(sys.argv)<3:
print "usage SimpleAuthServer.py [port] [username:password]"
sys.exit()
https_port = int(sys.argv[1])
key = base64.b64encode(sys.argv[2])
if len(sys.argv) == 4:
change_dir = sys.argv[3]
print "Changing dir to {cd}".format(cd=change_dir)
os.chdir(change_dir)
serve_https(https_port)