Django Registration 구현

Registration Form 만들기

Django Allauth 설치

$ git clone git://github.com/pennersr/django-allauth.git
$ cd django-allauth/example
$ virtualenv venv
$ . venv/bin/activate
$ pip install -r requirements.txt
$ python manage.py syncdb

URL 설정하기

urlpatterns = patterns('',
                       (r'^accounts/', include('allauth.urls')),
                       ...
)

SMTP 서버 테스트하기

$ python -m smtpd -n -c DebuggingServer localhost:1025
EMAIL_HOST='localhost'
EMAIL_PORT=1025
EMAIL_HOST_USER=''
EMAIL_HOST_PASSWORD=''

Real SMTP 서버 설정하기

$ pip install django-smtp-ssl
EMAIL_BACKEND = 'django_smtp_ssl.SSLEmailBackend'
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.daum.net'
EMAIL_PORT = 465
EMAIL_HOST_USER = 'ADMIN_ID'
EMAIL_HOST_PASSWORD = 'ADMIN_PASSWORD'
DEFAULT_FROM_EMAIL = 'Verified-email <admin@localhost>'

SSL을 사용하는 SMTP 서버는 django.core.mail.backends.smtp.EmailBackend를 사용하면 동작하지 않았음.

실행하기

$ python manage.py runserver

여기까지 진행하면, 기본적인 회원 Registration, Login은 가능함.


JWT(JSON Web Token) 설정

설치하기

$ pip install djangorestframework
$ pip install djangorestframework-jwt

설정하기

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
    ),
}
INSTALLED_APPS = (
  ...
  'rest_framework',
  ...
)
from django.contrib.auth.models import User
from rest_framework import routers, serializers, viewsets

# Serializers define the API representation.
class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ('url', 'username', 'email', 'is_staff')

# ViewSets define the view behavior.
class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

# Routers provide an easy way of automatically determining the URL conf.
router = routers.DefaultRouter()
router.register(r'users', UserViewSet)
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^api-token-auth/', 'rest_framework_jwt.views.obtain_jwt_token'),
url(r'^api-token-refresh/', 'rest_framework_jwt.views.refresh_jwt_token'),
url(r'^api-token-verify/', 'rest_framework_jwt.views.verify_jwt_token'),

테스트하기

Login.

$ curl -X POST -H "Content-Type: application/json" -d '{"username":"admin","password":"admin"}' http://127.0.0.1:8000/api-token-auth/
{"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwidXNlcl9pZCI6MSwiZW1haWwiOiJhZG1pbkBuYXZlci5jb20iLCJleHAiOjE0MzU1MDY3NzF9.dsqiJDuJPCifRm0wt3qCdgQnuZSZYvIDeZQmCH62D1A"}%

Token Verification

$ curl -X POST -H "Content-Type: application/json" -d '{"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwidXNlcl9pZCI6MSwiZW1haWwiOiJhZG1pbkBuYXZlci5jb20iLCJleHAiOjE0MzU1MDY3NzF9.dsqiJDuJPCifRm0wt3qCdgQnuZSZYvIDeZQmCH62D1A"}' http://127.0.0.1:8000/api-token-verify/

접근 제한된 URL 추가하기.

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated

from rest_framework_jwt.authentication import JSONWebTokenAuthentication

class RestrictedView(APIView):
    permission_classes = (IsAuthenticated, )
    authentication_classes = (JSONWebTokenAuthentication, )

    def get(self, request):
        data = {
            'id': request.user.id,
            'username': request.user.username,
            'token': str(request.auth)
        }
        return Response(data)

from example.demo.views import RestrictedView
...
urlpatterns = patterns('',
  ...
  url(r'^restricted/$', RestrictedView.as_view()),
  ...
)
$ curl -H "Authorization: JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwidXNlcl9pZCI6MSwiZW1haWwiOiJhZG1pbkBuYXZlci5jb20iLCJleHAiOjE0MzU1MDgwNjJ9.Zd9MSdA41HYJTAjW7JEMsK3TUv5EYXAj5X0S1IdKwFY" http://127.0.0.1:8000/restricted/


참고

Django-Rest-Auth

Django-Rest-Auth with AngularJS

사이트
- AngularJS와 Django-Rest-Auth를 결합한 샘플 프로젝트

참고 : CORS 오류(Access-Control-Allow-Origin) 발생시.
- settings.py에 추가

CORS_ORIGIN_ALLOW_ALL = True
INSTALLED_APPS = (
...
'corsheaders',
...
)
MIDDLEWARE_CLASSES = (
...
'corsheaders.middleware.CorsMiddleware',
...
)