Commit f0ded919 authored by Florent Chehab's avatar Florent Chehab

REST API added

parent 20433b20
Pipeline #22006 passed with stage
in 1 minute and 15 seconds
API
========
Il n'y a rien dans cette section, mais ça va arriver :kissing:.
\ No newline at end of file
## Accès
L'API du site est accessible à l'adresse `/api`.
La documentation de l'API est accessible à l'adresse `/api-docs`.
## Authentification
Il existe deux modes d'authentification pour l'API.
Dans les deux cas, les réponses de l'API dépendront des droits associés à l'utilisateur.
### Session
Il s'agit du mode d'authentification automatiquement utilisé lorsque vous naviguez sur le site.
Il faut s'être connecté au CAS avant : `/user/login`.
### Token
Dans de rares cas, un token unique peut être associé à un utilisateur. Dans ce cas, la seule présence de ce token dans la requête est suffisant pour l'authentification. Exemple :
```bash
curl -X GET http://127.0.0.1:8000/api/country/ -H 'Authorization: Token MonTokenRandomSuperLong'
```
La génération du token se fait dans l'administration du site pour l'instant : `/admin`.
from rest_framework.authtoken.admin import TokenAdmin
# Pour la génération de token dans l'administration du site.
TokenAdmin.raw_id_fields = ('user',)
......@@ -4,9 +4,10 @@ from django.http import HttpResponseRedirect
from django.conf import settings
from re import compile
EXEMPT_URLS = [compile(settings.LOGIN_URL.lstrip('/'))]
EXEMPT_URLS = []
if hasattr(settings, 'LOGIN_EXEMPT_URLS'):
EXEMPT_URLS += [compile(expr) for expr in settings.LOGIN_EXEMPT_URLS]
EXEMPT_URLS += [compile(str.lstrip('/'))
for str in settings.LOGIN_EXEMPT_URLS]
class LoginRequiredMiddleware(MiddlewareMixin):
......
......@@ -29,6 +29,8 @@ INSTALLED_APPS = [
'django_cas_ng',
'reversion',
'reversion_compare',
'rest_framework',
'rest_framework.authtoken',
'main_website',
'rex'
]
......@@ -44,8 +46,10 @@ MIDDLEWARE = [
'general.middleware.LoginRequiredMiddleware',
]
LOGIN_URL = '/accounts/login'
# TODO add ignore administration
LOGIN_URL = '/user/login'
LOGIN_EXEMPT_URLS = [LOGIN_URL,
'/admin/',
'api']
AUTHENTICATION_BACKENDS = [
'django.contrib.auth.backends.ModelBackend',
......@@ -60,6 +64,17 @@ CAS_RENAME_ATTRIBUTES = {
'sn': 'last_name'
}
REST_FRAMEWORK = {
# Use Django's standard `django.contrib.auth` permissions,
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.DjangoModelPermissions',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication',
)
}
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
ROOT_URLCONF = 'general.urls'
......
......@@ -7,13 +7,13 @@ import django_cas_ng.views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^accounts/login$',
url(r'^user/login$',
django_cas_ng.views.login,
name='cas_ng_login'),
url(r'^accounts/logout$',
url(r'^user/logout$',
django_cas_ng.views.logout,
name='cas_ng_logout'),
url(r'^accounts/callback$',
url(r'^user/callback$',
django_cas_ng.views.callback,
name='cas_ng_proxy_callback'),
url(r'', include('rex.urls')),
......
......@@ -4,6 +4,10 @@ django_heroku==0.3.1
gunicorn==19.7.1
psycopg2-binary==2.7.4
git+https://github.com/mingchen/django-cas-ng.git@23e755c61d58c957a056c7a321272ab5888797a9#egg=django-cas-ng
djangorestframework==3.8.2 # Django REST Framework
markdown==2.6.11 # Complement for Django REST framework
django-filter==1.1.0 # Support filter in REST API
coreapi==2.3.3 # Automatic API doc generation
Pillow==5.0.0
django-imagekit==4.0.2
django-reversion==2.0.13
......
from .country import Country # noqa: F401
from .country import Country, CountryViewSet, CountrySerializer # noqa: F401
from django.db import models
from rest_framework import serializers, viewsets, permissions
class Country(models.Model):
name = models.CharField(max_length=200)
iso_code = models.CharField(primary_key=True, max_length=2)
class CountrySerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Country
fields = ('name', 'iso_code', 'url')
class CountryViewSet(viewsets.ModelViewSet):
"""
retrieve:
Retourne un pays.
list:
Retourne une liste de pays.
create:
Créée un nouveau pays.
"""
permission_classes = (permissions.DjangoModelPermissions,)
queryset = Country.objects.all() # noqa: E1101
serializer_class = CountrySerializer
from django.conf.urls import url
from . import views
from django.conf.urls import url, include
from rex import views
from rest_framework import routers
from rex.models.country import CountryViewSet
from rest_framework.documentation import include_docs_urls
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^api-docs/', include_docs_urls(title='Outgoing API'))
]
router = routers.DefaultRouter()
router.register(r'country', CountryViewSet)
urlpatterns += [url(r'^api/', include(router.urls))]
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment