Skip to content

Lesson 1 #21

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
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
  •  
  •  
  •  
6 changes: 5 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
*.pyc
.idea
*.sqlite3
*~
__pycache__/
env/
*.sqlite3
.DS_Store
Empty file added authapp/__init__.py
Empty file.
3 changes: 3 additions & 0 deletions authapp/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.contrib import admin

# Register your models here.
5 changes: 5 additions & 0 deletions authapp/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from django.apps import AppConfig


class AuthappConfig(AppConfig):
name = 'authapp'
26 changes: 26 additions & 0 deletions authapp/captcha_decorators.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
from functools import wraps
from geekshop import settings
from django.contrib import messages
import requests


def check_recaptcha(view_func):
@wraps(view_func)
def _wrapped_view(request, *args, **kwargs):
request.recaptcha_is_valid = None
if request.POST:
recaptcha_response = request.POST.get("g-recaptcha-response")
data = {
"secret": settings.GOOGLE_RECAPTCHA_SECRET_KEY,
"response": recaptcha_response
}
r = requests.post(
"https://www.google.com/recaptcha/api/siteverify", data=data)
result = r.json()
if result["success"]:
request.recaptcha_is_valid = True
else:
request.recaptcha_is_valid = False
messages.error(request, "Неверная каптча")
return view_func(request, *args, **kwargs)
return _wrapped_view
64 changes: 64 additions & 0 deletions authapp/forms.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
from django.forms import ModelForm
from django import forms
from .models import AdvUser, user_registrated
from datetime import date,timedelta,datetime
from django.utils.dateparse import parse_date
from django.core.exceptions import ValidationError
from django.contrib.auth import password_validation
from django.core import validators

#from django.shortcuts import render

class ChangeUserInfoForm(forms.ModelForm):
today = date.today()
email = forms.EmailField(required=True, label='Адрес электронной почты')
birstday = forms.DateField(label='Дата рождения',initial=today,widget=forms.widgets.DateInput(attrs={'type': 'date'}))

class Meta:
model = AdvUser
fields = ('username', 'email', 'first_name', 'last_name','sex','birstday','address','phone', 'send_messages')

class RegisterUserForm(forms.ModelForm):
email = forms.EmailField(required=True, label='Адрес электронной почты')
password1 = forms.CharField(label='Пароль', widget=forms.PasswordInput,
help_text=password_validation.password_validators_help_text_html())
password2 = forms.CharField(label='Пароль (повторно)', widget=forms.PasswordInput,
help_text='Введите тот же самый пароль еще раз для проверки')



def clean(self):
super().clean()
password1 = self.cleaned_data['password1']
password2 = self.cleaned_data['password2']

validate = password_validation.validate_password(password1)
if validate:
errors = {'password1': ValidationError('Введите другой пароль',
code='password_mismatch')}
raise forms.ValidationError(errors)


elif password1 and password2 and password1 != password2:
errors = {'password2': ValidationError('Введенные пароли не совпадают',
code='password_mismatch')}
raise ValidationError(errors)

def save(self, commit=True):
user = super().save(commit=False)
user.set_password(self.cleaned_data['password1'])
user.is_active = False
user.is_activated = False
if commit:
user.save()
user_registrated.send(RegisterUserForm, instance=user)
return user

class Meta:
model = AdvUser
fields = ('username', 'email', 'password1', 'password2', 'first_name', 'last_name',
'send_messages')




50 changes: 50 additions & 0 deletions authapp/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# Generated by Django 2.2.2 on 2019-12-08 10:23

import django.contrib.auth.models
import django.contrib.auth.validators
from django.db import migrations, models
import django.utils.timezone


class Migration(migrations.Migration):

initial = True

dependencies = [
('auth', '0011_update_proxy_permissions'),
]

operations = [
migrations.CreateModel(
name='AdvUser',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('password', models.CharField(max_length=128, verbose_name='password')),
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')),
('first_name', models.CharField(blank=True, max_length=30, verbose_name='first name')),
('last_name', models.CharField(blank=True, max_length=150, verbose_name='last name')),
('email', models.EmailField(blank=True, max_length=254, verbose_name='email address')),
('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')),
('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')),
('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')),
('sex', models.CharField(blank=True, choices=[('m', 'Мужской'), ('w', 'Женский')], default='m', help_text='Введите пол', max_length=1, verbose_name='Пол')),
('birstday', models.DateField(blank=True, null=True, verbose_name='Дата рождения')),
('address', models.CharField(blank=True, max_length=200, verbose_name='Место жительства')),
('phone', models.CharField(blank=True, max_length=16, verbose_name='Телефон')),
('is_activated', models.BooleanField(db_index=True, default=True, verbose_name='Прошел активацию?')),
('send_messages', models.BooleanField(default=True, verbose_name='Слать оповещения по электронной почте?')),
('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')),
('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')),
],
options={
'verbose_name': 'user',
'verbose_name_plural': 'users',
'abstract': False,
},
managers=[
('objects', django.contrib.auth.models.UserManager()),
],
),
]
Empty file added authapp/migrations/__init__.py
Empty file.
35 changes: 35 additions & 0 deletions authapp/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
from django.db import models

from django.contrib import admin
from django.contrib.auth.models import AbstractUser
from django.dispatch import Signal
#from precise_bbcode.fields import BBCodeTextField
from .utilities import send_activation_notification


class AdvUser(AbstractUser):
SEX_VISITOR = (
('m', 'Мужской'),
('w', 'Женский'),
)
sex = models.CharField(max_length=1, choices=SEX_VISITOR, blank=True, default='m', verbose_name = "Пол",
help_text='Введите пол')
birstday = models.DateField(auto_now_add = False, blank=True,null=True, db_index = False, verbose_name = "Дата рождения")
address = models.CharField(max_length=200, blank=True, verbose_name = "Место жительства")
phone = models.CharField(max_length=16, blank=True, verbose_name = "Телефон")

is_activated = models.BooleanField(default=True,db_index=True,verbose_name='Прошел активацию?')
send_messages = models.BooleanField(default=True,verbose_name='Слать оповещения по электронной почте?')

class Meta(AbstractUser.Meta):
pass
#--------------------------------------------------------------------------------------------
user_registrated = Signal(providing_args=['instance'])

def user_registrated_dispatcher(sender, **kwargs):
send_activation_notification(kwargs['instance'])

user_registrated.connect(user_registrated_dispatcher)
#--------------------------------------------------------------------------------------------from django.db import models

# Create your models here.
90 changes: 90 additions & 0 deletions authapp/static/css/styles.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
* {
margin: 0;
padding: 0;
}

.header{
min-height: 60px;
/*outline: 1px solid #212121;*/
display: table;
}
.logo{
margin-left: 17%;
float: left;
}
.logo img{
width: 50px;
}
.contact{
float: right;
margin-right: 17%;
width: 200px;
outline: 1px solid #212121;
margin-top: 13px;
}
.navbar{
background-color: #cda557;
/*box-shadow: 0 2px 5px 1px rgba(33, 33, 33, 0.35);*/
}

.content{
/*box-shadow: 0 2px 5px 1px rgba(33, 33, 33, 0.35);*/

}


.navi{
/*outline: 1px solid #212121;*/
/*box-shadow: 0 2px 5px 1px rgba(33, 33, 33, 0.35);*/

}
.head-nav{
/*outline: 1px solid #212121;*/
min-height: 60px;
background-color: #cda557;
text-align: center;
font-size: 18px;
line-height: 24px;
color: #fff;
width: 100%;
display: table;
}
.head-nav-title{
padding-top: 18px;
}

html {
position: relative;
min-height: 100%;
}
body {
margin-bottom: 60px; /* Margin bottom by footer height */
}
.body-post{
padding-top: 20px;
padding-bottom: 20px;
}
.btn-post_detail{
width: 100%;
margin-top: 20px;

background-color: #cda557;
}
.btn-post_detail:hover {
background-color: #caa500;
}

.footer {
position: absolute;
bottom: 0;
width: 100%;
height: 60px; /* Set the fixed height of the footer here */
line-height: 60px; /* Vertically center the text there */
background-color: #cda557;
}
.container-footer{
padding-left: 60px;
}
.card{
float: left;
}
11 changes: 11 additions & 0 deletions authapp/templates/email/activation_letter_body.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
Уважаемый пользователь {{ user.username }}!

Вы зарегистрировались на нашем сайте
Вам необходимо выполнить активацию, дабы подтвердить свою личность.
Для этого пройдите, пожалуйста, по ссылке

{{ host }}{% url 'register_activate' sign=sign %}

До свидания!

С уважением, администрация сайта
1 change: 1 addition & 0 deletions authapp/templates/email/activation_letter_subject.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Активация пользователя {{ user.username }}
10 changes: 10 additions & 0 deletions authapp/templates/email/new_comment_letter_body.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
Уважаемый пользователь {{ user.username }}!

К одному из Ваших объявлений оставлен новый комментарий.
Чтобы прочитать его, пройдите, пожалуйста, по ссылке

{{ host }}{# url 'profile_bb_detail' pk=comment.bb.pk #}

До свидания!

С уважением, администрация сайта cvvv.ru
1 change: 1 addition & 0 deletions authapp/templates/email/new_comment_letter_subject.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Новый комментарий оставлен под объявлением пользователя {{ author.username }}
10 changes: 10 additions & 0 deletions authapp/templates/email/reset_letter_body.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
Уважаемый пользователь {{ user.username }}!

Вы запросили на сайте cvvv.ru сброс пароля.
Чтобы выполнить сброс, пройдите, пожалуйста, по ссылке

{{ protocol}}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %}

До свидания!

С уважением, администрация сайта cvvv.ru
1 change: 1 addition & 0 deletions authapp/templates/email/reset_letter_subject.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Сброс пароля пользователя {{ user.username }}
7 changes: 7 additions & 0 deletions authapp/templates/profile/activation_done.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{% extends "base_generic.html" %}

{% block content2 %}
<h2>Активация</h2>
<p>Пользователь с таким именем успешно активирован.</p>
<p><a href="{% url 'login' %}">Войти на сайт</a></p>
{% endblock %}
18 changes: 18 additions & 0 deletions authapp/templates/profile/change_user_info.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{% extends "base_generic.html" %}

{% load bootstrap4 %}
{% block content %}

<div class="container">
<div class="row">
<div class="col-md-10" >
<h2>Правка личных данных пользователя {{ user.username }}</h2>
<form method="post">
{% csrf_token %}
{% bootstrap_form form layout='horizontal' %}
{% buttons submit='Сохранить' %}{% endbuttons %}
</form>
</div>
</div>
</div>
{% endblock %}
11 changes: 11 additions & 0 deletions authapp/templates/profile/delete_user.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{% extends "base_generic.html" %}

{% load bootstrap4 %}

{% block content %}
<h2>Удаление пользователя {{ object.username }}</h2>
<form method="post">
{% csrf_token %}
{% buttons submit='Удалить' %}{% endbuttons %}
</form>
{% endblock %}
Loading