def testSetAPIToken(self): result = connection.execute(auth_user_table.insert({'email': 'a'})) user_id = result.inserted_primary_key[0] token = generate_api_token() connection.execute(set_api_token(token=token, auth_user_id=user_id)) user = get_auth_user(connection, user_id) self.assertTrue(bcrypt_sha256.verify(token, user.token))
def testTokenExpires(self): result = connection.execute(auth_user_table.insert({'email': 'a'})) user_id = result.inserted_primary_key[0] token = generate_api_token() exp = timedelta(hours=1) connection.execute( set_api_token(token=token, auth_user_id=user_id, expiration=exp)) self.assertTrue( verify_api_token(connection, token=token, email='a')) token2 = generate_api_token() exp2 = timedelta(hours=-1) connection.execute(set_api_token( token=token2, auth_user_id=user_id, expiration=exp2)) self.assertFalse( verify_api_token(connection, token=token2, email='a'))
def testVerifyAPIToken(self): result = connection.execute(auth_user_table.insert({'email': 'a'})) user_id = result.inserted_primary_key[0] token = generate_api_token() connection.execute(set_api_token(token=token, auth_user_id=user_id)) self.assertTrue( verify_api_token(connection, token=token, email='a')) self.assertFalse( verify_api_token(connection, token=generate_api_token(), email='a'))
def generate_token(connection: Connection, data: dict) -> dict: """ Generates a new API token for a user specified by e-mail address. You can supply a duration in seconds. :param connection: a SQLAlchemy Connection :param data: the user's e-mail and an optional duration :return: the generated token and the token's expiration time """ user = get_auth_user_by_email(connection, data['email']) token = generate_api_token() params = {'token': token, 'auth_user_id': user.auth_user_id} if 'duration' in data: duration = float(data['duration']) if duration > 31536000: raise TokenDurationTooLong(data['duration']) params['expiration'] = timedelta(seconds=duration) with connection.begin(): connection.execute(set_api_token(**params)) updated_user = get_auth_user_by_email(connection, data['email']) return json_response( {'token': token, 'expires_on': updated_user.expires_on.isoformat()})