# Path: apps/auth/models.py
# class KipptUser(AbstractUser):
#     """
#     Defines our custom user model and fields
# 
#     """
#     api_token = models.CharField(max_length=255)
#     list_id = models.IntegerField(blank=True, null=True)
# 
#     def __unicode__(self):
#         return self.username
# 
#     def kippt_client(self):
#         return Kippt(self.username, api_token=self.api_token)
# 
# Path: apps/auth/forms.py
# class KipptUserConnectForm(forms.ModelForm):
# 
#     class Meta:
#         model = KipptUser
#         fields = ('username', 'password')
# 
#     def __init__(self, *args, **kwargs):
#         super(KipptUserConnectForm, self).__init__(*args, **kwargs)
# 
#         self.fields['username'].label = 'Kippt Username'
#         self.fields['username'].help_text = ''
#         self.fields['password'].label = 'Kippt Password or API Token'
#         self.fields['password'].widget = forms.PasswordInput()
# 
#     def clean(self):
#         username = self.cleaned_data.get('username')
#         password = self.cleaned_data.get('password')
# 
#         kippt = Kippt(username, password=password)
#         user = kippt.account()
# 
#         if 'message' in user:
#             kippt = Kippt(username, api_token=password)
#             user = kippt.account()
# 
#             if 'message' in user:
#                 raise forms.ValidationError(user['message'])
# 
#         self.cleaned_data['api_token'] = user['api_token']
# 
#         return self.cleaned_data
# 
#     def save(self, commit=True):
#         user, created = KipptUser.objects.get_or_create(
#             username=self.cleaned_data['username'],
#         )
# 
#         user.api_token = self.cleaned_data['api_token']
#         user.save()
# 
#         if created:
#             user.set_password(None)
# 
#         return user, created
# 
# class KipptUserSetupForm(forms.ModelForm):
#     list_id = forms.ChoiceField(label='Default list')
# 
#     class Meta:
#         model = KipptUser
#         fields = ('list_id',)
# 
#     def __init__(self, *args, **kwargs):
#         super(KipptUserSetupForm, self).__init__(*args, **kwargs)
# 
#         kippt = self.instance.kippt_client()
#         meta, lists = kippt.lists()
# 
#         LIST_CHOICES = [('', 'Choose a list to store feed items')]
# 
#         for kippt_list in lists:
#             LIST_CHOICES.append((kippt_list['id'], kippt_list['title']))
# 
#         self.fields['list_id'].choices = LIST_CHOICES


from django.views.generic import CreateView, UpdateView
from django.contrib.auth import authenticate, login
from django.core.urlresolvers import reverse_lazy, reverse
from django.shortcuts import redirect
from braces.views import LoginRequiredMixin
from .models import KipptUser
from .forms import KipptUserConnectForm, KipptUserSetupForm
        context = super(ConnectView, self).get_context_data(**kwargs)
        feeds_create = self.request.build_absolute_uri(reverse('feeds_create'))
        context['subtome_url'] = '{}?feed={{feed}}&source=subtome'.format(feeds_create)
        return context

    def get(self, request, *args, **kwargs):
        if request.user.is_authenticated():
            return redirect(reverse_lazy('feeds_list'))

        return super(ConnectView, self).get(request, *args, **kwargs)

    def form_valid(self, form):
        obj, created = form.save()
        user = authenticate(username=obj.username, api_token=obj.api_token)

        if user is not None:
            login(self.request, user)

        redirect_to = self.request.GET.get('next')

        if created:
            redirect_to = reverse_lazy('auth_setup')
        elif not redirect_to:
            redirect_to = reverse_lazy('feeds_list')

        return redirect(redirect_to)


class SetupView(LoginRequiredMixin, UpdateView):
    model = KipptUser

# Path: apps/auth/models.py
# class KipptUser(AbstractUser):
#     """
#     Defines our custom user model and fields
# 
#     """
#     api_token = models.CharField(max_length=255)
#     list_id = models.IntegerField(blank=True, null=True)
# 
#     def __unicode__(self):
#         return self.username
# 
#     def kippt_client(self):
#         return Kippt(self.username, api_token=self.api_token)
# 
# Path: apps/auth/forms.py
# class KipptUserConnectForm(forms.ModelForm):
# 
#     class Meta:
#         model = KipptUser
#         fields = ('username', 'password')
# 
#     def __init__(self, *args, **kwargs):
#         super(KipptUserConnectForm, self).__init__(*args, **kwargs)
# 
#         self.fields['username'].label = 'Kippt Username'
#         self.fields['username'].help_text = ''
#         self.fields['password'].label = 'Kippt Password or API Token'
#         self.fields['password'].widget = forms.PasswordInput()
# 
#     def clean(self):
#         username = self.cleaned_data.get('username')
#         password = self.cleaned_data.get('password')
# 
#         kippt = Kippt(username, password=password)
#         user = kippt.account()
# 
#         if 'message' in user:
#             kippt = Kippt(username, api_token=password)
#             user = kippt.account()
# 
#             if 'message' in user:
#                 raise forms.ValidationError(user['message'])
# 
#         self.cleaned_data['api_token'] = user['api_token']
# 
#         return self.cleaned_data
# 
#     def save(self, commit=True):
#         user, created = KipptUser.objects.get_or_create(
#             username=self.cleaned_data['username'],
#         )
# 
#         user.api_token = self.cleaned_data['api_token']
#         user.save()
# 
#         if created:
#             user.set_password(None)
# 
#         return user, created
# 
# class KipptUserSetupForm(forms.ModelForm):
#     list_id = forms.ChoiceField(label='Default list')
# 
#     class Meta:
#         model = KipptUser
#         fields = ('list_id',)
# 
#     def __init__(self, *args, **kwargs):
#         super(KipptUserSetupForm, self).__init__(*args, **kwargs)
# 
#         kippt = self.instance.kippt_client()
#         meta, lists = kippt.lists()
# 
#         LIST_CHOICES = [('', 'Choose a list to store feed items')]
# 
#         for kippt_list in lists:
#             LIST_CHOICES.append((kippt_list['id'], kippt_list['title']))
# 
#         self.fields['list_id'].choices = LIST_CHOICES


# Path: apps/auth/views.py
from django.views.generic import CreateView, UpdateView
from django.contrib.auth import authenticate, login
from django.core.urlresolvers import reverse_lazy, reverse
from django.shortcuts import redirect
from braces.views import LoginRequiredMixin
from .models import KipptUser
from .forms import KipptUserConnectForm, KipptUserSetupForm

        context = super(ConnectView, self).get_context_data(**kwargs)
        feeds_create = self.request.build_absolute_uri(reverse('feeds_create'))
        context['subtome_url'] = '{}?feed={{feed}}&source=subtome'.format(feeds_create)
        return context

    def get(self, request, *args, **kwargs):
        if request.user.is_authenticated():
            return redirect(reverse_lazy('feeds_list'))

        return super(ConnectView, self).get(request, *args, **kwargs)

    def form_valid(self, form):
        obj, created = form.save()
        user = authenticate(username=obj.username, api_token=obj.api_token)

        if user is not None:
            login(self.request, user)

        redirect_to = self.request.GET.get('next')

        if created:
            redirect_to = reverse_lazy('auth_setup')
        elif not redirect_to:
            redirect_to = reverse_lazy('feeds_list')

        return redirect(redirect_to)


class SetupView(LoginRequiredMixin, UpdateView):
    model = KipptUser

    form_class = KipptUserSetupForm