demonstration of a http-auth for the webif
[enigma2-plugins.git] / webinterface / src / plugin.py
1 from Plugins.Plugin import PluginDescriptor
2
3 sessions = [ ]
4
5 # set DEBUG to True, if twisted should write logoutput to a file.
6 DEBUG = False 
7 DEBUGFILE= "/tmp/twisted.log"
8
9 # Passwordprotection Test
10 # set it only to True, if you have a patched wrapper.py
11 # see http://twistedmatrix.com/trac/ticket/2041
12 # in /usr/lib/python2.4/site-packages/twisted/web2/auth/wrapper.py
13 # The solution is to change this line
14 #       
15 #       return self.authenticate(req), seg[1:]
16 # into this
17 #       return self.authenticate(req), seg
18 PASSWORDPROTECTION = False
19 PASSWORDPROTECTION_pwd = "root"
20 PASSWORDPROTECTION_mode = "md5-sess"; 
21 # twisted supports more than sha ('md5','md5-sess','sha')
22 # but only sha works for me, but IE 
23 # sha, Firefox=ok, Opera=ok, wget=ok, ie=not ok
24 # md5-sess, firefox=not ok, opera=not ok,wget=ok, ie=not ok
25 # md5 same as md5-sess 
26
27 def startWebserver():
28         from twisted.internet import reactor
29         from twisted.web2 import server, channel, static, resource, stream, http_headers, responsecode, http
30         from twisted.python import util
31         import webif
32
33         class ScreenPage(resource.Resource):
34                 def __init__(self, path):
35                         self.path = path
36                         
37                 def render(self, req):
38                         global sessions
39                         if sessions == [ ]:
40                                 return http.Response(200, stream="please wait until enigma has booted")
41
42                         class myProducerStream(stream.ProducerStream):
43                                 closed_callback = None
44
45                                 def close(self):
46                                         if self.closed_callback:
47                                                 self.closed_callback()
48                                         stream.ProducerStream.close(self)
49
50                         s = myProducerStream()
51                         webif.renderPage(s, self.path, req, sessions[0])  # login?
52
53                         return http.Response(stream=s)
54
55                 def locateChild(self, request, segments):
56                         path = '/'.join(["web"] + segments)
57                         if path[-1:] == "/":
58                                 path += "index.html"
59
60                         path += ".xml"
61                         return ScreenPage(path), ()
62
63         class Toplevel(resource.Resource):
64                 addSlash = True
65
66                 def render(self, req):
67                         return http.Response(responsecode.OK, {'Content-type': http_headers.MimeType('text', 'html')},
68                                 stream='Hello! You want go to <a href="/web/">OSD</a> instead.')
69
70                 child_web = ScreenPage("/") # "/web"
71                 child_hdd = static.File("/hdd")
72                 child_webdata = static.File(util.sibpath(__file__, "web-data")) # FIXME: web-data appears as webdata
73
74         if PASSWORDPROTECTION is False:
75                 site = server.Site(Toplevel())
76         else:
77                 from twisted.cred.portal import Portal
78         from twisted.cred import checkers
79         from twisted.web2.auth import digest, basic, wrapper
80         portal = Portal(HTTPAuthRealm())
81         checker = checkers.InMemoryUsernamePasswordDatabaseDontUse(root=PASSWORDPROTECTION_pwd)
82         portal.registerChecker(checker)
83         root = wrapper.HTTPAuthResource(Toplevel(),
84                                         (basic.BasicCredentialFactory('DM7025'),digest.DigestCredentialFactory(PASSWORDPROTECTION_mode,'DM7025')),
85                                         portal, (IHTTPUser,))
86         site = server.Site(root)
87         reactor.listenTCP(80, channel.HTTPFactory(site))
88
89 # start classes for PASSWORDPROTECTION
90 from zope.interface import Interface, implements
91 from twisted.cred import portal
92 class IHTTPUser(Interface):
93     pass
94
95 class HTTPUser(object):
96     implements(IHTTPUser)
97
98 class HTTPAuthRealm(object):
99     implements(portal.IRealm)
100
101     def requestAvatar(self, avatarId, mind, *interfaces):
102         if IHTTPUser in interfaces:
103             return IHTTPUser, HTTPUser()
104
105         raise NotImplementedError("Only IHTTPUser interface is supported")
106 # end  classes for PASSWORDPROTECTION
107
108 def autostart(reason, **kwargs):
109         if "session" in kwargs:
110                 global sessions
111                 sessions.append(kwargs["session"])
112                 return
113
114         if reason == 0:
115                 try:
116                         """
117                          in normal console output, twisted will print only the first Traceback.
118                          is this a bug in twisted or a conflict with enigma2?
119                          with this option enabled, twisted will print all TB to the logfile
120                          use tail -f <file> to view this log
121                         """
122                         if DEBUG:
123                                 from twisted.python.log import startLogging
124                                 print "start twisted logfile, writing to %s" % DEBUGFILE 
125                                 startLogging(open(DEBUGFILE,'w'))
126                         
127                         startWebserver()
128                 except ImportError:
129                         print "twisted not available, not starting web services"
130
131 def Plugins(**kwargs):
132         return PluginDescriptor(where = [PluginDescriptor.WHERE_SESSIONSTART, PluginDescriptor.WHERE_AUTOSTART], fnc = autostart)