def test_http_host(): environ = { 'tiddlyweb.config': config, } url = server_host_url(environ) assert url == 'http://0.0.0.0:8080' environ['HTTP_HOST'] = 'fancy.virtual.domain:9090' environ['wsgi.url_scheme'] = 'https' url = server_host_url(environ) assert url == 'https://fancy.virtual.domain:9090'
def _validate_and_redirect(self, environ, start_response, username, password, redirect): """ Check a username and password. If valid, send a cookie to the client. If it is not, send the form again. """ status = '401 Unauthorized' try: store = environ['tiddlyweb.store'] secret = environ['tiddlyweb.config']['secret'] user = User(username) store.get(user) if user.check_password(password): uri = '%s%s' % (server_host_url(environ), redirect) import re uri = re.sub("/recipes/portal(-.*)?/", "/recipes/portal-"+username+"/", uri) # uri = uri.replace("/recipes/portal/", # print "USERNAME" + username # print "URI" + uri cookie = Cookie.SimpleCookie() secret_string = sha('%s%s' % (user.usersign, secret)).hexdigest() cookie['tiddlyweb_user'] = '******' % (user.usersign, secret_string) cookie['tiddlyweb_user']['path'] = '/' start_response('303 See Other', [ ('Set-Cookie', cookie.output(header='')), ('Location', uri) ]) return [uri] except KeyError: pass except NoUserError: pass return self._send_cookie_form(environ, start_response, redirect, status, 'User or Password no good')
def _validate_and_redirect(self, environ, start_response, username, password, redirect): """ Check a username and password. If valid, send a cookie to the client. If it is not, send the form again. """ status = "401 Unauthorized" try: store = environ["tiddlyweb.store"] secret = environ["tiddlyweb.config"]["secret"] user = User(username) user = store.get(user) if user.check_password(password): uri = "%s%s" % (server_host_url(environ), redirect) cookie = Cookie.SimpleCookie() secret_string = sha("%s%s" % (user.usersign, secret)).hexdigest() cookie["tiddlyweb_user"] = "******" % (user.usersign, secret_string) cookie["tiddlyweb_user"]["path"] = self._cookie_path(environ) logging.debug("303 to %s" % uri) start_response("303 Other", [("Set-Cookie", cookie.output(header="")), ("Location", uri)]) return [uri] except KeyError: pass except NoUserError: pass return self._send_cookie_form(environ, start_response, redirect, status, "User or Password no good")
def _validate_and_redirect(self, environ, start_response, username, password, redirect): """ Check a username and password. If valid, send a cookie to the client. If it is not, send the form again. """ status = '401 Unauthorized' try: store = environ['tiddlyweb.store'] secret = environ['tiddlyweb.config']['secret'] cookie_age = environ['tiddlyweb.config'].get('cookie_age', None) user = User(username) user = store.get(user) if user.check_password(password): uri = '%s%s' % (server_host_url(environ), redirect) cookie_header_string = make_cookie('tiddlyweb_user', user.usersign, mac_key=secret, path=self._cookie_path(environ), expires=cookie_age) logging.debug('303 to %s', uri) start_response('303 Other', [('Set-Cookie', cookie_header_string), ('Content-Type', 'text/plain'), ('Location', uri.encode('utf-8'))]) return [uri] except KeyError: pass except NoUserError: pass return self._send_cookie_form(environ, start_response, redirect, status, 'User or Password no good')
def _validate_and_redirect(self, environ, start_response, username, password, redirect): """ Check a username and password. If valid, send a cookie to the client. If it is not, send the form again. """ status = "401 Unauthorized" try: store = environ["tiddlyweb.store"] secret = environ["tiddlyweb.config"]["secret"] cookie_age = environ["tiddlyweb.config"].get("cookie_age", None) user = User(username) user = store.get(user) if user.check_password(password): uri = "%s%s" % (server_host_url(environ), redirect) cookie_header_string = make_cookie( "tiddlyweb_user", user.usersign, mac_key=secret, path=self._cookie_path(environ), expires=cookie_age ) logging.debug("303 to %s", uri) start_response("303 Other", [("Set-Cookie", cookie_header_string), ("Location", uri.encode("utf-8"))]) return [uri] except KeyError: pass except NoUserError: pass return self._send_cookie_form(environ, start_response, redirect, status, "User or Password no good")
def _validate_and_redirect(self, environ, start_response, username, password, redirect): """ Check a username and password. If valid, send a cookie to the client. If it is not, send the form again. """ status = '401 Unauthorized' try: store = environ['tiddlyweb.store'] secret = environ['tiddlyweb.config']['secret'] cookie_age = environ['tiddlyweb.config'].get('cookie_age', None) user = User(username) user = store.get(user) if user.check_password(password): uri = '%s%s' % (server_host_url(environ), redirect) cookie_header_string = make_cookie( 'tiddlyweb_user', user.usersign, mac_key=secret, path=self._cookie_path(environ), expires=cookie_age) logging.debug('303 to %s', uri) start_response('303 Other', [('Set-Cookie', cookie_header_string), ('Content-Type', 'text/plain'), ('Location', uri.encode('utf-8'))]) return [uri] except KeyError: pass except NoUserError: pass return self._send_cookie_form(environ, start_response, redirect, status, 'User or Password no good')
def _success(self, environ, start_response, info): """ After successful validation of an openid generate and send a cookie with the value of that openid. If this is a normal auth scenario make the name of the cookie the normal 'tiddlyweb_user'. If this is auth addition, where a fragment of 'auth:OpenID' is set on the redirect uri, then name the cookie 'tiddlyweb_secondary_user'. """ usersign = info.getDisplayIdentifier() if info.endpoint.canonicalID: usersign = info.endpoint.canonicalID # canonicolize usersign to tiddlyweb form if usersign.startswith('http'): usersign = usersign.split('://', 1)[1] usersign = usersign.rstrip('/') redirect = environ['tiddlyweb.query'].get('tiddlyweb_redirect', ['/'])[0] uri = urlparse.urljoin(server_host_url(environ), redirect) cookie_age = environ['tiddlyweb.config'].get('cookie_age', None) secondary_cookie_only = False try: fragment = uri.rsplit('#', 1)[1] except (ValueError, IndexError): pass else: openid = fragment[len(FRAGMENT_PREFIX):] uri = uri.replace(FRAGMENT_PREFIX + openid, FRAGMENT_PREFIX + usersign) secondary_cookie_only = True secret = environ['tiddlyweb.config']['secret'] secondary_cookie_header_string = make_cookie( 'tiddlyweb_secondary_user', usersign, mac_key=secret, path=self._cookie_path(environ), expires=cookie_age, domain=self._domain_path(environ)) headers = [('Location', uri.encode('utf-8')), ('Content-Type', 'text/plain'), ('Set-Cookie', secondary_cookie_header_string)] if not secondary_cookie_only: cookie_header_string = make_cookie('tiddlyweb_user', usersign, mac_key=secret, path=self._cookie_path(environ), expires=cookie_age) headers.append(('Set-Cookie', cookie_header_string)) start_response('303 See Other', headers) return [uri]
def challenge_post(self, environ, start_response): """ Respond to a POST by processing data sent from a form. Attempts to bind to the LDAP interface with the user credentials extracted from the form. If this succeeds then the user is redirected to the target URI (default '/'). If the authentication fails then the form is re-sent with the appropriate error message. """ ldap_config = environ['tiddlyweb.config'].get('ldapauth', {}) ldap_host = ldap_config.get('ldap_host', '127.0.0.1') ldap_port = ldap_config.get('ldap_port', '389') ldap_base_dn = ldap_config.get('ldap_base_dn', 'dc=localhost') ldap_instance = ldap.initialize('ldap://%s:%s' % (ldap_host, ldap_port)) tiddlyspace_mode = ldap_config.get('ldap_tiddlyspace_mode', False) # Get the required data from the posted form query = environ['tiddlyweb.query'] user = query['user'][0] password = query['password'][0] redirect = query.get('tiddlyweb_redirect', ['/'])[0] try: # Attempt to authenticate the user.I # If no exception is raised then the user is authenticated. ldap_instance.simple_bind_s('cn=%s,%s' % (user, ldap_base_dn), password) LOGGER.info("user %s successfully authenticated" % user) status = '303 See Other' uri = '%s%s' % (server_host_url(environ), redirect) cookie = self._make_cookie(environ, user) # Redirect the user to the target URI now that they are authenticated. start_response(status, [('Content-Type', 'text/plain'), ('Set-Cookie', cookie), ('Location', uri.encode('utf-8'))]) return [uri] except ldap.INVALID_CREDENTIALS: LOGGER.warn("user %s failed authentication" % user) return self._send_login_form( start_response, error_message='Invalid user credentials, please try again', redirect=redirect, tiddlyspace_mode=tiddlyspace_mode) except ldap.SERVER_DOWN: LOGGER.error("could not establish connection with LDAP server") return self._send_login_form( start_response, '504 Gateway Timeout', error_message= 'Unable to reach authorization provider, please contact your administrator', redirect=redirect, tiddlyspace_mode=tiddlyspace_mode)
def _success(self, environ, start_response, info): """ After successful validation of an openid generate and send a cookie with the value of that openid. If this is a normal auth scenario make the name of the cookie the normal 'tiddlyweb_user'. If this is auth addition, where a fragment of 'auth:OpenID' is set on the redirect uri, then name the cookie 'tiddlyweb_secondary_user'. """ usersign = info.getDisplayIdentifier() if info.endpoint.canonicalID: usersign = info.endpoint.canonicalID # canonicolize usersign to tiddlyweb form if usersign.startswith('http'): usersign = usersign.split('://', 1)[1] usersign = usersign.rstrip('/') redirect = environ['tiddlyweb.query'].get( 'tiddlyweb_redirect', ['/'])[0] uri = urlparse.urljoin(server_host_url(environ), redirect) cookie_age = environ['tiddlyweb.config'].get('cookie_age', None) secondary_cookie_only = False try: fragment = uri.rsplit('#', 1)[1] except (ValueError, IndexError): pass else: openid = fragment[len(FRAGMENT_PREFIX):] uri = uri.replace(FRAGMENT_PREFIX + openid, FRAGMENT_PREFIX + usersign) secondary_cookie_only = True secret = environ['tiddlyweb.config']['secret'] secondary_cookie_header_string = make_cookie( 'tiddlyweb_secondary_user', usersign, mac_key=secret, path=self._cookie_path(environ), expires=cookie_age, domain=self._domain_path(environ)) headers = [('Location', uri.encode('utf-8')), ('Content-Type', 'text/plain'), ('Set-Cookie', secondary_cookie_header_string)] if not secondary_cookie_only: cookie_header_string = make_cookie('tiddlyweb_user', usersign, mac_key=secret, path=self._cookie_path(environ), expires=cookie_age) headers.append(('Set-Cookie', cookie_header_string)) start_response('303 See Other', headers) return [uri]
def challenge_post(self, environ, start_response): """ Respond to a POST by processing data sent from a form. Attempts to bind to the LDAP interface with the user credentials extracted from the form. If this succeeds then the user is redirected to the target URI (default '/'). If the authentication fails then the form is re-sent with the appropriate error message. """ ldap_config = environ['tiddlyweb.config'].get('ldapauth', {}) ldap_host = ldap_config.get('ldap_host', '127.0.0.1') ldap_port = ldap_config.get('ldap_port', '389') ldap_base_dn = ldap_config.get('ldap_base_dn', 'dc=localhost') ldap_instance = ldap.initialize('ldap://%s:%s' % (ldap_host, ldap_port)) tiddlyspace_mode = ldap_config.get('ldap_tiddlyspace_mode', False) # Get the required data from the posted form query = environ['tiddlyweb.query'] user = query['user'][0] password = query['password'][0] redirect = query.get('tiddlyweb_redirect', ['/'])[0] try: # Attempt to authenticate the user.I # If no exception is raised then the user is authenticated. ldap_instance.simple_bind_s('cn=%s,%s' % (user, ldap_base_dn), password) LOGGER.info("user %s successfully authenticated" % user) status = '303 See Other' uri = '%s%s' % (server_host_url(environ), redirect) cookie = self._make_cookie(environ, user) # Redirect the user to the target URI now that they are authenticated. start_response(status, [('Content-Type', 'text/plain'), ('Set-Cookie', cookie), ('Location', uri.encode('utf-8'))]) return [uri] except ldap.INVALID_CREDENTIALS: LOGGER.warn("user %s failed authentication" % user) return self._send_login_form(start_response, error_message='Invalid user credentials, please try again', redirect=redirect, tiddlyspace_mode=tiddlyspace_mode) except ldap.SERVER_DOWN: LOGGER.error("could not establish connection with LDAP server") return self._send_login_form(start_response, '504 Gateway Timeout', error_message= 'Unable to reach authorization provider, please contact your administrator', redirect=redirect, tiddlyspace_mode=tiddlyspace_mode)
def _respond_success(self, parsed_return_to, redirect, environ, start_response): """ If the openid server validates our key checking, then set the cookie and redirect the user. """ usersign = parsed_return_to['usersign'][0] if 'http' in usersign: usersign = usersign.split('://', 1)[1] uri = '%s%s' % (server_host_url(environ), redirect) secret = environ['tiddlyweb.config']['secret'] cookie_age = environ['tiddlyweb.config'].get('cookie_age', None) cookie_header_string = make_cookie('tiddlyweb_user', usersign, mac_key=secret, path=self._cookie_path(environ), expires=cookie_age) logging.debug('303 to %s', uri) start_response('303 See Other', [('Location', uri.encode('utf-8')), ('Set-Cookie', cookie_header_string)]) return [uri]
def _send_cookie(environ, start_response, user): """ We are authentic and a user exists, so install a cookie. """ query = environ['tiddlyweb.query'] tiddlyweb_redirect = query.get('tiddlyweb_redirect', [None])[0] config = environ['tiddlyweb.config'] if not tiddlyweb_redirect: tiddlyweb_redirect = config.get('logged_in_redirect', '/') redirect_uri = '%s%s' % (server_host_url(environ), tiddlyweb_redirect) secret = config['secret'] cookie_age = config.get('cookie_age', None) cookie_header_string = make_cookie('tiddlyweb_user', user.usersign, mac_key=secret, path='/', expires=cookie_age) start_response('303 See Other', [('Set-Cookie', cookie_header_string), ('Content-Type', 'text/plain'), ('Location', str(redirect_uri))]) return [redirect_uri]
def _respond_success(self, parsed_return_to, redirect, environ, start_response): """ If the openid server validates our key checking, then set the cookie and redirect the user. """ usersign = parsed_return_to['usersign'][0] if 'http' in usersign: usersign = usersign.split('://', 2)[1] uri = '%s%s' % (web.server_host_url(environ), redirect) cookie = Cookie.SimpleCookie() secret = environ['tiddlyweb.config']['secret'] secret_string = sha('%s%s' % (usersign, secret)).hexdigest() cookie['tiddlyweb_user'] = '******' % (usersign, secret_string) cookie['tiddlyweb_user']['path'] = self._cookie_path(environ) logging.debug('303 to %s' % uri) start_response('303 Found', [('Set-Cookie', cookie.output(header='')), ('Location', uri)]) return [uri]
def _success(self, environ, start_response, info): usersign = info.getDisplayIdentifier() if info.endpoint.canonicalID: usersign = info.endpoint.canonicalID # canonicolize usersign to tiddlyweb form if usersign.startswith('http'): usersign = usersign.split('://', 1)[1] usersign = usersign.rstrip('/') uri = urlparse.urljoin(server_host_url(environ), environ['tiddlyweb.query'].get('tiddlyweb_redirect', ['/'])[0]) secret = environ['tiddlyweb.config']['secret'] cookie_age = environ['tiddlyweb.config'].get('cookie_age', None) cookie_header_string = make_cookie('tiddlyweb_user', usersign, mac_key=secret, path=self._cookie_path(environ), expires=cookie_age) start_response('303 See Other', [('Location', uri.encode('utf-8')), ('Content-Type', 'text/plain'), ('Set-Cookie', cookie_header_string)]) return [uri]
def _success(self, environ, start_response, info): usersign = info.getDisplayIdentifier() if info.endpoint.canonicalID: usersign = info.endpoint.canonicalID # canonicolize usersign to tiddlyweb form if usersign.startswith('http'): usersign = usersign.split('://', 1)[1] usersign = usersign.rstrip('/') uri = urlparse.urljoin( server_host_url(environ), environ['tiddlyweb.query'].get('tiddlyweb_redirect', ['/'])[0]) secret = environ['tiddlyweb.config']['secret'] cookie_age = environ['tiddlyweb.config'].get('cookie_age', None) cookie_header_string = make_cookie('tiddlyweb_user', usersign, mac_key=secret, path=self._cookie_path(environ), expires=cookie_age) start_response('303 See Other', [('Location', uri.encode('utf-8')), ('Content-Type', 'text/plain'), ('Set-Cookie', cookie_header_string)]) return [uri]
def _validate_and_redirect(self, environ, start_response, username, password, redirect): """ Check a username and password. If valid, send a cookie to the client. If it is not, send the form again. """ status = '401 Unauthorized' try: store = environ['tiddlyweb.store'] secret = environ['tiddlyweb.config']['secret'] cookie_age = environ['tiddlyweb.config'].get('cookie_age', None) user = User(username) user = store.get(user) if user.check_password(password): uri = '%s%s' % (server_host_url(environ), redirect) cookie_header_string = make_cookie('tiddlyweb_user', user.usersign, mac_key=secret, path=self._cookie_path(environ), expires=cookie_age) logging.debug('303 to %s', uri) start_response('303 Other', [('Set-Cookie', cookie_header_string), ('Location', uri.encode('utf-8')), ('Pragma', 'no-cache')]) return [uri] except KeyError: pass except NoUserError: logging.debug('NoUserError for: '+username) template = templating.get_template(environ, 'login_form.html') start_response(status, [ ('Content-Type', 'text/html'), ('Pragma', 'no-cache') ]) return template.render(redirect=redirect, commonVars=templating.common_vars(environ), error=True)
def profile_atom_url(environ, username): """ The atom url of a profile, given a username. """ return (server_host_url(environ) + '/profiles/%s.atom' % encode_name(username))
def profile_atom_url(environ, username): return (server_host_url(environ) + '/profiles/%s.atom' % encode_name(username))
def _host_url(self): return server_host_url(self.environ)