From 6fc34786901d8d3b6ac1daf4369fe5ccac2363c4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexis=20M=C3=A9taireau?= Date: Tue, 25 Dec 2018 17:29:27 +0100 Subject: [PATCH] Add CORS to the API. Fix #404 --- CHANGELOG.rst | 2 +- ihatemoney/api.py | 2 ++ ihatemoney/tests/tests.py | 10 ++++++++++ requirements.txt | 1 + 4 files changed, 14 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.rst b/CHANGELOG.rst index b1842037..6c55e7ff 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -6,7 +6,7 @@ This document describes changes between each past release. 3.1 (unreleased) ---------------- -- Nothing changed yet. +- Add CORS headers in the API (#407) 3.0 (2018-11-25) diff --git a/ihatemoney/api.py b/ihatemoney/api.py index 6068cf72..c9c5376b 100644 --- a/ihatemoney/api.py +++ b/ihatemoney/api.py @@ -1,6 +1,7 @@ # -*- coding: utf-8 -*- from flask import Blueprint, request from flask_restful import Resource, Api, abort +from flask_cors import CORS from wtforms.fields.core import BooleanField from ihatemoney.models import db, Project, Person, Bill @@ -11,6 +12,7 @@ from functools import wraps api = Blueprint("api", __name__, url_prefix="/api") +CORS(api) restful_api = Api(api) diff --git a/ihatemoney/tests/tests.py b/ihatemoney/tests/tests.py index f3687809..17b3a8d9 100644 --- a/ihatemoney/tests/tests.py +++ b/ihatemoney/tests/tests.py @@ -1020,6 +1020,16 @@ class APITestCase(IhatemoneyTestCase): ('%s:%s' % (username, password)).encode('utf-8')).decode('utf-8').replace('\n', '') return {"Authorization": "Basic %s" % base64string} + def test_cors_requests(self): + # Create a project and test that CORS headers are present if requested. + resp = self.api_create("raclette") + self.assertStatus(201, resp) + + # Try to do an OPTIONS requests and see if the headers are correct. + resp = self.client.options("/api/projects/raclette", + headers=self.get_auth("raclette")) + self.assertEqual(resp.headers['Access-Control-Allow-Origin'], '*') + def test_basic_auth(self): # create a project resp = self.api_create("raclette") diff --git a/requirements.txt b/requirements.txt index f61c9b93..09221f58 100644 --- a/requirements.txt +++ b/requirements.txt @@ -8,6 +8,7 @@ flask-babel flask-restful>=0.3.6 jinja2>=2.6 blinker +flask-cors six>=1.10 itsdangerous>=0.24 email_validator>=1.0