Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from django.contrib.auth import authenticate, login, logout
- from django.utils.decorators import method_decorator
- from django.views.decorators.csrf import csrf_exempt
- from django.shortcuts import render_to_response
- from django.views.generic import View
- from django.http.response import HttpResponse, HttpResponseRedirect
- from django.template import RequestContext
- from django.contrib.auth.models import User
- from posts.views import JsonResponseMixin, DataError
- from .forms import RegistrationForm
- # Create your views here.
- class LoginView(JsonResponseMixin, View):
- def get_context_data(self, request, *args, **kwargs):
- try:
- data = json.loads(request.body.decode('utf-8'))
- username = data['login']
- password = data['password']
- except KeyError:
- raise DataError
- user = authenticate(username=username, password=password)
- if user is not None and user.is_active:
- login(request, user)
- return [{'login': username}]
- else:
- raise DataError
- @method_decorator(csrf_exempt)
- def dispatch(self, request, *args, **kwargs):
- return super(LoginView, self).dispatch(request, *args, **kwargs)
- class CheckLoginView(JsonResponseMixin, View):
- def get_context_data(self, request, *args, **kwargs):
- if request.user.is_authenticated():
- return {'isLogined': True, 'username': request.user.username}
- else:
- return {'isLogined': False}
- @method_decorator(csrf_exempt)
- def dispatch(self, request, *args, **kwargs):
- return super(CheckLoginView, self).dispatch(request, *args, **kwargs)
- class LogoutView(View):
- def get(self, request, *args, **kwargs):
- if request.user.is_authenticated():
- logout(request)
- return HttpResponse()
- class RegisterView(View):
- def get(self, request, *args, **kwargs):
- form = RegistrationForm()
- context = RequestContext(request, {'form': form})
- return render_to_response("registration.html", context,)
- def post(self, request, *args, **kwargs):
- print(request.body)
- form = RegistrationForm(request.POST)
- print(form)
- if form.is_valid():
- user = User.objects.create_user(
- username=form.cleaned_data['username'],
- password=form.cleaned_data['password1'],
- email=form.cleaned_data['email']
- )
- user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password1'])
- login(request, user)
- return HttpResponseRedirect('/')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement