def setUp(self): request = Request(env={}) request.application = "a" request.controller = "c" request.function = "f" request.folder = "applications/admin" response = Response() session = Session() T = translator("", "en") session.connect(request, response) from gluon.globals import current current.request = request current.response = response current.session = session current.T = T self.db = DAL(DEFAULT_URI, check_reserved=["all"]) self.auth = Auth(self.db) self.auth.define_tables(username=True, signature=False) self.db.define_table("t0", Field("tt"), self.auth.signature) self.auth.enable_record_versioning(self.db) # Create a user self.db.auth_user.insert( first_name="Bart", last_name="Simpson", username="******", email="*****@*****.**", password="******", registration_key=None, registration_id=None, ) self.db.commit()
def setUp(self): request = Request(env={}) request.application = 'a' request.controller = 'c' request.function = 'f' request.folder = 'applications/admin' response = Response() session = Session() T = translator('', 'en') session.connect(request, response) from gluon.globals import current current.request = request current.response = response current.session = session current.T = T self.db = DAL(DEFAULT_URI, check_reserved=['all']) self.auth = Auth(self.db) self.auth.define_tables(username=True, signature=False) self.db.define_table('t0', Field('tt'), self.auth.signature) self.auth.enable_record_versioning(self.db) # Create a user self.db.auth_user.insert(first_name='Bart', last_name='Simpson', username='******', email='*****@*****.**', password='******', registration_key=None, registration_id=None) self.db.commit()
def testRun(self): # setup request = Request(env={}) request.application = 'a' request.controller = 'c' request.function = 'f' request.folder = 'applications/admin' response = Response() session = Session() T = translator('', 'en') session.connect(request, response) from gluon.globals import current current.request = request current.response = response current.session = session current.T = T db = DAL(DEFAULT_URI, check_reserved=['all']) auth = Auth(db) auth.define_tables(username=True, signature=False) self.assertTrue('auth_user' in db) self.assertTrue('auth_group' in db) self.assertTrue('auth_membership' in db) self.assertTrue('auth_permission' in db) self.assertTrue('auth_event' in db) db.define_table('t0', Field('tt'), auth.signature) auth.enable_record_versioning(db) self.assertTrue('t0_archive' in db) for f in [ 'login', 'register', 'retrieve_password', 'retrieve_username' ]: html_form = getattr(auth, f)().xml() self.assertTrue('name="_formkey"' in html_form) for f in [ 'logout', 'verify_email', 'reset_password', 'change_password', 'profile', 'groups' ]: self.assertRaisesRegexp(HTTP, "303*", getattr(auth, f)) self.assertRaisesRegexp(HTTP, "401*", auth.impersonate) try: for t in [ 't0_archive', 't0', 'auth_cas', 'auth_event', 'auth_membership', 'auth_permission', 'auth_group', 'auth_user' ]: db[t].drop() except SyntaxError as e: # GAE doesn't support drop pass return
def setup_clean_session(): request = Request(env={}) request.application = 'a' request.controller = 'c' request.function = 'f' request.folder = 'applications/admin' response = Response() session = Session() session.connect(request, response) from gluon.globals import current current.request = request current.response = response current.session = session return current
def testRun(self): # setup request = Request(env={}) request.application = 'a' request.controller = 'c' request.function = 'f' request.folder = 'applications/admin' response = Response() session = Session() T = translator('', 'en') session.connect(request, response) from gluon.globals import current current.request = request current.response = response current.session = session current.T = T db = DAL(DEFAULT_URI, check_reserved=['all']) auth = Auth(db) auth.define_tables(username=True, signature=False) self.assertTrue('auth_user' in db) self.assertTrue('auth_group' in db) self.assertTrue('auth_membership' in db) self.assertTrue('auth_permission' in db) self.assertTrue('auth_event' in db) db.define_table('t0', Field('tt'), auth.signature) auth.enable_record_versioning(db) self.assertTrue('t0_archive' in db) for f in ['login', 'register', 'retrieve_password', 'retrieve_username']: html_form = getattr(auth, f)().xml() self.assertTrue('name="_formkey"' in html_form) for f in ['logout', 'verify_email', 'reset_password', 'change_password', 'profile', 'groups']: self.assertRaisesRegexp(HTTP, "303*", getattr(auth, f)) self.assertRaisesRegexp(HTTP, "401*", auth.impersonate) try: for t in ['t0_archive', 't0', 'auth_cas', 'auth_event', 'auth_membership', 'auth_permission', 'auth_group', 'auth_user']: db[t].drop() except SyntaxError as e: # GAE doesn't support drop pass return
def setUp(self): request = Request(env={}) request.application = 'a' request.controller = 'c' request.function = 'f' request.folder = 'applications/admin' response = Response() session = Session() session.connect(request, response) from gluon.globals import current current.request = request current.response = response current.session = session self.current = current rconn = RConn(host='localhost') self.db = RedisSession(redis_conn=rconn, session_expiry=False) self.tname = 'testtablename' return current
def setUp(self): from gluon.globals import Request, Response, Session, current from gluon.html import A, DIV, FORM, MENU, TABLE, TR, INPUT, URL, XML from gluon.html import ASSIGNJS from gluon.validators import IS_NOT_EMPTY from gluon.compileapp import LOAD from gluon.http import HTTP, redirect from gluon.tools import Auth from gluon.sql import SQLDB from gluon.sqlhtml import SQLTABLE, SQLFORM self.original_check_credentials = fileutils.check_credentials fileutils.check_credentials = fake_check_credentials request = Request(env={}) request.application = 'welcome' request.controller = 'appadmin' request.function = self._testMethodName.split('_')[1] request.folder = 'applications/welcome' request.env.http_host = '127.0.0.1:8000' request.env.remote_addr = '127.0.0.1' response = Response() session = Session() T = TranslatorFactory('', 'en') session.connect(request, response) current.request = request current.response = response current.session = session current.T = T db = DAL(DEFAULT_URI, check_reserved=['all']) auth = Auth(db) auth.define_tables(username=True, signature=False) db.define_table('t0', Field('tt'), auth.signature) # Create a user db.auth_user.insert(first_name='Bart', last_name='Simpson', username='******', email='*****@*****.**', password='******', registration_key=None, registration_id=None) self.env = locals()
def setUp(self): from gluon.globals import Request, Response, Session, current from gluon.html import A, DIV, FORM, MENU, TABLE, TR, INPUT, URL, XML from gluon.html import ASSIGNJS from gluon.validators import IS_NOT_EMPTY from gluon.compileapp import LOAD from gluon.http import HTTP, redirect from gluon.tools import Auth from gluon.sql import SQLDB from gluon.sqlhtml import SQLTABLE, SQLFORM self.original_check_credentials = fileutils.check_credentials fileutils.check_credentials = fake_check_credentials request = Request(env={}) request.application = 'welcome' request.controller = 'appadmin' request.function = self._testMethodName.split('_')[1] request.folder = 'applications/welcome' request.env.http_host = '127.0.0.1:8000' request.env.remote_addr = '127.0.0.1' response = Response() session = Session() T = translator('', 'en') session.connect(request, response) current.request = request current.response = response current.session = session current.T = T db = DAL(DEFAULT_URI, check_reserved=['all']) auth = Auth(db) auth.define_tables(username=True, signature=False) db.define_table('t0', Field('tt'), auth.signature) # Create a user db.auth_user.insert(first_name='Bart', last_name='Simpson', username='******', email='*****@*****.**', password='******', registration_key=None, registration_id=None) self.env = locals()
def wsgibase(environ, responder): """ The gluon wsgi application. The first function called when a page is requested (static or dynamic). It can be called by paste.httpserver or by apache mod_wsgi (or any WSGI-compatible server). - fills request with info - the environment variables, replacing '.' with '_' - adds web2py path and version info - compensates for fcgi missing path_info and query_string - validates the path in url The url path must be either: 1. for static pages: - /<application>/static/<file> 2. for dynamic pages: - /<application>[/<controller>[/<function>[/<sub>]]][.<extension>] The naming conventions are: - application, controller, function and extension may only contain `[a-zA-Z0-9_]` - file and sub may also contain '-', '=', '.' and '/' """ eget = environ.get current.__dict__.clear() request = Request(environ) response = Response() session = Session() env = request.env #env.web2py_path = global_settings.applications_parent env.web2py_version = web2py_version #env.update(global_settings) static_file = False try: try: try: # ################################################## # handle fcgi missing path_info and query_string # select rewrite parameters # rewrite incoming URL # parse rewritten header variables # parse rewritten URL # serve file if static # ################################################## fixup_missing_path_info(environ) (static_file, version, environ) = url_in(request, environ) response.status = env.web2py_status_code or response.status if static_file: if eget('QUERY_STRING', '').startswith('attachment'): response.headers['Content-Disposition'] \ = 'attachment' if version: response.headers['Cache-Control'] = 'max-age=315360000' response.headers[ 'Expires'] = 'Thu, 31 Dec 2037 23:59:59 GMT' response.stream(static_file, request=request) # ################################################## # fill in request items # ################################################## app = request.application # must go after url_in! if not global_settings.local_hosts: local_hosts = set(['127.0.0.1', '::ffff:127.0.0.1', '::1']) if not global_settings.web2py_runtime_gae: try: fqdn = socket.getfqdn() local_hosts.add(socket.gethostname()) local_hosts.add(fqdn) local_hosts.update([ addrinfo[4][0] for addrinfo in getipaddrinfo(fqdn) ]) if env.server_name: local_hosts.add(env.server_name) local_hosts.update([ addrinfo[4][0] for addrinfo in getipaddrinfo(env.server_name) ]) except (socket.gaierror, TypeError): pass global_settings.local_hosts = list(local_hosts) else: local_hosts = global_settings.local_hosts client = get_client(env) x_req_with = str(env.http_x_requested_with).lower() request.update( client = client, folder = abspath('applications', app) + os.sep, ajax = x_req_with == 'xmlhttprequest', cid = env.http_web2py_component_element, is_local = env.remote_addr in local_hosts, is_https = env.wsgi_url_scheme in HTTPS_SCHEMES or \ request.env.http_x_forwarded_proto in HTTPS_SCHEMES \ or env.https == 'on' ) request.compute_uuid() # requires client request.url = environ['PATH_INFO'] # ################################################## # access the requested application # ################################################## disabled = pjoin(request.folder, 'DISABLED') if not exists(request.folder): if app == rwthread.routes.default_application \ and app != 'welcome': redirect(URL('welcome', 'default', 'index')) elif rwthread.routes.error_handler: _handler = rwthread.routes.error_handler redirect( URL(_handler['application'], _handler['controller'], _handler['function'], args=app)) else: raise HTTP(404, rwthread.routes.error_message % 'invalid request', web2py_error='invalid application') elif not request.is_local and exists(disabled): raise HTTP( 503, "<html><body><h1>Temporarily down for maintenance</h1></body></html>" ) # ################################################## # build missing folders # ################################################## create_missing_app_folders(request) # ################################################## # get the GET and POST data # ################################################## #parse_get_post_vars(request, environ) # ################################################## # expose wsgi hooks for convenience # ################################################## request.wsgi = LazyWSGI(environ, request, response) # ################################################## # load cookies # ################################################## if env.http_cookie: try: request.cookies.load(env.http_cookie) except Cookie.CookieError, e: pass # invalid cookies # ################################################## # try load session or create new session file # ################################################## if not env.web2py_disable_session: session.connect(request, response) # ################################################## # run controller # ################################################## if global_settings.debugging and app != "admin": import gluon.debug # activate the debugger gluon.debug.dbg.do_debug(mainpyfile=request.folder) serve_controller(request, response, session) except HTTP, http_response: if static_file: return http_response.to(responder, env=env) if request.body: request.body.close() if hasattr(current, 'request'): # ################################################## # on success, try store session in database # ################################################## session._try_store_in_db(request, response) # ################################################## # on success, commit database # ################################################## if response.do_not_commit is True: BaseAdapter.close_all_instances(None) elif response.custom_commit: BaseAdapter.close_all_instances(response.custom_commit) else: BaseAdapter.close_all_instances('commit') # ################################################## # if session not in db try store session on filesystem # this must be done after trying to commit database! # ################################################## session._try_store_in_cookie_or_file(request, response) # Set header so client can distinguish component requests. if request.cid: http_response.headers.setdefault( 'web2py-component-content', 'replace') if request.ajax: if response.flash: http_response.headers['web2py-component-flash'] = \ urllib2.quote(xmlescape(response.flash)\ .replace('\n','')) if response.js: http_response.headers['web2py-component-command'] = \ urllib2.quote(response.js.replace('\n','')) # ################################################## # store cookies in headers # ################################################## session._fixup_before_save() http_response.cookies2headers(response.cookies) ticket = None except RestrictedError, e: if request.body: request.body.close() # ################################################## # on application error, rollback database # ################################################## # log tickets before rollback if not in DB if not request.tickets_db: ticket = e.log(request) or 'unknown' # rollback if response._custom_rollback: response._custom_rollback() else: BaseAdapter.close_all_instances('rollback') # if tickets in db, reconnect and store it in db if request.tickets_db: ticket = e.log(request) or 'unknown' http_response = \ HTTP(500, rwthread.routes.error_message_ticket % dict(ticket=ticket), web2py_error='ticket %s' % ticket)
def wsgibase(environ, responder): """ this is the gluon wsgi application. the first function called when a page is requested (static or dynamic). it can be called by paste.httpserver or by apache mod_wsgi. - fills request with info - the environment variables, replacing '.' with '_' - adds web2py path and version info - compensates for fcgi missing path_info and query_string - validates the path in url The url path must be either: 1. for static pages: - /<application>/static/<file> 2. for dynamic pages: - /<application>[/<controller>[/<function>[/<sub>]]][.<extension>] - (sub may go several levels deep, currently 3 levels are supported: sub1/sub2/sub3) The naming conventions are: - application, controller, function and extension may only contain [a-zA-Z0-9_] - file and sub may also contain '-', '=', '.' and '/' """ eget = environ.get current.__dict__.clear() request = Request(environ) response = Response() session = Session() env = request.env #env.web2py_path = global_settings.applications_parent env.web2py_version = web2py_version #env.update(global_settings) static_file = False try: try: try: # ################################################## # handle fcgi missing path_info and query_string # select rewrite parameters # rewrite incoming URL # parse rewritten header variables # parse rewritten URL # serve file if static # ################################################## fixup_missing_path_info(environ) (static_file, version, environ) = url_in(request, environ) response.status = env.web2py_status_code or response.status if static_file: if eget('QUERY_STRING', '').startswith('attachment'): response.headers['Content-Disposition'] \ = 'attachment' if version: response.headers['Cache-Control'] = 'max-age=315360000' response.headers[ 'Expires'] = 'Thu, 31 Dec 2037 23:59:59 GMT' response.stream(static_file, request=request) # ################################################## # fill in request items # ################################################## app = request.application # must go after url_in! if not global_settings.local_hosts: local_hosts = set(['127.0.0.1', '::ffff:127.0.0.1', '::1']) if not global_settings.web2py_runtime_gae: try: fqdn = socket.getfqdn() local_hosts.add(socket.gethostname()) local_hosts.add(fqdn) local_hosts.update([ addrinfo[4][0] for addrinfo in getipaddrinfo(fqdn)]) if env.server_name: local_hosts.add(env.server_name) local_hosts.update([ addrinfo[4][0] for addrinfo in getipaddrinfo(env.server_name)]) except (socket.gaierror, TypeError): pass global_settings.local_hosts = list(local_hosts) else: local_hosts = global_settings.local_hosts client = get_client(env) x_req_with = str(env.http_x_requested_with).lower() request.update( client = client, folder = abspath('applications', app) + os.sep, ajax = x_req_with == 'xmlhttprequest', cid = env.http_web2py_component_element, is_local = env.remote_addr in local_hosts, is_https = env.wsgi_url_scheme in HTTPS_SCHEMES or \ request.env.http_x_forwarded_proto in HTTPS_SCHEMES \ or env.https == 'on' ) request.compute_uuid() # requires client request.url = environ['PATH_INFO'] # ################################################## # access the requested application # ################################################## disabled = pjoin(request.folder, 'DISABLED') if not exists(request.folder): if app == rwthread.routes.default_application \ and app != 'welcome': redirect(URL('welcome', 'default', 'index')) elif rwthread.routes.error_handler: _handler = rwthread.routes.error_handler redirect(URL(_handler['application'], _handler['controller'], _handler['function'], args=app)) else: raise HTTP(404, rwthread.routes.error_message % 'invalid request', web2py_error='invalid application') elif not request.is_local and exists(disabled): raise HTTP(503, "<html><body><h1>Temporarily down for maintenance</h1></body></html>") # ################################################## # build missing folders # ################################################## create_missing_app_folders(request) # ################################################## # get the GET and POST data # ################################################## #parse_get_post_vars(request, environ) # ################################################## # expose wsgi hooks for convenience # ################################################## request.wsgi = LazyWSGI(environ, request, response) # ################################################## # load cookies # ################################################## if env.http_cookie: try: request.cookies.load(env.http_cookie) except Cookie.CookieError, e: pass # invalid cookies # ################################################## # try load session or create new session file # ################################################## if not env.web2py_disable_session: session.connect(request, response) # ################################################## # run controller # ################################################## if global_settings.debugging and app != "admin": import gluon.debug # activate the debugger gluon.debug.dbg.do_debug(mainpyfile=request.folder) serve_controller(request, response, session) except HTTP, http_response: if static_file: return http_response.to(responder, env=env) if request.body: request.body.close() if hasattr(current,'request'): # ################################################## # on success, try store session in database # ################################################## session._try_store_in_db(request, response) # ################################################## # on success, commit database # ################################################## if response.do_not_commit is True: BaseAdapter.close_all_instances(None) elif response.custom_commit: BaseAdapter.close_all_instances(response.custom_commit) else: BaseAdapter.close_all_instances('commit') # ################################################## # if session not in db try store session on filesystem # this must be done after trying to commit database! # ################################################## session._try_store_in_cookie_or_file(request, response) # Set header so client can distinguish component requests. if request.cid: http_response.headers.setdefault( 'web2py-component-content', 'replace') if request.ajax: if response.flash: http_response.headers['web2py-component-flash'] = \ urllib2.quote(xmlescape(response.flash)\ .replace('\n','')) if response.js: http_response.headers['web2py-component-command'] = \ urllib2.quote(response.js.replace('\n','')) # ################################################## # store cookies in headers # ################################################## session._fixup_before_save() http_response.cookies2headers(response.cookies) ticket = None except RestrictedError, e: if request.body: request.body.close() # ################################################## # on application error, rollback database # ################################################## # log tickets before rollback if not in DB if not request.tickets_db: ticket = e.log(request) or 'unknown' # rollback if response._custom_rollback: response._custom_rollback() else: BaseAdapter.close_all_instances('rollback') # if tickets in db, reconnect and store it in db if request.tickets_db: ticket = e.log(request) or 'unknown' http_response = \ HTTP(500, rwthread.routes.error_message_ticket % dict(ticket=ticket), web2py_error='ticket %s' % ticket)
class TestAuthAPI(unittest.TestCase): def setUp(self): self.request = Request(env={}) self.request.application = 'a' self.request.controller = 'c' self.request.function = 'f' self.request.folder = 'applications/admin' self.response = Response() self.session = Session() T = translator('', 'en') self.session.connect(self.request, self.response) from gluon.globals import current self.current = current self.current.request = self.request self.current.response = self.response self.current.session = self.session self.current.T = T self.db = DAL(DEFAULT_URI, check_reserved=['all']) self.auth = AuthAPI(self.db) self.auth.define_tables(username=True, signature=False) # Create a user self.auth.table_user().validate_and_insert(first_name='Bart', last_name='Simpson', username='******', email='*****@*****.**', password='******', registration_key='', registration_id='') self.db.commit() def test_login(self): result = self.auth.login(**{ 'username': '******', 'password': '******' }) self.assertTrue(self.auth.is_logged_in()) self.assertTrue(result['user']['email'] == '*****@*****.**') self.auth.logout() self.assertFalse(self.auth.is_logged_in()) self.auth.settings.username_case_sensitive = False result = self.auth.login(**{ 'username': '******', 'password': '******' }) self.assertTrue(self.auth.is_logged_in()) def test_logout(self): self.auth.login(**{'username': '******', 'password': '******'}) self.assertTrue(self.auth.is_logged_in()) result = self.auth.logout() self.assertTrue(not self.auth.is_logged_in()) self.assertTrue(result['user'] is None) def test_register(self): self.auth.settings.login_after_registration = True result = self.auth.register( **{ 'username': '******', 'first_name': 'Lisa', 'last_name': 'Simpson', 'email': '*****@*****.**', 'password': '******' }) self.assertTrue(result['user']['email'] == '*****@*****.**') self.assertTrue(self.auth.is_logged_in()) with self.assertRaises( AssertionError): # Can't register if you're logged in result = self.auth.register( **{ 'username': '******', 'first_name': 'Lisa', 'last_name': 'Simpson', 'email': '*****@*****.**', 'password': '******' }) self.auth.logout() self.auth.settings.login_after_registration = False result = self.auth.register( **{ 'username': '******', 'first_name': 'Barney', 'last_name': 'Gumble', 'email': '*****@*****.**', 'password': '******' }) self.assertTrue(result['user']['email'] == '*****@*****.**') self.assertFalse(self.auth.is_logged_in()) self.auth.settings.login_userfield = 'email' result = self.auth.register( **{ 'username': '******', 'first_name': 'Lisa', 'last_name': 'Simpson', 'email': '*****@*****.**', 'password': '******' }) self.assertTrue( result['errors']['email'] == self.auth.messages.email_taken) self.assertTrue(result['user'] is None) self.auth.settings.registration_requires_verification = True result = self.auth.register( **{ 'username': '******', 'first_name': 'Homer', 'last_name': 'Simpson', 'email': '*****@*****.**', 'password': '******' }) self.assertTrue('key' in result['user']) def test_profile(self): with self.assertRaises(AssertionError): # We are not logged in self.auth.profile() self.auth.login(**{'username': '******', 'password': '******'}) self.assertTrue(self.auth.is_logged_in()) result = self.auth.profile(email='*****@*****.**') self.assertTrue(result['user']['email'] == '*****@*****.**') self.assertTrue(self.auth.table_user()[result['user']['id']].email == '*****@*****.**') def test_change_password(self): with self.assertRaises(AssertionError): # We are not logged in self.auth.change_password() self.auth.login(**{'username': '******', 'password': '******'}) self.assertTrue(self.auth.is_logged_in()) self.auth.change_password(old_password='******', new_password='******', new_password2='1234') self.auth.logout() self.assertTrue(not self.auth.is_logged_in()) self.auth.login(username='******', password='******') self.assertTrue(self.auth.is_logged_in()) result = self.auth.change_password(old_password='******', new_password='******', new_password2='5678') self.assertTrue('new_password2' in result['errors']) result = self.auth.change_password(old_password='******', new_password='******', new_password2='1234') self.assertTrue('old_password' in result['errors']) # Test the default 4 min_length is enforced on change password result = self.auth.change_password(old_password='******', new_password='******', new_password2='123') self.assertTrue('new_password' in result['errors']) def test_verify_key(self): self.auth.settings.registration_requires_verification = True result = self.auth.register( **{ 'username': '******', 'first_name': 'Homer', 'last_name': 'Simpson', 'email': '*****@*****.**', 'password': '******' }) self.assertTrue('key' in result['user']) homer_id = result['user']['id'] homers_key = result['user']['key'] result = self.auth.verify_key(key=None) self.assertTrue(result['errors'] is not None) result = self.auth.verify_key(key='12345') self.assertTrue(result['errors'] is not None) result = self.auth.verify_key(key=homers_key) self.assertTrue(result['errors'] is None) self.assertEqual(self.auth.table_user()[homer_id].registration_key, '') self.auth.settings.registration_requires_approval = True result = self.auth.register( **{ 'username': '******', 'first_name': 'Lisa', 'last_name': 'Simpson', 'email': '*****@*****.**', 'password': '******' }) lisa_id = result['user']['id'] result = self.auth.verify_key(key=result['user']['key']) self.assertEqual(self.auth.table_user()[lisa_id].registration_key, 'pending')
class TestAuthAPI(unittest.TestCase): def setUp(self): self.request = Request(env={}) self.request.application = 'a' self.request.controller = 'c' self.request.function = 'f' self.request.folder = 'applications/admin' self.response = Response() self.session = Session() T = translator('', 'en') self.session.connect(self.request, self.response) from gluon.globals import current self.current = current self.current.request = self.request self.current.response = self.response self.current.session = self.session self.current.T = T self.db = DAL(DEFAULT_URI, check_reserved=['all']) self.auth = AuthAPI(self.db) self.auth.define_tables(username=True, signature=False) # Create a user self.auth.table_user().validate_and_insert(first_name='Bart', last_name='Simpson', username='******', email='*****@*****.**', password='******', registration_key='', registration_id='' ) self.db.commit() def test_login(self): result = self.auth.login(**{'username': '******', 'password': '******'}) self.assertTrue(self.auth.is_logged_in()) self.assertTrue(result['user']['email'] == '*****@*****.**') self.auth.logout() self.assertFalse(self.auth.is_logged_in()) self.auth.settings.username_case_sensitive = False result = self.auth.login(**{'username': '******', 'password': '******'}) self.assertTrue(self.auth.is_logged_in()) def test_logout(self): self.auth.login(**{'username': '******', 'password': '******'}) self.assertTrue(self.auth.is_logged_in()) result = self.auth.logout() self.assertTrue(not self.auth.is_logged_in()) self.assertTrue(result['user'] is None) def test_register(self): self.auth.settings.login_after_registration = True result = self.auth.register(**{ 'username': '******', 'first_name': 'Lisa', 'last_name': 'Simpson', 'email': '*****@*****.**', 'password': '******' }) self.assertTrue(result['user']['email'] == '*****@*****.**') self.assertTrue(self.auth.is_logged_in()) with self.assertRaises(AssertionError): # Can't register if you're logged in result = self.auth.register(**{ 'username': '******', 'first_name': 'Lisa', 'last_name': 'Simpson', 'email': '*****@*****.**', 'password': '******' }) self.auth.logout() self.auth.settings.login_after_registration = False result = self.auth.register(**{ 'username': '******', 'first_name': 'Barney', 'last_name': 'Gumble', 'email': '*****@*****.**', 'password': '******' }) self.assertTrue(result['user']['email'] == '*****@*****.**') self.assertFalse(self.auth.is_logged_in()) self.auth.settings.login_userfield = 'email' result = self.auth.register(**{ 'username': '******', 'first_name': 'Lisa', 'last_name': 'Simpson', 'email': '*****@*****.**', 'password': '******' }) self.assertTrue(result['errors']['email'] == self.auth.messages.email_taken) self.assertTrue(result['user'] is None) self.auth.settings.registration_requires_verification = True result = self.auth.register(**{ 'username': '******', 'first_name': 'Homer', 'last_name': 'Simpson', 'email': '*****@*****.**', 'password': '******' }) self.assertTrue('key' in result['user']) def test_profile(self): with self.assertRaises(AssertionError): # We are not logged in self.auth.profile() self.auth.login(**{'username': '******', 'password': '******'}) self.assertTrue(self.auth.is_logged_in()) result = self.auth.profile(email='*****@*****.**') self.assertTrue(result['user']['email'] == '*****@*****.**') self.assertTrue(self.auth.table_user()[result['user']['id']].email == '*****@*****.**') def test_change_password(self): with self.assertRaises(AssertionError): # We are not logged in self.auth.change_password() self.auth.login(**{'username': '******', 'password': '******'}) self.assertTrue(self.auth.is_logged_in()) self.auth.change_password(old_password='******', new_password='******', new_password2='1234') self.auth.logout() self.assertTrue(not self.auth.is_logged_in()) self.auth.login(username='******', password='******') self.assertTrue(self.auth.is_logged_in()) result = self.auth.change_password(old_password='******', new_password='******', new_password2='5678') self.assertTrue('new_password2' in result['errors']) result = self.auth.change_password(old_password='******', new_password='******', new_password2='1234') self.assertTrue('old_password' in result['errors']) def test_verify_key(self): self.auth.settings.registration_requires_verification = True result = self.auth.register(**{ 'username': '******', 'first_name': 'Homer', 'last_name': 'Simpson', 'email': '*****@*****.**', 'password': '******' }) self.assertTrue('key' in result['user']) homer_id = result['user']['id'] homers_key = result['user']['key'] result = self.auth.verify_key(key=None) self.assertTrue(result['errors'] is not None) result = self.auth.verify_key(key='12345') self.assertTrue(result['errors'] is not None) result = self.auth.verify_key(key=homers_key) self.assertTrue(result['errors'] is None) self.assertEqual(self.auth.table_user()[homer_id].registration_key, '') self.auth.settings.registration_requires_approval = True result = self.auth.register(**{ 'username': '******', 'first_name': 'Lisa', 'last_name': 'Simpson', 'email': '*****@*****.**', 'password': '******' }) lisa_id = result['user']['id'] result = self.auth.verify_key(key=result['user']['key']) self.assertEqual(self.auth.table_user()[lisa_id].registration_key, 'pending')