from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from django.contrib.auth.decorators import login_required
from .forms import ExtendedUserCreationForm


def register(request):
    if request.method == 'POST':
        form = ExtendedUserCreationForm(request.POST)
        if form.is_valid():
            form.save()
            # Auto login after register successfully
            user = authenticate(request, username=form.cleaned_data.get('username'),
                                password=form.cleaned_data.get('password1'))
            if user is not None:
                login(request, user)
                return redirect('index')
    else:
        form = ExtendedUserCreationForm()
    return render(request, 'user_profile/register.html', {'form': form})


@login_required
def profile(request):
    return render(request, 'user_profile/profile.html')
