def test_cookie_set(): """ test that we get a cookie relating to the space we are in """ store = get_store(config) hostname = "foo.0.0.0.0:8080" user = User(u"f\u00F6o") user.set_password("foobar") store.put(user) user_cookie = get_auth(u"f\u00F6o", "foobar") response, content = http.request( "http://foo.0.0.0.0:8080/", method="GET", headers={"Cookie": 'tiddlyweb_user="******"' % user_cookie} ) assert response["status"] == "200", content time = datetime.utcnow().strftime("%Y%m%d%H") cookie = "csrf_token=%s:%s:%s" % ( time, user.usersign, sha("%s:%s:%s:%s" % (user.usersign, time, hostname, config["secret"])).hexdigest(), ) assert response["set-cookie"] == quote(cookie.encode("utf-8"), safe=".!~*'():=")
def test_adduser_with_roles(): handle(['', u'adduser', u'cdent', u'crunk', u'cow', u'monkey']) the_user = User('cdent') the_user = store.get(the_user) assert the_user.check_password('crunk') assert 'cow' in the_user.list_roles() assert 'monkey' in the_user.list_roles()
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'] 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 setup_module(module): try: shutil.rmtree('store') except: pass # !!! config['server_host'] = { 'host': 'our_test_domain', 'port': '8001', 'scheme': 'http', } from tiddlyweb.web import serve # we have to have a function that returns the callable, # Selector just _is_ the callable def app_fn(): return serve.load_app() #wsgi_intercept.debuglevel = 1 httplib2_intercept.install() wsgi_intercept.add_wsgi_intercept('our_test_domain', 8001, app_fn) environ = {'tiddlyweb.config': config} module.store = Store(config['server_store'][0], config['server_store'][1], environ) admin = User('admin') admin.add_role('ADMIN') admin.set_password('spank') module.store.put(admin) module.admin_authorization = b64encode('admin:spank') module.user_authorization = b64encode('cdent:pigdog')
def test_post_new_user(): http = httplib2.Http() # XXX simon removed the code that makes this test pass # response, content = http.request('http://our_test_domain:8001/users', # method='POST', # headers={'Content-Type': 'application/json'}, # body='{"username":"******","password":"******"}') # # assert response['status'] == '403' # assert 'insufficient' in content response, content = http.request('http://our_test_domain:8001/users', method='POST', headers={'Content-Type': 'application/json', 'Authorization': 'Basic %s' % admin_authorization}, body='{"username":"******","password":"******"}') assert response['status'] == '201' user = User('cdent') user = store.get(user) assert user.check_password('pigdog') is True assert user.check_password('slam') is False response, content = http.request('http://our_test_domain:8001/users', method='POST', headers={'Content-Type': 'application/json', 'Authorization': 'Basic %s' % admin_authorization}, body='{"username":"******","password":"******"}') assert response['status'] == '409' assert 'User exists' in content
def test_put_password(): http = httplib2.Http() response, content = http.request('http://our_test_domain:8001/users/cdent', method='PUT', headers={'Content-Type': 'application/json'}, body='{"password":"******"}') assert response['status'] == '403' response, content = http.request('http://our_test_domain:8001/users/cdent', method='PUT', headers={'Content-Type': 'application/json', 'Authorization': 'Basic %s' % user_authorization}, body='{"password":"******"}') assert response['status'] == '204' user = User('cdent') user = store.get(user) assert user.check_password('pigcat') is True assert user.check_password('pigdog') is False response, content = http.request('http://our_test_domain:8001/users/cdent', method='PUT', headers={'Content-Type': 'application/json', 'Authorization': 'Basic %s' % admin_authorization}, body='{"password":"******"}') assert response['status'] == '204' user = User('cdent') user = store.get(user) assert user.check_password('pigcow') is True assert user.check_password('pigcat') is False
def register_user(environ, start_response): username, password, confirmation = [environ['tiddlyweb.query'][param][0] for param in ('username', 'password', 'password_confirmation')] user = User(username) store = environ['tiddlyweb.store'] try: store.get(user) available = False except NoUserError: available = username not in BLACKLIST if not available: raise HTTP409('username unavailable') if not password == confirmation: raise HTTP400('passwords do not match') _create_wiki(store, username, username, private=True) user.set_password(password) store.put(user) index = Tiddler('index', username) index.type = 'text/x-markdown' index.text = "Welcome to %s's personal wiki." % username store.put(index) cookie = make_cookie('tiddlyweb_user', user.usersign, path=uri('front page', environ), mac_key=environ['tiddlyweb.config']['secret'], expires=environ['tiddlyweb.config'].get('cookie_age', None)) start_response('303 See Other', [('Set-Cookie', cookie), ('Location', uri('dashboard', environ).encode('UTF-8'))]) return ['']
def make_user(username, password): user = User(username) user.set_password(password) store.put(user) secret_string = sha('%s%s' % (username, config['secret'])).hexdigest() return secret_string
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 handle(environ, start_response): """ Handle a posted request for registration. If the provided username is blacklisted, ask them to log in as someone else. Otherwise send closing material with a link to get started. """ pretty_name = environ["tiddlyweb.query"].get("pretty_name", [None])[0] target_role = environ["tiddlyweb.config"].get("register_role", "MEMBER") store = environ["tiddlyweb.store"] username = environ["tiddlyweb.usersign"]["name"] if _blacklisted(environ, username): return _send_start(environ, start_response, message="That user has been blocked") user = User(username) try: user = store.get(user) except NoUserError: pass # is cool if they don't exist yet user.add_role("%s" % target_role) if pretty_name: user.note = pretty_name store.put(user) environ["tiddlyweb.usersign"] = {"name": user.usersign, "roles": user.list_roles()} return _send_finish(environ, start_response)
def test_users(): userc = User('cdent') userc.set_password('foobar') userc.add_role('ADMIN') userc.note = 'A simple programmer of matter' store.put(userc) userf = User('FND') userf.set_password('I<3whitespace') store.put(userf) user2 = store.get(User('cdent')) assert user2.usersign == userc.usersign assert user2.check_password('foobar') assert user2.list_roles() == userc.list_roles() assert user2.note == userc.note users = list(store.list_users()) assert len(users) == 2 assert ['FND', 'cdent'] == sorted([user.usersign for user in users]) store.delete(User('FND')) users = list(store.list_users()) assert len(users) == 1 py.test.raises(NoUserError, "store.get(User('FND'))")
def establish_user_auth(config, store, host, username): user = User(username) mapping_username = '******' % username mapping_tiddler = Tiddler(mapping_username, 'MAPUSER') mapping_tiddler.fields['mapped_user'] = username try: store.delete(user) except StoreError: pass try: store.delete(mapping_tiddler) except IOError: pass user.add_role('MEMBER') user.note = '{}' store.put(user) ensure_bag('MAPUSER', store) store.put(mapping_tiddler) stamp = datetime.utcnow().strftime('%Y%m%d%H') csrf = gen_nonce(username, host, stamp, config['secret']) cookie = make_cookie('tiddlyweb_user', mapping_username, mac_key=config['secret'], httponly=False) return cookie, csrf
def test_no_cookie_sent(): """ Test no cookie is sent if one is already present """ store = get_store(config) space = 'foo' make_fake_space(store, space) user = User('foo') user.set_password('foobar') store.put(user) user_cookie = get_auth('foo', 'foobar') time = datetime.now().strftime('%Y%m%d%H') cookie = 'csrf_token=%s:%s:%s' % (time, user.usersign, sha('%s:%s:%s:%s' % (user.usersign, time, space, config['secret'])).hexdigest()) response, _ = http.request('http://foo.0.0.0.0:8080/status', method='GET', headers={ 'Cookie': 'tiddlyweb_user="******"; %s' % (user_cookie, cookie) }) cookie = response.get('set-cookie') if cookie: assert 'csrf_token' not in cookie
def test_cookie_set(): """ test that we get a cookie relating to the space we are in """ store = get_store(config) space = 'foo' make_fake_space(store, space) user = User('foo') user.set_password('foobar') store.put(user) user_cookie = get_auth('foo', 'foobar') response, content = http.request('http://foo.0.0.0.0:8080/status', method='GET', headers={ 'Cookie': 'tiddlyweb_user="******"' % user_cookie }) assert response['status'] == '200', content time = datetime.now().strftime('%Y%m%d%H') cookie = 'csrf_token=%s:%s:%s' % (time, user.usersign, sha('%s:%s:%s:%s' % (user.usersign, time, space, config['secret'])).hexdigest()) assert response['set-cookie'] == cookie
def tiddler_get(self, tiddler): store = self.main_store username = tiddler.title user = User(username) user = store.get(user) tiddler.text = '%s' % user.list_roles() return tiddler
def test_cookie_set(): """ test that we get a cookie relating to the space we are in """ store = get_store(config) space = 'foo' make_fake_space(store, space) user = User('foo') user.set_password('foobar') store.put(user) user_cookie = get_auth('foo', 'foobar') response, _ = http.request( 'http://foo.0.0.0.0:8080/status', method='GET', headers={'Cookie': 'tiddlyweb_user="******"' % user_cookie}) assert response['status'] == '200' time = datetime.now().strftime('%Y%m%d%H') cookie = 'csrf_token=%s:%s:%s' % ( time, user.usersign, sha('%s:%s:%s:%s' % (user.usersign, time, space, config['secret'])).hexdigest()) assert response['set-cookie'] == cookie
def test_no_cookie_sent(): """ Test no cookie is sent if one is already present """ store = get_store(config) space = 'foo' make_fake_space(store, space) user = User('foo') user.set_password('foobar') store.put(user) user_cookie = get_auth('foo', 'foobar') time = datetime.now().strftime('%Y%m%d%H') cookie = 'csrf_token=%s:%s:%s' % ( time, user.usersign, sha('%s:%s:%s:%s' % (user.usersign, time, space, config['secret'])).hexdigest()) response, _ = http.request( 'http://foo.0.0.0.0:8080/status', method='GET', headers={'Cookie': 'tiddlyweb_user="******"; %s' % (user_cookie, cookie)}) cookie = response.get('set-cookie') if cookie: assert 'csrf_token' not in cookie
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 _init_store(self, struct): """ creates basic store structure with bags, recipes and users (no support for user passwords for security reasons) """ store = get_store(self.init_config) bags = struct.get("bags", {}) for name, data in bags.items(): desc = data.get("desc") bag = Bag(name, desc=desc) constraints = data.get("policy", {}) _set_policy(bag, constraints) store.put(bag) recipes = struct.get("recipes", {}) for name, data in recipes.items(): # TODO: DRY desc = data.get("desc") recipe = Recipe(name, desc=desc) recipe.set_recipe(data["recipe"]) constraints = data.get("policy", {}) _set_policy(recipe, constraints) store.put(recipe) users = struct.get("users", {}) for name, data in users.items(): note = data.get("note") user = User(name, note=note) password = data.get("_password") if password: user.set_password(password) for role in data.get("roles", []): user.add_role(role) store.put(user)
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 setup_module(module): """ clean up the store, establish a registered client """ clean_store() module.store = get_store(config) environ = {'tiddlyweb.config': config, 'tiddlyweb.store': module.store} ensure_bags(config) # make an application and store that info app = create(name='testapp', owner='appowner1', app_url='http://our_test_domain:8001', callback_url='http://our_test_domain:8001/_oauth/callback') client_id = app.title client_secret = app.fields['client_secret'] store_app(environ, app) config['oauth.servers']['testserver']['client_id'] = client_id config['oauth.servers']['testserver']['client_secret'] = client_secret module.client_id = client_id initialize_app(config) module.http = Http() # we need a user who is going to use the client app user = User('cdent') user.set_password('cowpig') module.store.put(user)
def handle(environ, start_response): """ Handle a posted request for registration. If the provided username is blacklisted, ask them to log in as someone else. Otherwise send closing material with a link to get started. """ pretty_name = environ['tiddlyweb.query'].get('pretty_name', [None])[0] target_role = environ['tiddlyweb.config'].get('register_role', 'MEMBER') store = environ['tiddlyweb.store'] username = environ['tiddlyweb.usersign']['name'] if _blacklisted(environ, username): return _send_start(environ, start_response, message='That user has been blocked') user = User(username) try: user = store.get(user) except NoUserError: pass # is cool if they don't exist yet user.add_role('%s' % target_role) if pretty_name: user.note = pretty_name store.put(user) environ['tiddlyweb.usersign'] = {'name': user.usersign, 'roles': user.list_roles()} return _send_finish(environ, start_response)
def user_page(environ, start_response): userpage = environ['wsgiorg.routing_args'][1]['userpage'] user = environ['tiddlyweb.usersign'] userpage = _decode_name(userpage) first_time_check(environ, user) store = environ['tiddlyweb.store'] # If we try to go to a user page that doesn't exist, # just go to the home page. XXX maybe should 404 instead. try: userpage_user = User(userpage) userpage_user = store.get(userpage_user) except NoUserError: pass # roles will be empty if 'MEMBER' not in userpage_user.list_roles(): raise HTTP404('%s has no page' % userpage) user_friend_names = get_friends(store, user['name']) friend_names = sorted(get_friends(store, userpage)) friends = [] for name in friend_names: email = get_email_tiddler(store, name) email_md5 = md5(email.lower()).hexdigest() friends.append((name, email_md5)) profile_tiddler = get_profile(store, user, userpage) profile_html = render_wikitext(profile_tiddler, environ) notice_tiddler = get_notice(environ) notice_html = render_wikitext(notice_tiddler, environ) kept_recipes = get_stuff(store, store.list_recipes(), user, userpage) kept_bags = get_stuff(store, store.list_bags(), user, userpage) kept_favorites = get_stuff(store, get_favorited_bags(store, userpage), user) kept_bookmarks = get_stuff(store, get_bookmarked_recipes(store, userpage), user) email = get_email_tiddler(store, userpage) email_md5 = md5(email.lower()).hexdigest() data = { 'bags': kept_bags, 'user_friends': user_friend_names, 'friends': friends, 'recipes': kept_recipes, 'favorites': kept_favorites, 'bookmarks': kept_bookmarks, 'home': userpage, 'profile': profile_html, 'notice': { 'html': notice_html, 'modified': notice_tiddler.modified }, 'title': userpage, 'email': email, 'email_md5': email_md5, 'user': get_user_object(environ) } return send_template(environ, 'profile.html', data)
def setup_module(module): initialize_app() reset_textstore() module.store = _teststore() user = User(name) user.set_password(name) module.store.put(user) module.cookie = None
def setup_module(module): initialize_app() reset_textstore() module.store = _teststore() user = User(u'cd\u2714nt') user.set_password('cowpig') module.store.put(user) muchdata(module.store)
def test_simple_get(): user = User("cdent") user = store.get(user) assert user.note == "foo" assert user.check_password("cowpig") assert sorted(user.list_roles()) == ["ADMIN", "BOSS"] assert not user.check_password("pigcow")
def test_simple_get(): user = User('cdent') user = store.get(user) assert user.note == 'foo' assert user.check_password('cowpig') assert sorted(user.list_roles()) == ['ADMIN', 'BOSS'] assert not user.check_password('pigcow')
def setup_module(module): config['system_plugins'].append('test.test_web_extract') initialize_app() reset_textstore() module.store = _teststore() user = User('cow') user.set_password('pig') module.store.put(user)
def test_multi_role_user(): user = User(u'cdent') user.add_role('cow') user.add_role('cow') store.put(user) user2 = store.get(User(u'cdent')) assert list(user2.roles) == ['cow']
def test_multi_role_user(): user = User(u'cdent') user.add_role(u'cow') user.add_role(u'cow') store.put(user) user2 = store.get(User(u'cdent')) assert list(user2.roles) == ['cow']
def _create_user(environ, start_response, creation=0, expiration=0, role='tier1'): domain = get_domain(environ['HTTP_HOST']) if creation == 0: creation = time.time() store = environ['tiddlyweb.store'] query = environ['tiddlyweb.query'] name = query.get('name', [None])[0] email = query.get('email', [None])[0] company = query.get('company', [None])[0] country = query.get('country', [None])[0] if not (name and email): # The form has not been filled out return _user_form(environ, start_response, role=role, message='Missing Data!', formdata={'name': name, 'email': email, 'company': company, 'country': country}) user = User(email) try: user = store.get(user) # User exists! return _user_form(environ, start_response, role=role, message='That account already exists!', formdata={'name': name, 'email': email, 'company': company, 'country': country}) except NoUserError: password = _random_pass() user.set_password(password) user.add_role(role) store.put(user) bag_name = environ['tiddlyweb.config'].get('magicuser.bag', 'MAGICUSER') ensure_bag(bag_name, store, policy_dict={ 'read': ['NONE'], 'write': ['NONE'], 'create': ['NONE'], 'manage': ['NONE']}) tiddler = Tiddler(email, bag_name) tiddler.fields['country'] = country tiddler.fields['company'] = company tiddler.fields['name'] = name # Set the creation and expiration times. now = time.time() tiddler.fields['creation'] = '%s' % creation tiddler.fields['expiry'] = '%s' % expiration store.put(tiddler) to_address = email subject = domain+" user info" body = """ Here's your info: Username: %s Password: %s """ % (email, password) query_string = '?email=%s' % to_address try: send_email(to_address, subject=subject, body=body, from_='avox@'+domain) query_string += '&success=1&role=%s' % role raise HTTP303(server_base_url(environ)+'/pages/new_account'+query_string) except socket.error: logging.debug('failed to send: %s:%s:%s', to_address, subject, body) query_string += '&failure=1&role=%s' % role raise HTTP302(server_base_url(environ)+'/pages/new_account'+query_string)
def _do_login_or_register(environ, start_response, server_name, response_map, content): """ We had a valid response from the oauth provider, let's see if that is a user or somebody we can register. """ store = environ['tiddlyweb.store'] config = environ['tiddlyweb.config'] userinfo = simplejson.loads(content) userdata = {} for key, value in response_map.iteritems(): userdata[key] = userinfo.get(value, '') server_login = None username = userdata['login'] if not username: raise HTTP400('extractable username data required') userdata['server_name'] = server_name if config.get('oauth.use_mapuser', False): server_login = '******' % (server_name, username) map_bag_name = config.get('magicuser.map', 'MAPUSER') tiddler = Tiddler(server_login, map_bag_name) try: tiddler = store.get(tiddler) mapped_user = tiddler.fields.get('mapped_user') store.get(User(mapped_user)) user = User(server_login) return _send_cookie(environ, start_response, user) except StoreError: try: local_user = store.get(User(username)) except StoreError: local_user = None pass # fall through to register else: try: user = store.get(User(username)) return _send_cookie(environ, start_response, user) except StoreError: local_user = None pass # fall through to register registration_template = get_template(environ, 'registration.html') start_response('200 OK', [('Content-Type', 'text/html; charset=UTF-8'), ('Cache-Control', 'no-store')]) if local_user: userdata['local_user'] = local_user.usersign userdata['server_name_sig'] = _sign(config, server_name) if server_login: userdata['server_login'] = server_login userdata['server_login_sig'] = _sign(config, server_login) return registration_template.generate(userdata)
def test_put_get_user(): user = User('testone') user.add_role('monkey') store.put(user) read_user = User('testone') read_user = store.get(read_user) assert read_user.list_roles() == ['monkey']
def test_post_data_multipart_form(): """ test that a form POST requires a nonce test using multipart/form-data """ store = get_store(config) hostname = "foo.0.0.0.0:8080" user = User(u"f\u00F6o") user.set_password("foobar") store.put(user) timestamp = datetime.utcnow().strftime("%Y%m%d%H") secret = config["secret"] nonce = "%s:%s:%s" % ( timestamp, user.usersign, sha("%s:%s:%s:%s" % (user.usersign, timestamp, hostname, secret)).hexdigest(), ) user_cookie = get_auth(u"f\u00F6o", "foobar") csrf_token = "csrf_token=%s" % nonce data = """---------------------------168072824752491622650073 Content-Disposition: form-data; name="title" foobar ---------------------------168072824752491622650073 Content-Disposition: form-data; name="text" Hello World ---------------------------168072824752491622650073--""" # test success uri = "http://foo.0.0.0.0:8080/bags/foo_public/tiddlers?%s" % csrf_token response, content = http.request( uri, method="POST", headers={ "Content-Type": "multipart/form-data; " "boundary=---------------------------168072824752491622650073", "Cookie": 'tiddlyweb_user="******"' % user_cookie, "Content-Length": "390", }, body=data, ) assert response["status"] == "204", content # test failure response, _ = http.request( "http://foo.0.0.0.0:8080/bags/foo_public/tiddlers", method="POST", headers={ "Content-Type": "multipart/form-data; " "boundary=---------------------------168072824752491622650073", "Cookie": 'tiddlyweb_user="******"' % user_cookie, "Content-Length": "267", }, body=data, ) assert response["status"] == "400"
def user_page(environ, start_response): userpage = environ['wsgiorg.routing_args'][1]['userpage'] user = environ['tiddlyweb.usersign'] userpage = _decode_name(userpage) first_time_check(environ, user) store = environ['tiddlyweb.store'] # If we try to go to a user page that doesn't exist, # just go to the home page. XXX maybe should 404 instead. try: userpage_user = User(userpage) userpage_user = store.get(userpage_user) except NoUserError: pass # roles will be empty if 'MEMBER' not in userpage_user.list_roles(): raise HTTP404('%s has no page' % userpage) user_friend_names = get_friends(store, user['name']) friend_names = sorted(get_friends(store, userpage)) friends = [] for name in friend_names: email = get_email_tiddler(store, name) email_md5 = md5(email.lower()).hexdigest() friends.append((name, email_md5)) profile_tiddler = get_profile(store, user, userpage) profile_html = render_wikitext(profile_tiddler, environ) notice_tiddler = get_notice(environ) notice_html = render_wikitext(notice_tiddler, environ) kept_recipes = get_stuff(store, store.list_recipes(), user, userpage) kept_bags = get_stuff(store, store.list_bags(), user, userpage) kept_favorites = get_stuff(store, get_favorited_bags(store, userpage), user) kept_bookmarks = get_stuff(store, get_bookmarked_recipes(store, userpage), user) email = get_email_tiddler(store, userpage) email_md5 = md5(email.lower()).hexdigest() data = {'bags': kept_bags, 'user_friends': user_friend_names, 'friends': friends, 'recipes': kept_recipes, 'favorites': kept_favorites, 'bookmarks': kept_bookmarks, 'home': userpage, 'profile': profile_html, 'notice': {'html': notice_html, 'modified': notice_tiddler.modified}, 'title': userpage, 'email': email, 'email_md5': email_md5, 'user': get_user_object(environ)} return send_template(environ, 'profile.html', data)
def test_user_create(): user = User('cdent') assert type(user) == User assert user.usersign == 'cdent' user.note = note assert user.note == note user.note = 'bar' assert user.note == 'bar'
def setup_module(module): make_test_env(module) httplib2_intercept.install() wsgi_intercept.add_wsgi_intercept('0.0.0.0', 8080, app_fn) wsgi_intercept.add_wsgi_intercept('cdent.0.0.0.0', 8080, app_fn) make_fake_space(module.store, 'cdent') user = User('cdent') user.set_password('cow') module.store.put(user) module.http = httplib2.Http()
def setup_module(module): config['auth_systems'].append('not.really.there') initialize_app() reset_textstore() module.store = _teststore() muchdata(module.store) user = User('cdent') user.set_password('cowpig') store.put(user)
def test_post_data_multipart_form(): """ test that a form POST requires a nonce test using multipart/form-data """ store = get_store(config) space = 'foo' make_fake_space(store, space) user = User('foo') user.set_password('foobar') store.put(user) timestamp = datetime.now().strftime('%Y%m%d%H') secret = config['secret'] nonce = '%s:%s:%s' % ( timestamp, user.usersign, sha('%s:%s:%s:%s' % (user.usersign, timestamp, space, secret)).hexdigest()) user_cookie = get_auth('foo', 'foobar') csrf_token = 'csrf_token=%s' % nonce data = '''---------------------------168072824752491622650073 Content-Disposition: form-data; name="title" foobar ---------------------------168072824752491622650073 Content-Disposition: form-data; name="text" Hello World ---------------------------168072824752491622650073--''' #test success uri = 'http://foo.0.0.0.0:8080/bags/foo_public/tiddlers?%s' % csrf_token response, content = http.request(uri, method='POST', headers={ 'Content-Type': 'multipart/form-data; ' \ 'boundary=---------------------------168072824752491622650073', 'Cookie': 'tiddlyweb_user="******"' % user_cookie, 'Content-Length': '390' }, body=data) print content assert response['status'] == '204' #test failure response, _ = http.request('http://foo.0.0.0.0:8080/bags/foo_public/tiddlers', method='POST', headers={ 'Content-Type': 'multipart/form-data; ' \ 'boundary=---------------------------168072824752491622650073', 'Cookie': 'tiddlyweb_user="******"' % user_cookie, 'Content-Length': '267' }, body=data) assert response['status'] == '400'
def http_test(): initialize_app() reset_textstore() store = _teststore() muchdata(store) # we're going to need a user for testing auth stuff # so make that now user = User('cdent') user.set_password('cowpig') store.put(user)
def test_complex_username(): username = u'test\u00BB\u00BBuser.com/foo' user = User(username) store.put(user) users = list(store.list_users()) assert username in [user.usersign for user in users] user_out = User(username) user_out = store.get(user_out) assert user_out.usersign == username
def setup_module(module): initialize_app() reset_textstore() module.store = _teststore() bag = Bag('bag0') module.store.put(bag) user = User('cdent') user.set_password('cowpig') module.store.put(user)
def test_list_users(): user1 = User('test1') user2 = User('test2') store.put(user1) store.put(user2) users = list(store.list_users()) assert len(users) == 3 usernames = [user.usersign for user in users] assert 'test1' in usernames assert 'test2' in usernames assert 'cdent' in usernames assert 'laramie' not in usernames
def setup_module(module): initialize_app() reset_textstore() module.store = _teststore() muchdata(module.store) user = User('cdent') user.set_password('cowpig') module.store.put(user) try: os.mkdir('.test_cache') except OSError: pass # we don't care if it already exists
def http_test(test_data, base): global tests, store, base_url base_url = base tests = test_data initialize_app() reset_textstore() store = _teststore() muchdata(store) # we're going to need a user for testing auth stuff # so make that now user = User('cdent') user.set_password('cowpig') store.put(user)
def setup_module(module): clean_store() module.store = get_store(config) module.environ = { 'tiddlyweb.config': config, 'tiddlyweb.store': module.store } ensure_bags(config) initialize_app(config) module.http = Http() user = User('cdent') user.set_password('cowpig') module.store.put(user)
def test_delete(): user = User('deleteme') user.note = 'delete me please' store.put(user) stored_user = User('deleteme') stored_user = store.get(stored_user) assert stored_user.note == 'delete me please' deleted_user = User('deleteme') store.delete(deleted_user) py.test.raises(NoUserError, 'store.get(deleted_user)') py.test.raises(NoUserError, 'store.delete(deleted_user)')
def test_status_base_auth(): user = User('foo') user.set_password('foobar') store.put(user) user_cookie = get_auth('foo', 'foobar') change_space_member(store, 'thing', add='foo') response, content = http.request( 'http://0.0.0.0:8080/status', headers={'Cookie': 'tiddlyweb_user="******"' % user_cookie}) assert response['status'] == '200' info = simplejson.loads(content) assert info['username'] == 'foo' assert 'space' not in info
def _status_gather_data(environ): """ Monkey patch twp.status to add additional information specific to TiddlySpace. """ data = original_gather_data(environ) data['server_host'] = environ['tiddlyweb.config']['server_host'] data['tiddlyspace_version'] = environ['tiddlyweb.config'][ 'tiddlyspace.version'] # gather space data http_host, host_url = determine_host(environ) if http_host != host_url: space_name = determine_space(environ, http_host) try: recipe_name = determine_space_recipe(environ, space_name) data['space'] = {'name': space_name, 'recipe': recipe_name} except HTTP404: pass # ensure user is known usersign = environ['tiddlyweb.usersign']['name'] store = environ['tiddlyweb.store'] try: store.get(User(usersign)) except NoUserError: data['username'] = '******' if usersign != 'GUEST': data['identity'] = usersign return data
def html_profile(environ, start_response): """ Send the HTML profile, made up for the user's SiteIcon, their profile from their space, and their most recently modified tiddlers. """ username = environ['wsgiorg.routing_args'][1]['username'] usersign = environ['tiddlyweb.usersign'] store = environ['tiddlyweb.store'] try: _ = store.get(User(username)) except NoUserError: raise HTTP404('Profile not found for %s' % username) activity_feed = profile_atom_url(environ, username) environ['tiddlyweb.links'] = [ '<link rel="alternate" type="application/atom+xml"' 'title="Atom activity feed" href="%s" />' % activity_feed ] profile_tiddler = Tiddler('profile', '%s_public' % username) try: profile_tiddler = store.get(profile_tiddler) except StoreError, exc: raise HTTP404('No profile for %s: %s' % (username, exc))
def userpage(environ, start_response): username = environ['tiddlyweb.usersign']['name'] user = environ['wsgiorg.routing_args'][1]['user'] if username != user: #raise ForbiddenError raise UserRequiredError store = environ['tiddlyweb.store'] user_data = User(user) try: user_data = store.get(user_data) wikinames = user_data.note.split('\n') wikis = [] if wikinames: for name in wikinames: if not len(name): continue recipe = Recipe(name) recipe = store.get(recipe) url = recipe_url(environ, recipe) wikis.append(dict(name=name, url=url, description=recipe.desc)) except NoUserError: wikis = [] start_response('200 OK', [('Content-Type', 'text/html')]) environ['tiddlyweb.title'] = 'Hello %s' % user template = template_env.get_template('user.html') return template.generate(wikis=wikis)