def test_login_with_cas(self): token = JwtPrincipal( dict(email='*****@*****.**', title='user2', referenceId=2)).dump().decode() self._authentication_token = token with cas_mockup_server(): settings.merge(f''' oauth: member: url: {settings.tokenizer.url}/apiv1/members verb: get ''') with self.given(title='Try to access an authorized resource', description='Members are got from the cas', url='/apiv1/resources', headers={'X-Oauth2-Access-Token: access token2'}): assert status == 200 mismathc_token = JwtPrincipal( dict(email='*****@*****.**', title='user3', referenceId=3)).dump().decode() when('Token not match the CAS member', authorization=mismathc_token) assert status == 400 when('Try to pass with bad token', authorization='Invalid Token') assert status == 400 when('Try to access an unauthorized resource', authorization=None) assert status == 401 member_token = JwtPrincipal( dict(email='*****@*****.**', title='user1', referenceId=1)).dump().decode() when('Member exist in database', authorization=member_token, headers=Remove('X-Oauth2-Access-Token')) assert status == 200 with cas_server_status('503 Service Not Available'): when('CAS server is not available') assert status == '800 CAS Server Not Available' with cas_server_status('500 Internal Service Error'): when('CAS server faces with internal error') assert status == '801 CAS Server Internal Error' with cas_server_status('404 Not Found'): when('CAS server is not found') assert status == '617 CAS Server Not Found'
def test_root(self): principal = JwtPrincipal(dict( email='*****@*****.**', name='mohammad', family='sheikhian', id=1, sessionId=1, roles=['admin'] )) self.login_token = principal.dump().decode("utf-8") call = dict( title='GET', description='', url='/', verb='GET', autodoc=f'{document_directory}/root_get_with_authorization.md' ) with self.given(**call): then(response.status_code == 200) self.login_token = None call = dict( title='GET', description='', url='/', verb='GET', autodoc=f'{document_directory}/root_get_without_authorization.md' ) with self.given(**call): then(response.status_code == 200) call = dict( title='POST', description='', url='/', verb='POST', form={ 'url': 'www.varzesh3.com' }, autodoc=f'{document_directory}/root_post.md' ) with self.given(**call): then(response.status_code == 200) call = dict( title='POST', description='', url='/', verb='POST', form={} ) with self.given(**call): then(response.status_code == 400)
def test_login(self): call = dict( title='Login', description='Login to system as god', url='/apiv1/members', verb='LOGIN', form={ 'email': '*****@*****.**', 'password': '******', } ) with self.given(**call): then(response.status_code == 200) and_('token' in response.json) principal = JwtPrincipal.load(response.json['token']) and_('sessionId' in principal.payload) when( 'Trying to login with invalid email and_ password', form={ 'email': '*****@*****.**', 'password': '******', } ) then(response.status_code == 400) when( 'Trying to login with invalid password', form={ 'email': '*****@*****.**', 'password': '******', } ) then(response.status_code == 400)
def create_jwt_principal(self, session_id=None): # FIXME: IMPORTANT Include user password as salt in signature if session_id is None: session_id = str(uuid.uuid4()) return JwtPrincipal( dict(id=self.id, roles=self.roles, email=self.email, sessionId=session_id))
def get(self): if(context.query_string.get('code') is None) or \ (client_secret_data['client_id'] is None) or \ (client_secret_data['client_secret'] is None): raise HttpBadRequest body_token = dict() body_token['grant_type'] = 'authorization_code' body_token['code'] = context.query_string.get('code') body_token['client_id'] = client_secret_data['client_id'] body_token['redirect_uri'] = settings.redirect_uri_auth body_token['client_secret'] = client_secret_data['client_secret'] response_token = requests.post(settings.auth_google_uri_token, body_token) if response_token.status_code != 200: raise HttpForbidden() response_get_profile = requests.get( settings.oauth_url_google_api, headers={ 'Authorization': 'OAuth ' + json_library.loads(response_token.text)['access_token'] }) if response_get_profile.status_code != 200: raise HttpNotFound() profile = json_library.loads(response_get_profile.text) if 'refresh_token' in response_token.text: member = Member(given_name=profile['given_name'], family_name=profile['family_name'], email=profile['email'], google_access_token=json_library.loads( response_token.text)['access_token'], google_refresh_token=json_library.loads( response_token.text)['refresh_token']) DBSession.add(member) DBSession.commit() return dict(authorization=JwtPrincipal(profile).dump().decode("utf-8"))
def test_create_user(self): token = JwtPrincipal( dict(email='*****@*****.**', title='user1', referenceId=2)).dump().decode() with cas_mockup_server(), self.given( 'Create a member', '/apiv1/members', 'ENSURE', headers=dict(authorization=token, x_oauth2_access_token='access token1'), form=dict(title='example')): assert status == 200 assert response.json['title'] == 'user1' when('Access token is not in headers', headers=Remove('x_oauth2_access_token')) assert status == 400
async def test_websocket(self, websocket_session, asyncpg): self.login('*****@*****.**') async with websocket_session(token=self._authentication_token) as ws: token = JwtPrincipal.load(self._authentication_token) member_id = self.member.id session_id = token.session_id.encode() member_sessions = await sessions.get_sessions(member_id) assert len(member_sessions) == 1 assert member_sessions == { session_id: b'jaguar_websocket_server_1' } await ws.send_str('close') assert await ws.receive_str() == 'closing' active_sessions = await sessions.get_sessions(member_id) assert len(active_sessions) == 0
def test_principal(): __configuration__ = ''' jwt: secret: JWT-SECRET algorithm: HS256 max_age: 86400 # 24 Hours refresh_token: secret: JWT-REFRESH-SECRET algorithm: HS256 max_age: 2678400 # 30 Days ''' configure(force=True) settings.merge(__configuration__) principal = JwtPrincipal( dict(email='*****@*****.**', id=1, sessionId=1, roles=['admin'])) assert principal.email == '*****@*****.**' assert principal.id == 1 assert principal.session_id == 1 assert principal.roles == ['admin'] assert principal.is_in_roles('admin') is True assert principal.is_in_roles('admin', 'god') is True encoded = principal.dump() principal = JwtPrincipal.load(encoded.decode()) assert principal.email == '*****@*****.**' assert principal.id == 1 assert principal.session_id == 1 assert principal.roles == ['admin'] assert principal.is_in_roles('admin') is True assert principal.is_in_roles('admin', 'god') is True principal = JwtPrincipal.load(encoded.decode(), force=True) assert principal.email == '*****@*****.**' assert principal.id == 1 assert principal.session_id == 1 assert principal.roles == ['admin'] assert principal.is_in_roles('admin') is True assert principal.is_in_roles('admin', 'god') is True principal =\ JwtPrincipal.load((b'Bearer %s' % encoded).decode(), force=True) assert principal.email == '*****@*****.**' assert principal.id == 1 assert principal.session_id == 1 assert principal.roles == ['admin'] assert principal.is_in_roles('admin') is True assert principal.is_in_roles('admin', 'god') is True
def create_principal(self, member_id=None, session_id=None): return JwtPrincipal( dict(id=1, email='*****@*****.**', roles=roles, sessionId='1'))
def test_principal(self): principal = JwtPrincipal( dict(email='*****@*****.**', id=1, sessionId=1, roles=['admin'])) self.assertEqual(principal.email, '*****@*****.**') self.assertEqual(principal.id, 1) self.assertEqual(principal.session_id, 1) self.assertEqual(principal.roles, ['admin']) self.assertTrue(principal.is_in_roles('admin')) self.assertTrue(principal.is_in_roles('admin', 'god')) encoded = principal.dump() principal = JwtPrincipal.load(encoded.decode()) self.assertEqual(principal.email, '*****@*****.**') self.assertEqual(principal.id, 1) self.assertEqual(principal.session_id, 1) self.assertEqual(principal.roles, ['admin']) self.assertTrue(principal.is_in_roles('admin')) self.assertTrue(principal.is_in_roles('admin', 'god')) principal = JwtPrincipal.load(encoded.decode(), force=True) self.assertEqual(principal.email, '*****@*****.**') self.assertEqual(principal.id, 1) self.assertEqual(principal.session_id, 1) self.assertEqual(principal.roles, ['admin']) self.assertTrue(principal.is_in_roles('admin')) self.assertTrue(principal.is_in_roles('admin', 'god')) principal = JwtPrincipal.load((b'Bearer %s' % encoded).decode(), force=True) self.assertEqual(principal.email, '*****@*****.**') self.assertEqual(principal.id, 1) self.assertEqual(principal.session_id, 1) self.assertEqual(principal.roles, ['admin']) self.assertTrue(principal.is_in_roles('admin')) self.assertTrue(principal.is_in_roles('admin', 'god'))
def create_jwt_principal(self): return JwtPrincipal(dict(id=self.id, email=self.email, name=self.title))
def __call__(self, args): payload = ujson.loads(args.payload) print(JwtPrincipal(payload).dump(args.expire_in).decode())
def verify_token(self, encoded_token): return JwtPrincipal.load(encoded_token)
def launch(self): payload = ujson.loads(self.args.payload) print(JwtPrincipal(payload).dump(self.args.expire_in).decode())