Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
The diff you're trying to view is too large. We only load the first 3000 changed files.
3 changes: 3 additions & 0 deletions geekshop/.idea/misc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions geekshop/.idea/vcs.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Binary file modified geekshop/adminapp/__pycache__/views.cpython-37.pyc
Binary file not shown.
Binary file not shown.
Binary file modified geekshop/authapp/__pycache__/forms.cpython-37.pyc
Binary file not shown.
Binary file modified geekshop/authapp/__pycache__/models.cpython-37.pyc
Binary file not shown.
Binary file modified geekshop/authapp/__pycache__/urls.cpython-37.pyc
Binary file not shown.
Binary file modified geekshop/authapp/__pycache__/views.cpython-37.pyc
Binary file not shown.
26 changes: 24 additions & 2 deletions geekshop/authapp/forms.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import hashlib, random

from django import forms
from django.contrib.auth.forms import AuthenticationForm, UserCreationForm
from .models import ShopUser
from .models import ShopUser, ShopUserProfile

from django.contrib.auth.forms import UserChangeForm

Expand Down Expand Up @@ -34,6 +36,15 @@ def clean_age(self):

return data

def save(self):
user = super(ShopUserRegisterForm, self).save()

user.is_active = False
salt = hashlib.sha1(str(random.random()).encode('utf8')).hexdigest()[:6]
user.activation_key = hashlib.sha1((user.email + salt).encode('utf8')).hexdigest()
user.save()

return user

class ShopUserEditForm(UserChangeForm):
class Meta:
Expand All @@ -53,4 +64,15 @@ def clean_age(self):
if data < 18:
raise forms.ValidationError("Вы слишком молоды!")

return data
return data

class ShopUserProfileEditForm(forms.ModelForm):
class Meta:
model = ShopUserProfile
fields = ('tagline', 'aboutMe', 'gender')

def __init__(self, *args, **kwargs):
super(ShopUserProfileEditForm, self).__init__(*args, **kwargs)
for field_name, field in self.fields.items():
field.widget.attrs['class'] = 'form-control'

30 changes: 30 additions & 0 deletions geekshop/authapp/migrations/0002_auto_20200507_1500.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Generated by Django 2.2 on 2020-05-07 12:00

import datetime
from django.db import migrations, models
from django.utils.timezone import utc


class Migration(migrations.Migration):

dependencies = [
('authapp', '0001_initial'),
]

operations = [
migrations.AddField(
model_name='shopuser',
name='activation_key',
field=models.CharField(blank=True, max_length=128),
),
migrations.AddField(
model_name='shopuser',
name='activation_key_expires',
field=models.DateTimeField(default=datetime.datetime(2020, 5, 9, 12, 0, 34, 568962, tzinfo=utc)),
),
migrations.AlterField(
model_name='shopuser',
name='last_name',
field=models.CharField(blank=True, max_length=150, verbose_name='last name'),
),
]
25 changes: 25 additions & 0 deletions geekshop/authapp/migrations/0003_auto_20200511_1358.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Generated by Django 2.2 on 2020-05-11 10:58

import datetime
from django.db import migrations, models
from django.utils.timezone import utc


class Migration(migrations.Migration):

dependencies = [
('authapp', '0002_auto_20200507_1500'),
]

operations = [
migrations.AlterField(
model_name='shopuser',
name='activation_key_expires',
field=models.DateTimeField(default=datetime.datetime(2020, 5, 13, 10, 58, 19, 130867, tzinfo=utc)),
),
migrations.AlterField(
model_name='shopuser',
name='age',
field=models.PositiveIntegerField(default=18, verbose_name='возраст'),
),
]
32 changes: 32 additions & 0 deletions geekshop/authapp/migrations/0004_auto_20200511_1430.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Generated by Django 2.2 on 2020-05-11 11:30

import datetime
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
from django.utils.timezone import utc


class Migration(migrations.Migration):

dependencies = [
('authapp', '0003_auto_20200511_1358'),
]

operations = [
migrations.AlterField(
model_name='shopuser',
name='activation_key_expires',
field=models.DateTimeField(default=datetime.datetime(2020, 5, 13, 11, 30, 26, 513466, tzinfo=utc)),
),
migrations.CreateModel(
name='ShopUserProfile',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('tagline', models.CharField(blank=True, max_length=128, verbose_name='теги')),
('aboutMe', models.TextField(blank=True, max_length=512, verbose_name='о себе')),
('gender', models.CharField(blank=True, choices=[('M', 'М'), ('W', 'Ж')], max_length=1, verbose_name='пол')),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
20 changes: 20 additions & 0 deletions geekshop/authapp/migrations/0005_auto_20200511_1430.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Generated by Django 2.2 on 2020-05-11 11:30

import datetime
from django.db import migrations, models
from django.utils.timezone import utc


class Migration(migrations.Migration):

dependencies = [
('authapp', '0004_auto_20200511_1430'),
]

operations = [
migrations.AlterField(
model_name='shopuser',
name='activation_key_expires',
field=models.DateTimeField(default=datetime.datetime(2020, 5, 13, 11, 30, 41, 529123, tzinfo=utc)),
),
]
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
44 changes: 43 additions & 1 deletion geekshop/authapp/models.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,49 @@
from datetime import timedelta

from django.db import models
from django.contrib.auth.models import AbstractUser
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.utils.timezone import now


class ShopUser(AbstractUser):
avatar = models.ImageField(upload_to='users_avatars', blank=True)
age = models.PositiveIntegerField(verbose_name = 'возраст')
age = models.PositiveIntegerField(verbose_name = 'возраст', default=18)
activation_key = models.CharField(max_length=128, blank=True)
activation_key_expires = models.DateTimeField( default=(now() + timedelta(hours=48)))


def is_activation_key_expired(self):
if now() <= self.activation_key_expires:
return False
else:
return True

class ShopUserProfile(models.Model):
MALE = 'M'
FEMALE = 'W'

GENDER_CHOICES = (
(MALE, 'М'),
(FEMALE, 'Ж'),
)

user = models.OneToOneField(ShopUser, unique=True, null=False,\
db_index=True, on_delete=models.CASCADE)
tagline = models.CharField(verbose_name='теги', max_length=128, \
blank=True)
aboutMe = models.TextField(verbose_name='о себе', max_length=512, \
blank=True)
gender = models.CharField(verbose_name='пол', max_length=1, \
choices=GENDER_CHOICES, blank=True)

@receiver(post_save, sender=ShopUser)
def create_user_profile(sender, instance, created, **kwargs):
if created:
ShopUserProfile.objects.create(user=instance)


@receiver(post_save, sender=ShopUser)
def save_user_profile(sender, instance, **kwargs):
instance.shopuserprofile.save()
45 changes: 45 additions & 0 deletions geekshop/authapp/pipeline.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
from collections import OrderedDict
from datetime import datetime
from urllib.parse import urlencode, urlunparse

import requests
from django.utils import timezone
from social_core.exceptions import AuthForbidden

from authapp.models import ShopUserProfile


def save_user_profile(backend, user, response, *args, **kwargs):
if backend.name != 'vk-oauth2':
return

api_url = urlunparse(('https',
'api.vk.com',
'/method/users.get',
None,
urlencode(OrderedDict(fields=','.join(('bdate', 'sex', 'about')),
access_token=response['access_token'],
v='5.92')),
None
))

resp = requests.get(api_url)
if resp.status_code != 200:
return

data = resp.json()['response'][0]
if data['sex']:
user.shopuserprofile.gender = ShopUserProfile.MALE if data['sex'] == 2 else ShopUserProfile.FEMALE

if data['about']:
user.shopuserprofile.aboutMe = data['about']

if data['bdate']:
bdate = datetime.strptime(data['bdate'], '%d.%m.%Y').date()

age = timezone.now().date().year - bdate.year
if age < 18:
user.delete()
raise AuthForbidden('social_core.backends.vk.VKOAuth2')

user.save()
1 change: 1 addition & 0 deletions geekshop/authapp/templates/authapp/edit.html
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
<form class="form-horizontal" action="{% url 'auth:edit' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ edit_form.as_p }}
{{ profile_form.as_p }}
<input class="form-control" type="submit" value="сохранить">
</form>
<button class="btn btn-round form-control last">
Expand Down
7 changes: 6 additions & 1 deletion geekshop/authapp/templates/authapp/login.html
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,12 @@
</form>
<button class="btn btn-round form-control">
<a href="{% url 'auth:register' %}" class="">
зарегистрироваться
Зарегистрироваться
</a>
</button>
<button class="btn btn-round form-control">
<a href="{% url 'social:begin' 'vk-oauth2' %}?next=/">
Вход через ВКонтакте
</a>
</button>

Expand Down
18 changes: 18 additions & 0 deletions geekshop/authapp/templates/authapp/verification.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{% extends 'authapp/base.html' %}
{% load staticfiles %}

{% block content %}

{% if user %}
<h3>Поздравляем!</h3>
<br>
<h4>Пользователь {{user.username}} подтвержден.</h4>
{% else %}
<h3>Верификация не пройдена.</h3>
{% endif %}
<br>
<button class="btn btn-round form-control">
<a href="{% url 'main' %}" class="">на главную</a>
</button>

{% endblock %}
11 changes: 6 additions & 5 deletions geekshop/authapp/urls.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
from django.urls import path
from django.urls import path, re_path

import authapp.views as authapp

app_name = 'authapp'

urlpatterns = [
path('login/', authapp.login, name='login'),
path('logout/', authapp.logout, name='logout'),
path('register/', authapp.register, name='register'),
path('edit/', authapp.edit, name='edit'),
re_path('login/', authapp.login, name='login'),
re_path('logout/', authapp.logout, name='logout'),
re_path('register/', authapp.register, name='register'),
re_path('edit/', authapp.edit, name='edit'),
re_path(r'^verify/(?P<email>.+)/(?P<activation_key>\w+)/$', authapp.verify, name='verify'),
]
Loading