from django.http import request
from django.shortcuts import redirect, render
from django.contrib.auth.models import User
from django.contrib import auth

def signup(request):
    if request.method == "POST":
        if request.POST['password']== request.POST['password2']:
            user=User.objects.create_user(
                request.POST['username'],password=request.POST['password'])
            auth.login(request,user)
            return redirect('/main')
    return render(request, 'blog/signup.html')

def login_request(request):
    if request.method == "POST":
        username=request.POST['username']
        password=request.POST['password']
        user=auth.authenticate(request, username=username, password=password)
        if user is not None:
            auth.login(request, user)
            return redirect('/main')
        else:
            return render(request,'blog/login.html', {'error':'username or password is incorrect'})
    else:
        return render(request, 'blog/login.html')

def logout_request(request):
    if request.method == 'POST':
        auth.logout(request)
        return redirect('/')
    return redirect('/')
