Exemple #1
0
    def test_get_csv_should_return_200_when_correct_authorization_and_have_data_for_user_id_and_status_is_true_when_have_data(self):
        token = generate_jwt(self.user_id)

        data_id = 1
        keyword = "test-keyword"
        total_adword = 1
        total_link = 1
        total_search_result = "about 1,000"
        html_code = "test-html-code"

        new_data = Data(
            file_id = self.file_id,
            id = data_id,
            keyword = keyword,
            total_adword = total_adword,
            total_link = total_link,
            total_search_result = total_search_result,
            html_code = html_code
        )
        self.db_session.add(new_data)
        self.db_session.commit()

        with app.test_client() as client:
            result = client.get(
                '/csv',
                headers={"Authorization": token}
            )
            assert result.status_code == 200

            expected_result = [
                [self.file_id, self.filename, self.keywords, ANY, True]
            ]
            assert json.loads(result.data) == expected_result
Exemple #2
0
async def authenticate(token: IDToken):
    #1. validate google's id_token
    token = token.dict()["google_id_token"]
    try:
        google_id_info = id_token.verify_oauth2_token(token, requests.Request(), GOOGLE_CLIENT_ID)
        google_id = google_id_info["sub"]
        google_name = google_id_info["name"]
    except ValueError:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN, detail="Could not validate token"
        )
    #2. look up user id in db
    user = dataservice.find_user_by_google_id(google_id)
    if user is None:
        user_id = dataservice.create_new_user(google_id, google_name)
    else:
        user_id = user["_id"]
    #3. store jwt token in httpOnly cookie with samesite=lax
    access_token = generate_jwt({"sub": str(user_id), "iss": "ispend", "scope": "full"}, JWT_SECRET_KEY, JWT_ALGORITHM)
    response = JSONResponse({"login_success": True})
    response.set_cookie(
        key=COOKIE_NAME,
        value=f"Bearer {access_token}",
        domain=COOKIE_DOMAIN,
        httponly=True,
        max_age=15*60,
        expires=15*60,
        samesite="lax",
    )
    #response.headers["Access-Control-Allow-Origin"] = "http://localhost:8080"
    #response.headers["Access-Control-Allow-Credentials"] = "True"
    response.headers["Access-Control-Allow-Headers"] = "Origin, X-Requested-With, Content-Type, Accept"
    return response
    async def login(**kwargs):
        """
        :param kwargs:
        address: "hxbe258ceb872e08851f1f59694dac2558708ece11",
        signature: "VAia7YZ2Ji6igKWzjR2YsGa2m53nKPrfK7uXYW78QLE+ATehAVZPC40szvAiA6NEU5gCYB4c4qaQzqDh2ugcHgA="
        :return:
        result: "0x48757af881f76c858890fb41934bee228ad50a71707154a482826c39b8560d4b"
        """
        address = kwargs.get('address')
        signature = kwargs.get('signature')

        address_bytes = bytes.fromhex(address[2:])
        sign_bytes = base64.b64decode(signature.encode('utf-8'))

        await utils.verify_signature(address_bytes=address_bytes,
                                     random_bytes=USERS_RANDOM[address_bytes],
                                     sign_bytes=sign_bytes,
                                     private_key=PRIVATE_KEY)

        token = utils.generate_jwt(address)
        if address in db_manager.get_addresses():
            db_manager.update_token(address, token)
        else:
            db_manager.add_user(address, token)
        return token
Exemple #4
0
 def test_get_csv_should_return_404_when_correct_authorization_but_no_data_for_user_id(self):
     user_id = 2
     token = generate_jwt(user_id)
     with app.test_client() as client:
         result = client.get(
             '/csv',
             headers={"Authorization": token}
         )
         assert result.status_code == 404
Exemple #5
0
def login():
    if request.method == 'POST':
        request_body = request.json
        result = User.query.with_entities(
            User.id,
            User.password).filter(User.email == request_body["email"]).first()
        if not result or not check_password_hash(result[1],
                                                 request_body["password"]):
            return "Email or Password incorrect", 400
        return generate_jwt(result[0]), 200
Exemple #6
0
    def test_get_csv_should_return_200_when_correct_authorization_and_have_data_for_user_id_and_status_is_false_when_no_data(self):
        token = generate_jwt(self.user_id)
        with app.test_client() as client:
            result = client.get(
                '/csv',
                headers={"Authorization": token}
            )
            assert result.status_code == 200

            expected_result = [
                [self.file_id, self.filename, self.keywords, ANY, False]
            ]
            assert json.loads(result.data) == expected_result
Exemple #7
0
def user():
    if request.method == 'POST':
        request_body = request.json
        result = User.query.with_entities(
            User.id).filter(User.email == request_body["email"]).first()
        if result:
            return "Email already exist", 400
        new_user = User(email=request_body["email"],
                        password=generate_password_hash(
                            request_body["password"], method='sha256'))
        db_session.add(new_user)
        db_session.commit()
        return generate_jwt(new_user.id), 201
def test_authenticate_invalid_audience(client, jwks):
    claims = {'iss': ISSUER, 'aud': 'invalid'}

    token = utils.generate_jwt(claims)
    headers['Authorization'] = 'Bearer ' + token
    post = schemas.PostSchema().dumps({"id": "420"}).data

    with requests_mock.Mocker() as mock:
        mock.get(current_app.config['JWKS_URL'], json=jwks)
        resp = client.post(url_for('api.posts_list'),
                           headers=headers,
                           data=post)

    assert resp.status_code == 401
    assert 'Invalid audience' in resp.json['errors'][0]['detail']
Exemple #9
0
    def test_post_csv_should_return_200_when_correct_authorization(self):
        self.cur.execute("""
            DELETE FROM data;
            DELETE FROM file;
        """)
        self.cnx.commit()

        token = generate_jwt(self.user_id)
        body = {
            "filename": self.filename,
            "keywords": [1, 2, 3, 4]
        }
        with app.test_client() as client:
            result = client.post(
                '/csv',
                headers={"Authorization": token},
                json=body
            )
            assert result.status_code == 200
def headers():
    now = (datetime.utcnow() - datetime(1970, 1, 1))
    exp_at = now + timedelta(seconds=690000)

    claims = {
        'iss': 'issuer',
        'aud': 'api audience',
        'sub': '36420',
        'iat': now.total_seconds(),
        'exp': exp_at.total_seconds()
    }

    token = utils.generate_jwt(claims)
    _headers = {
        'Accept': 'application/vnd.api+json',
        'Content-Type': 'application/vnd.api+json',
        'Authorization': 'Bearer ' + token
    }
    return _headers
def test_authenticate(client):
    now = (datetime.utcnow() - datetime(1970, 1, 1))
    exp_at = now + timedelta(seconds=69)

    claims = {
        'iss': ISSUER,
        'aud': API_AUDIENCE,
        'sub': '696969',
        'iat': now.total_seconds(),
        'exp': exp_at.total_seconds()
    }

    token = utils.generate_jwt(claims)
    headers['Authorization'] = 'Bearer ' + token
    user = schemas.UserSchema().dumps({
        "id": "420",
        "username": "******",
    }).data

    with requests_mock.Mocker() as mock:
        mock.get(current_app.config['JWKS_URL'], json=JWKS)
        resp = client.post(url_for('api.users_list'),
                           headers=headers,
                           data=user)

    assert resp.status_code == 201
    user = schemas.UserSchema().load(resp.json).data
    assert user['id'] != 420
    assert user['user_id'] == '696969'
    resp = client.get(url_for('api.users_likes', id=1), headers=headers)

    assert resp.status_code == 200

    # THEN WE GOTTA DELETE IT
    # Defs gotta sort this db.session issue out
    resp = client.delete(url_for('api.users_detail', id=user['id']),
                         headers=headers)
    assert resp.status_code == 200
def test_authenticate_expired_token(client, jwks):
    now = (datetime(1971, 1, 1) - datetime(1970, 1, 1))
    exp_at = now + timedelta(seconds=0)

    claims = {
        'iss': ISSUER,
        'aud': API_AUDIENCE,
        'sub': '6969',
        'iat': now.total_seconds(),
        'exp': exp_at.total_seconds()
    }

    token = utils.generate_jwt(claims)
    headers['Authorization'] = 'Bearer ' + token
    post = schemas.PostSchema().dumps({"id": "420"}).data
    with requests_mock.Mocker() as mock:
        mock.get(current_app.config['JWKS_URL'], json=jwks)
        resp = client.post(url_for('api.posts_list'),
                           headers=headers,
                           data=post)

    assert resp.status_code == 401
    assert 'Signature has expired.' in resp.json['errors'][0]['detail']
Exemple #13
0
    def test_login(self):
        # test login_hash
        response = http_client.request(method_name='login_hash', address=test_address)
        result = json.loads(response.text)['result']
        random_bytes = bytes.fromhex(result[2:])
        random_result_example = '0x9aa0330713174af486fb46144ed479bbee6054d448e6484d86e7507c780779b4'

        self.assertNotEqual(result, random_result_example)
        self.assertEqual(len(result), 66)

        # test login
        signature_base64str = utils.sign(PRIVATE_KEY, random_bytes)
        response = http_client.request(method_name='login', address=test_address, signature=signature_base64str)
        result = json.loads(response.text)['result']

        token = utils.generate_jwt(test_address)

        self.assertEqual(result, token)

        # test set_nickname
        response = http_client.request(method_name='set_nickname', token=token, nickname='june')
        user_data = requests.get(CONFIG.http_uri + '/db').json()
        nickname = user_data[test_address]['nickname']

        self.assertEqual(nickname, 'june')

        # test login again and nickname remains
        response = http_client.request(method_name='login_hash', address=test_address)
        random_result = json.loads(response.text)['result']
        random_bytes = bytes.fromhex(random_result[2:])
        signature_base64str = utils.sign(PRIVATE_KEY, random_bytes)
        response = http_client.request(method_name='login', address=test_address, signature=signature_base64str)
        nickname_response = http_client.request(method_name='get_nickname', token=token)
        nickname = json.loads(nickname_response.text)['result']

        self.assertEqual(nickname, 'june')
def test_create_post_with_tags(client):
    now = (datetime.utcnow() - datetime(1970, 1, 1))
    exp_at = now + timedelta(seconds=69)

    claims = {
        'iss': ISSUER,
        'aud': API_AUDIENCE,
        'sub': '696969',
        'iat': now.total_seconds(),
        'exp': exp_at.total_seconds()
    }

    token = utils.generate_jwt(claims)
    headers['Authorization'] = 'Bearer ' + token
    tag = schemas.TagSchema().dumps({'id': '1', 'name': 'test_tag'}).data

    post = schemas.PostSchema().dumps({
        "id": "420",
        "title": "uh oh",
        "tags": [{
            'type': 'tags',
            'id': '1'
        }]
    }).data

    with requests_mock.Mocker() as mock:
        mock.get(current_app.config['JWKS_URL'], json=JWKS)
        resp = client.post(url_for('api.tags_list'), headers=headers, data=tag)
        assert resp.status_code == 201
        tag = schemas.TagSchema().load(resp.json).data

        resp = client.post(url_for('api.posts_list') + '?include=tags',
                           headers=headers,
                           data=post)
        assert resp.status_code == 201
        post = schemas.PostSchema().load(resp.json).data

        resp = client.get('/api/posts/{}'.format(post['id']), headers=headers)
        assert resp.status_code == 200
        resp = client.get('/api/posts/{}/tags'.format(post['id']),
                          headers=headers)
        assert resp.status_code == 200
        resp = client.get('/api/posts/{}/relationships/tags'.format(
            post['id']),
                          headers=headers)
        assert resp.status_code == 200

        resp = client.delete(url_for('api.posts_detail', id=post['id']),
                             headers=headers)
        assert resp.status_code == 200

        resp = client.delete(url_for('api.tags_detail', id=tag['id']),
                             headers=headers)
        assert resp.status_code == 200


# def test_delete_post(client):
#     now = (datetime.utcnow() - datetime(1970, 1, 1))
#     exp_at = now + timedelta(seconds=69)

#     claims = {
#         'iss': ISSUER,
#         'aud': API_AUDIENCE,
#         'sub': '696969',
#         'iat': now.total_seconds(),
#         'exp': exp_at.total_seconds()
#     }

#     token = utils.generate_jwt(claims)
#     headers['Authorization'] = 'Bearer ' + token

#     with requests_mock.Mocker() as mock:
#         mock.get(current_app.config['JWKS_URL'], json=JWKS)
#         resp = client.delete(url_for('api.posts_detail', id=2), headers=headers)
#         assert resp.status_code == 200

#         resp = client.get('/api/posts/2', headers=headers)
#         assert resp.status_code == 404
 def test_generate_jwt_should_generate_correctly(self):
     result = generate_jwt("*****@*****.**")
     assert result == b"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ0ZXN0QGVtYWlsLmNvbSJ9.LoWRlX0n5tcoif-uvhodG52GXF4ZTSYPZezT3dj7BTU"
Exemple #16
0
 def get_token(self):
     return generate_jwt({'name': self.name},
                         expiry=datetime.datetime.now() +
                         datetime.timedelta(minutes=30))