aboutsummaryrefslogtreecommitdiff
path: root/users
diff options
context:
space:
mode:
Diffstat (limited to 'users')
-rw-r--r--users/accountFunctions.py10
-rw-r--r--users/forms.py262
-rw-r--r--users/mail_send.py34
-rw-r--r--users/templates/email_change_verification_email.html37
-rw-r--r--users/templates/reset_password_email.html25
-rw-r--r--users/templates/verification_email.html36
-rw-r--r--users/urls.py37
-rw-r--r--users/views.py299
8 files changed, 497 insertions, 243 deletions
diff --git a/users/accountFunctions.py b/users/accountFunctions.py
index f5d77d72..38bc7099 100644
--- a/users/accountFunctions.py
+++ b/users/accountFunctions.py
@@ -28,12 +28,18 @@ def store_token(token_type, user, email=None):
token_store.save()
return uid, token
-def verify_token(token_type, uid, token):
+def verify_token(token_type, uid, token, hold_verification=False):
try:
token_store = TokenStore.objects.get(token_type=token_type, uid=uid, token=token)
if token_store.expires > timezone.now() and not token_store.verified and token_store.token_type == token_type and token_store.uid == uid and token_store.token == token:
+
+ if hold_verification:
+ return token_store
token_store.verified = True
- UserProfile.objects.filter(user=token_store.user).update(email_verified=True)
+
+ if token_type == "verifyemail":
+ UserProfile.objects.filter(user=token_store.user).update(email_verified=True)
+
token_store.save()
return token_store
diff --git a/users/forms.py b/users/forms.py
index e618cec8..016ad6bb 100644
--- a/users/forms.py
+++ b/users/forms.py
@@ -16,109 +16,221 @@ from .mail_send import send_email
class RegisterForm(forms.Form):
- username = forms.CharField(label='Username', max_length=30, min_length=4)
- email = forms.EmailField(label='Email')
- password1 = forms.CharField(label='Password', widget=forms.PasswordInput, min_length=8)
- password2 = forms.CharField(label='Password (again)', widget=forms.PasswordInput, min_length=8)
- captcha = forms.CharField(label='Captcha', max_length=6)
+ username = forms.CharField(label="Username", max_length=30, min_length=4)
+ email = forms.EmailField(label="Email")
+ password1 = forms.CharField(
+ label="Password", widget=forms.PasswordInput, min_length=8
+ )
+ password2 = forms.CharField(
+ label="Password (again)", widget=forms.PasswordInput, min_length=8
+ )
+ captcha = forms.CharField(label="Captcha", max_length=6)
expected_captcha = None
protected_usernames = [
- 'admin',
- 'administrator',
- 'root',
- 'thatcomputerscientist',
- 'skippy',
- 'system',
- 'test',
- 'user',
- 'webmaster',
- 'www',
- 'postmaster',
- 'hostmaster',
- 'info',
- 'support',
- 'anonymous',
- 'guest',
- 'nobody',
- 'someone',
- 'moderator',
- 'moderators',
- 'mods',
- 'crvs'
+ "admin",
+ "administrator",
+ "root",
+ "thatcomputerscientist",
+ "skippy",
+ "system",
+ "test",
+ "user",
+ "webmaster",
+ "www",
+ "postmaster",
+ "hostmaster",
+ "info",
+ "support",
+ "anonymous",
+ "guest",
+ "nobody",
+ "someone",
+ "moderator",
+ "moderators",
+ "mods",
+ "crvs",
]
- allowed_chars = string.ascii_letters + string.digits
+ allowed_chars = string.ascii_letters + string.digits
def __init__(self, *args, **kwargs):
- if 'expected_captcha' in kwargs:
- self.expected_captcha = kwargs.pop('expected_captcha')
+ if "expected_captcha" in kwargs:
+ self.expected_captcha = kwargs.pop("expected_captcha")
super().__init__(*args, **kwargs)
def clean(self):
cleaned_data = super().clean()
- password1 = cleaned_data.get('password1')
- password2 = cleaned_data.get('password2')
- captcha = cleaned_data.get('captcha')
+ password1 = cleaned_data.get("password1")
+ password2 = cleaned_data.get("password2")
+ captcha = cleaned_data.get("captcha")
if password1 and password2:
if password1 != password2:
- raise forms.ValidationError('Passwords do not match.')
+ raise forms.ValidationError("Passwords do not match.")
if len(password1) < 8:
- raise forms.ValidationError('Password must be at least 8 characters long.')
+ raise forms.ValidationError("Password must be at least 8 characters long.")
if str.lower(captcha) != str.lower(self.expected_captcha):
- raise forms.ValidationError('Captcha does not match.')
- if User.objects.filter(username=cleaned_data.get('username')).exists():
- raise forms.ValidationError('Username not available. Please choose another.')
- if cleaned_data.get('username').lower() in self.protected_usernames:
- raise forms.ValidationError('Username not available. Please choose another.')
- for char in cleaned_data.get('username'):
+ raise forms.ValidationError("Captcha does not match.")
+ if User.objects.filter(username=cleaned_data.get("username")).exists():
+ raise forms.ValidationError(
+ "Username not available. Please choose another."
+ )
+ if cleaned_data.get("username").lower() in self.protected_usernames:
+ raise forms.ValidationError(
+ "Username not available. Please choose another."
+ )
+ for char in cleaned_data.get("username"):
if char not in self.allowed_chars:
- raise forms.ValidationError('Username contains invalid characters. Only A-Z, a-z, and 0-9 are allowed.')
- if User.objects.filter(email=cleaned_data.get('email')).exists():
- raise forms.ValidationError('Email already exists. Please login if this account is yours.')
+ raise forms.ValidationError(
+ "Username contains invalid characters. Only A-Z, a-z, and 0-9 are allowed."
+ )
+ if User.objects.filter(email=cleaned_data.get("email")).exists():
+ raise forms.ValidationError(
+ "Email already exists. Please login if this account is yours."
+ )
return cleaned_data
def save(self, request):
user = User.objects.create_user(
- username=self.cleaned_data.get('username').lower(),
- email=self.cleaned_data.get('email').lower(),
- password=self.cleaned_data.get('password1'),
+ username=self.cleaned_data.get("username").lower(),
+ email=self.cleaned_data.get("email").lower(),
+ password=self.cleaned_data.get("password1"),
)
user.save()
user_profile = UserProfile.objects.create(user=user)
avatar_dir = choice(list(avatar_list().keys()))
avatar_file = choice(avatar_list()[avatar_dir])
- user_profile.avatar_url = avatar_dir + '/' + avatar_file.replace('.gif', '')
+ user_profile.avatar_url = avatar_dir + "/" + avatar_file.replace(".gif", "")
user_profile.save()
- uid, token = store_token(token_type='verifyemail', user=user, email=user.email)
+ uid, token = store_token(token_type="verifyemail", user=user, email=user.email)
# Send verification email
- subject = 'Verify your email address'
- message = render_to_string('verification_email.html', {
- 'user': user.username if user.first_name is None else user.first_name,
- 'site_name': 'Shifoo',
- 'uid': uid,
- 'token': token,
- 'protocol': 'https://' if request.is_secure() else 'http://',
- 'domain': request.get_host(),
- })
- message = strip_tags(message)
+ subject = "Verify your email address"
+ message = render_to_string(
+ "verification_email.html",
+ {
+ "user": user.username if user.first_name is None else user.first_name,
+ "site_name": "Shifoo",
+ "uid": uid,
+ "token": token,
+ "protocol": "https://" if request.is_secure() else "http://",
+ "domain": request.get_host(),
+ },
+ )
+ # message = strip_tags(message)
# send_mail(subject, message, 'Shifoo <' + settings.EMAIL_HOST_USER + '>', [user.email], fail_silently=False)
- if (send_email(sender='[email protected]', sender_name='Shifoo', recipient=user.email, subject=subject, body_html=message, body_text=message)):
+ if send_email(
+ sender="[email protected]",
+ sender_name="Shifoo",
+ recipient=user.email,
+ subject=subject,
+ body_html=message,
+ body_text=message,
+ ):
return user
else:
return user
-class UpdateUserDetailsForm(forms.Form):
- first_name = forms.CharField(label='First name', max_length=30, required=False, widget=forms.TextInput(attrs={'placeholder': 'First name'}))
- last_name = forms.CharField(label='Last name', max_length=30, required=False, widget=forms.TextInput(attrs={'placeholder': 'Last name'}))
- location = forms.CharField(label='Location', max_length=30, required=False, widget=forms.TextInput(attrs={'placeholder': 'Location'}))
- bio = forms.CharField(label='Bio', max_length=500, required=False, widget=forms.Textarea(attrs={'placeholder': 'Bio'}))
- is_public = forms.ChoiceField(label='Activity Visibility', choices=((True, 'Public'), (False, 'Private')), widget=forms.RadioSelect)
- email_public = forms.ChoiceField(label='Email Visibility', choices=((True, 'Public'), (False, 'Private')), widget=forms.RadioSelect)
+class ForgotPasswordForm(forms.Form):
+ email = forms.EmailField(label="Email", required=True)
+
+ def clean(self):
+ cleaned_data = super().clean()
+ return cleaned_data
+
+ def save(self, request):
+ email = self.cleaned_data.get("email")
+ user = User.objects.get(email=email)
+ uid, token = store_token(
+ token_type="resetpassword", user=user, email=user.email
+ )
+ subject = "Reset your password"
+ message = render_to_string(
+ "reset_password_email.html",
+ {
+ "user": user.username if user.first_name is None else user.first_name,
+ "site_name": "Shifoo",
+ "uid": uid,
+ "token": token,
+ "protocol": "https://" if request.is_secure() else "http://",
+ "domain": request.get_host(),
+ },
+ )
+ # message = strip_tags(message)
+ if send_email(
+ sender="[email protected]",
+ sender_name="Shifoo",
+ recipient=user.email,
+ subject=subject,
+ body_html=message,
+ body_text=message,
+ ):
+ return user
+ else:
+ raise forms.ValidationError("Failed to send email.")
+
+class ResetPasswordForm(forms.Form):
+ password1 = forms.CharField(
+ label="New Password", widget=forms.PasswordInput, min_length=8
+ )
+ password2 = forms.CharField(
+ label="New Password (again)", widget=forms.PasswordInput, min_length=8
+ )
+
+ def clean(self):
+ cleaned_data = super().clean()
+ password1 = cleaned_data.get("password1")
+ password2 = cleaned_data.get("password2")
+ if password1 and password2:
+ if password1 != password2:
+ raise forms.ValidationError("Passwords do not match.")
+ if len(password1) < 8:
+ raise forms.ValidationError("Password must be at least 8 characters long.")
+ return cleaned_data
+
+ def save(self, user):
+ user.set_password(self.cleaned_data.get("password1"))
+ user.save()
+ return user
+
+class UpdateUserDetailsForm(forms.Form):
+ first_name = forms.CharField(
+ label="First name",
+ max_length=30,
+ required=False,
+ widget=forms.TextInput(attrs={"placeholder": "First name"}),
+ )
+ last_name = forms.CharField(
+ label="Last name",
+ max_length=30,
+ required=False,
+ widget=forms.TextInput(attrs={"placeholder": "Last name"}),
+ )
+ location = forms.CharField(
+ label="Location",
+ max_length=30,
+ required=False,
+ widget=forms.TextInput(attrs={"placeholder": "Location"}),
+ )
+ bio = forms.CharField(
+ label="Bio",
+ max_length=500,
+ required=False,
+ widget=forms.Textarea(attrs={"placeholder": "Bio"}),
+ )
+ is_public = forms.ChoiceField(
+ label="Activity Visibility",
+ choices=((True, "Public"), (False, "Private")),
+ widget=forms.RadioSelect,
+ )
+ email_public = forms.ChoiceField(
+ label="Email Visibility",
+ choices=((True, "Public"), (False, "Private")),
+ widget=forms.RadioSelect,
+ )
def __init__(self, *args, **kwargs):
- self.user = kwargs.pop('user')
+ self.user = kwargs.pop("user")
super().__init__(*args, **kwargs)
def clean(self):
@@ -126,15 +238,15 @@ class UpdateUserDetailsForm(forms.Form):
return cleaned_data
def save(self):
- self.user.first_name = self.cleaned_data.get('first_name')
- self.user.last_name = self.cleaned_data.get('last_name')
+ self.user.first_name = self.cleaned_data.get("first_name")
+ self.user.last_name = self.cleaned_data.get("last_name")
self.user.save()
user_profile = UserProfile.objects.get(user=self.user)
- user_profile.location = self.cleaned_data.get('location')
- user_profile.bio = self.cleaned_data.get('bio')
- user_profile.is_public = self.cleaned_data.get('is_public')
- user_profile.email_public = self.cleaned_data.get('email_public')
+ user_profile.location = self.cleaned_data.get("location")
+ user_profile.bio = self.cleaned_data.get("bio")
+ user_profile.is_public = self.cleaned_data.get("is_public")
+ user_profile.email_public = self.cleaned_data.get("email_public")
user_profile.save()
- return (self.user, user_profile) \ No newline at end of file
+ return (self.user, user_profile)
diff --git a/users/mail_send.py b/users/mail_send.py
index be167eb1..df837a32 100644
--- a/users/mail_send.py
+++ b/users/mail_send.py
@@ -13,51 +13,55 @@ def send_email(sender, sender_name, recipient, subject, body_html, body_text):
# this is the approved sender email
SENDER = sender
SENDERNAME = sender_name
-
+
# Replace [email protected] with a "To" address. If your account
# is still in the sandbox, this address must be verified.
RECIPIENT = recipient
-
+
# Replace the USERNAME_SMTP value with your Email Delivery SMTP username.
USERNAME_SMTP = settings.USERNAME_SMTP
-
+
# Put the PASSWORD value from your Email Delivery SMTP password into the following file.
PASSWORD_SMTP = settings.PASSWORD_SMTP
-
+
# If you're using Email Delivery in a different region, replace the HOST value with an appropriate SMTP endpoint.
# Use port 25 or 587 to connect to the SMTP endpoint.
HOST = settings.EMAIL_HOST
PORT = settings.EMAIL_PORT
-
+
# The subject line of the email.
SUBJECT = subject
-
+
# The email body for recipients with non-HTML email clients.
BODY_TEXT = body_text
-
+
# The HTML body of the email.
BODY_HTML = body_html
# create message container
msg = EmailMessage()
- msg['Subject'] = SUBJECT
- msg['From'] = email.utils.formataddr((SENDERNAME, SENDER))
- msg['To'] = RECIPIENT
+ msg["Subject"] = SUBJECT
+ msg["From"] = email.utils.formataddr((SENDERNAME, SENDER))
+ msg["To"] = RECIPIENT
# make the message multi-part alternative, making the content the first part
- msg.add_alternative(BODY_TEXT, subtype='text')
+ msg.add_alternative(BODY_TEXT, subtype="text")
# this adds the additional part to the message
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
- msg.add_alternative(BODY_HTML, subtype='html')
+ msg.add_alternative(BODY_HTML, subtype="html")
# Try to send the message.
- try:
+ try:
server = smtplib.SMTP(HOST, PORT)
server.ehlo()
# most python runtimes default to a set of trusted public CAs that will include the CA used by OCI Email Delivery.
# However, on platforms lacking that default (or with an outdated set of CAs), customers may need to provide a capath that includes our public CA.
- server.starttls(context=ssl.create_default_context(purpose=ssl.Purpose.SERVER_AUTH, cafile=None, capath=None))
+ server.starttls(
+ context=ssl.create_default_context(
+ purpose=ssl.Purpose.SERVER_AUTH, cafile=None, capath=None
+ )
+ )
# smtplib docs recommend calling ehlo() before & after starttls()
server.ehlo()
server.login(USERNAME_SMTP, PASSWORD_SMTP)
@@ -68,4 +72,4 @@ def send_email(sender, sender_name, recipient, subject, body_html, body_text):
except Exception as e:
return e
else:
- return True \ No newline at end of file
+ return True
diff --git a/users/templates/email_change_verification_email.html b/users/templates/email_change_verification_email.html
index 3db0a9d6..f6f9b127 100644
--- a/users/templates/email_change_verification_email.html
+++ b/users/templates/email_change_verification_email.html
@@ -1,12 +1,27 @@
-{% autoescape off %}
-Hi {{ user }},
+<!DOCTYPE html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <meta http-equiv="X-UA-Compatible" content="IE=edge" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>Change Email</title>
+ </head>
+ <body>
+ <h3>Change Your Current Email</h3>
+ <p>Hi {{ user }},</p>
+ <p>
+ We received a request to change your email address on {{ site_name }}. To
+ verify and change your email address, please click the link below.
+ </p>
+ <a
+ href="{{ protocol }}{{ domain }}{% url 'users:changeemail' 'changeemail' uid token %}"
+ >Change Email</a
+ >
+ <p>If the above link does not work, copy and paste the URL below into your browser:</p>
+ <a href="{{ protocol }}{{ domain }}{% url 'users:changeemail' 'changeemail' uid token %}">{{ protocol }}{{ domain }}{% url 'users:changeemail' 'changeemail' uid token %}</a>
-We received a request to change you email address on {{ site_name }}. To verify and change your email address, please click the link below.
-{{ protocol }}{{ domain }}{% url 'users:changeemail' 'changeemail' uid token %}
-
-Please ignore this email if you did not make this request.
-
-Thanks,
-{{ site_name }} Team
-
-{% endautoescape %} \ No newline at end of file
+ <p>Please ignore this email if you did not make this request.</p>
+ <p>Thanks,</p>
+ <p>Bobby from {{ site_name }}</p>
+ </body>
+</html>
diff --git a/users/templates/reset_password_email.html b/users/templates/reset_password_email.html
new file mode 100644
index 00000000..f9651a13
--- /dev/null
+++ b/users/templates/reset_password_email.html
@@ -0,0 +1,25 @@
+<!DOCTYPE html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <meta http-equiv="X-UA-Compatible" content="IE=edge" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>Reset Password</title>
+ </head>
+ <body>
+ <h3>Reset Your Current Password</h3>
+ <p>Hi {{ user }},</p>
+ <p>
+ We received a request to reset your password on {{ site_name }}. To reset
+ your password, please click the link below.
+ </p>
+ <a href="{{ protocol }}{{ domain }}{% url 'blog:resetpassword' uid token %}"
+ >Reset Password</a
+ >
+ <p>If the above link does not work, copy and paste the URL below into your browser:</p>
+ <a href="{{ protocol }}{{ domain }}{% url 'blog:resetpassword' uid token %}">{{ protocol }}{{ domain }}{% url 'blog:resetpassword' uid token %}</a>
+ <p>Please ignore this email if you did not make this request.</p>
+ <p>Thanks,</p>
+ <p>Bobby from {{ site_name }}</p>
+ </body>
+</html>
diff --git a/users/templates/verification_email.html b/users/templates/verification_email.html
index cd85ab38..06e91a79 100644
--- a/users/templates/verification_email.html
+++ b/users/templates/verification_email.html
@@ -1,10 +1,26 @@
-{% autoescape off %}
-Hi {{ user }},
-
-Thanks for registering an account on {{ site_name }}. To verify your email address, please click the link below.
-{{ protocol }}{{ domain }}{% url 'users:changeemail' 'verifyemail' uid token %}
-
-Thanks,
-{{ site_name }} Team
-{% endautoescape %}
-
+<!DOCTYPE html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <meta http-equiv="X-UA-Compatible" content="IE=edge" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>Verify Email</title>
+ </head>
+ <body>
+ <h1>Verify Your New Account</h1>
+ <p>Hi {{ user }},</p>
+ <p>
+ Thanks for registering an account on {{ site_name }}. To verify your email
+ address, please click the link below.
+ </p>
+ <a
+ href="{{ protocol }}{{ domain }}{% url 'users:changeemail' 'verifyemail' uid token %}"
+ >Verify Email</a
+ >
+ <p>If the above link does not work, copy and paste the URL below into your browser:</p>
+ <a href="{{ protocol }}{{ domain }}{% url 'users:changeemail' 'verifyemail' uid token %}">{{ protocol }}{{ domain }}{% url 'users:changeemail' 'verifyemail' uid token %}</a>
+ <p>Please ignore this email if you did not make this request.</p>
+ <p>Thanks,</p>
+ <p>Bobby from {{ site_name }}</p>
+ </body>
+</html>
diff --git a/users/urls.py b/users/urls.py
index 98dff57c..b7081e42 100644
--- a/users/urls.py
+++ b/users/urls.py
@@ -3,22 +3,29 @@ from django.urls import path
from . import views
-app_name = 'users'
+app_name = "users"
urlpatterns = [
- path('/login', views.login_user, name='login'),
- path('/logout', views.logout_user, name='logout'),
- path('/update', views.update_user, name='update'),
- path('/changepassword', views.change_password, name='changepassword'),
- path('/sendchangeuseremail', views.send_change_user_email, name='sendchangeuseremail'),
- path('/sendverificationemail', views.send_verification_email, name='sendverificationemail'),
- path('/updateavatar', views.update_avatar, name='updateavatar'),
- path('/updateblinkies', views.update_blinkie, name='updateblinkie'),
- path('/delete', views.delete_user, name='delete'),
- path('/<mode>/<uid>/<token>', views.verify_email, name='verifyemail'),
- path('/<mode>/<uid>/<token>', views.verify_email, name='changeemail'),
+ path("/login", views.login_user, name="login"),
+ path("/logout", views.logout_user, name="logout"),
+ path("/update", views.update_user, name="update"),
+ path("/changepassword", views.change_password, name="changepassword"),
+ path(
+ "/sendchangeuseremail", views.send_change_user_email, name="sendchangeuseremail"
+ ),
+ path(
+ "/sendverificationemail",
+ views.send_verification_email,
+ name="sendverificationemail",
+ ),
+ path("/updateavatar", views.update_avatar, name="updateavatar"),
+ path("/updateblinkies", views.update_blinkie, name="updateblinkie"),
+ path("/delete", views.delete_user, name="delete"),
+ path("/<mode>/<uid>/<token>", views.verify_email, name="verifyemail"),
+ path("/<mode>/<uid>/<token>", views.verify_email, name="changeemail"),
+ path("/resetpassword/<uid>/<token>", views.reset_password, name="resetpassword"),
]
# Configure Admin Site
-admin.site.site_header = 'Shifoo Administation'
-admin.site.site_title = 'Shifoo'
-admin.site.index_title = 'Administration Area'
+admin.site.site_header = "Shifoo Administation"
+admin.site.site_title = "Shifoo"
+admin.site.index_title = "Administration Area"
diff --git a/users/views.py b/users/views.py
index 7c166911..5dba135b 100644
--- a/users/views.py
+++ b/users/views.py
@@ -1,6 +1,5 @@
from django.contrib import messages
-from django.contrib.auth import (authenticate, login, logout,
- update_session_auth_hash)
+from django.contrib.auth import authenticate, login, logout, update_session_auth_hash
from django.contrib.auth.models import User
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import redirect, reverse
@@ -16,14 +15,14 @@ from .models import UserProfile
# Create your views here.
def login_user(request):
# pass
- next = request.POST.get('next', 'blog:home')
- username = request.POST['username']
- password = request.POST['password']
- if username == '' or password == '' or username is None or password is None:
+ next = request.POST.get("next", "blog:home")
+ username = request.POST["username"]
+ password = request.POST["password"]
+ if username == "" or password == "" or username is None or password is None:
# required fields are empty
- messages.error(request, 'RFEERR', extra_tags='loginError')
- return HttpResponseRedirect(next + '?username=' + username)
- else:
+ messages.error(request, "RFEERR", extra_tags="loginError")
+ return HttpResponseRedirect(next + "?username=" + username)
+ else:
# check if email is verified
user = authenticate(request, username=username, password=password)
if user is not None:
@@ -37,195 +36,265 @@ def login_user(request):
return HttpResponseRedirect(next)
else:
# email not verified
- messages.error(request, 'ENVERR', extra_tags='loginError')
- return HttpResponseRedirect(next + '?username=' + username)
+ messages.error(request, "ENVERR", extra_tags="loginError")
+ return HttpResponseRedirect(next + "?username=" + username)
else:
# invalid credentials
- messages.error(request, 'IUOPERR', extra_tags='loginError')
- return HttpResponseRedirect(next + '?username=' + username)
+ messages.error(request, "IUOPERR", extra_tags="loginError")
+ return HttpResponseRedirect(next + "?username=" + username)
+
def logout_user(request):
logout(request)
- return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
+ return HttpResponseRedirect(request.META.get("HTTP_REFERER"))
+
def update_user(request):
user = request.user
if user is not None:
- if request.method == 'POST':
+ if request.method == "POST":
form = UpdateUserDetailsForm(request.POST, user=user)
if form.is_valid():
form.save()
- messages.success(request, 'Profile was successfully updated!')
- return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
+ messages.success(request, "Profile was successfully updated!")
+ return HttpResponseRedirect(request.META.get("HTTP_REFERER"))
else:
- messages.error(request, 'Unable to update profile! Please try again later.')
- return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
+ messages.error(
+ request, "Unable to update profile! Please try again later."
+ )
+ return HttpResponseRedirect(request.META.get("HTTP_REFERER"))
else:
- return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
+ return HttpResponseRedirect(request.META.get("HTTP_REFERER"))
else:
- messages.error(request, 'You must be logged in to update your profile!')
- return redirect('blog:home')
+ messages.error(request, "You must be logged in to update your profile!")
+ return redirect("blog:home")
+
def delete_user(request):
user = request.user
if user is not None:
- if request.method == 'POST':
- password = request.POST['password']
+ if request.method == "POST":
+ password = request.POST["password"]
if user.check_password(password):
# delete user, all comments, user profile details, and all posts
user.delete()
- messages.success(request, 'Your account was successfully deleted!')
- return redirect('blog:home')
+ messages.success(request, "Your account was successfully deleted!")
+ return redirect("blog:home")
else:
- messages.error(request, 'Incorrect password!')
- return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
+ messages.error(request, "Incorrect password!")
+ return HttpResponseRedirect(request.META.get("HTTP_REFERER"))
else:
- messages.error(request, 'Unable to delete account! Please try again later.')
- return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
+ messages.error(request, "Unable to delete account! Please try again later.")
+ return HttpResponseRedirect(request.META.get("HTTP_REFERER"))
else:
- messages.error(request, 'You must be logged in to delete your account!')
- return redirect('blog:home')
+ messages.error(request, "You must be logged in to delete your account!")
+ return redirect("blog:home")
+
def update_avatar(request):
user = request.user
if user is not None:
- if request.method == 'POST':
+ if request.method == "POST":
user_profile = UserProfile.objects.get(user=user)
- user_profile.avatar_url = request.POST['avatar']
+ user_profile.avatar_url = request.POST["avatar"]
user_profile.save()
- messages.success(request, 'Avatar was successfully updated!')
- return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
+ messages.success(request, "Avatar was successfully updated!")
+ return HttpResponseRedirect(request.META.get("HTTP_REFERER"))
else:
- messages.error(request, 'Unable to update avatar! Please try again later.')
- return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
+ messages.error(request, "Unable to update avatar! Please try again later.")
+ return HttpResponseRedirect(request.META.get("HTTP_REFERER"))
else:
- messages.error(request, 'You must be logged in to update your avatar!')
- return redirect('blog:home')
+ messages.error(request, "You must be logged in to update your avatar!")
+ return redirect("blog:home")
+
def update_blinkie(request):
- user = request.user
+ user = request.user
if user is not None:
- if request.method == 'POST':
+ if request.method == "POST":
user_profile = UserProfile.objects.get(user=user)
- user_profile.blinkie_url = request.POST['blinkie']
+ user_profile.blinkie_url = request.POST["blinkie"]
user_profile.save()
- messages.success(request, 'Blinkie was successfully updated!')
- return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
+ messages.success(request, "Blinkie was successfully updated!")
+ return HttpResponseRedirect(request.META.get("HTTP_REFERER"))
else:
- messages.error(request, 'Unable to update blinkie! Please try again later.')
- return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
+ messages.error(request, "Unable to update blinkie! Please try again later.")
+ return HttpResponseRedirect(request.META.get("HTTP_REFERER"))
else:
- messages.error(request, 'You must be logged in to update your blinkie!')
- return redirect('blog:home')
-
+ messages.error(request, "You must be logged in to update your blinkie!")
+ return redirect("blog:home")
+
+
def change_password(request):
username = request.user
- old_password = request.POST['oldPassword']
- new_password = request.POST['newPassword']
- confirm_password = request.POST['confirmPassword']
+ old_password = request.POST["oldPassword"]
+ new_password = request.POST["newPassword"]
+ confirm_password = request.POST["confirmPassword"]
if username is not None:
user = User.objects.get(username=username)
if user.check_password(old_password):
if new_password == confirm_password:
if len(new_password) < 8:
- messages.error(request, 'The new password must be at least 8 characters long!')
- return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
+ messages.error(
+ request, "The new password must be at least 8 characters long!"
+ )
+ return HttpResponseRedirect(request.META.get("HTTP_REFERER"))
user.set_password(new_password)
user.save()
update_session_auth_hash(request, user)
- messages.success(request, 'Password was successfully changed!')
- return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
+ messages.success(request, "Password was successfully changed!")
+ return HttpResponseRedirect(request.META.get("HTTP_REFERER"))
else:
- messages.error(request, 'The new password and confirmation password do not match!')
- return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
+ messages.error(
+ request, "The new password and confirmation password do not match!"
+ )
+ return HttpResponseRedirect(request.META.get("HTTP_REFERER"))
else:
- messages.error(request, 'Old password is incorrect!')
- return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
+ messages.error(request, "Old password is incorrect!")
+ return HttpResponseRedirect(request.META.get("HTTP_REFERER"))
else:
- messages.error(request, 'Unable to change password! Please try again later.')
- return redirect('blog:home')
+ messages.error(request, "Unable to change password! Please try again later.")
+ return redirect("blog:home")
+
def send_change_user_email(request):
user = request.user
- new_email = request.POST['email']
+ new_email = request.POST["email"]
if user is not None:
# Check if the new and the old email are the same
if user.email == new_email:
- messages.error(request, 'New email is the same as the old one!')
- return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
+ messages.error(request, "New email is the same as the old one!")
+ return HttpResponseRedirect(request.META.get("HTTP_REFERER"))
# check if email is already in use
if User.objects.filter(email=new_email).exists():
- messages.error(request, 'Email is already in use!')
+ messages.error(request, "Email is already in use!")
# Redirect to referrer
- return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
+ return HttpResponseRedirect(request.META.get("HTTP_REFERER"))
# Send verification email
- subject = 'Verify your email address'
- uid, token = store_token(token_type='changeemail', user=user, email=new_email)
-
- message = render_to_string('email_change_verification_email.html', {
- 'user': user.username if user.first_name is None else user.first_name,
- 'site_name': 'Shifoo',
- 'uid': uid,
- 'token': token,
- 'protocol': request.scheme + '://',
- 'domain': request.get_host(),
- })
- message = strip_tags(message)
+ subject = "Change your email address"
+ uid, token = store_token(token_type="changeemail", user=user, email=new_email)
+
+ message = render_to_string(
+ "email_change_verification_email.html",
+ {
+ "user": user.username if user.first_name is None else user.first_name,
+ "site_name": "Shifoo",
+ "uid": uid,
+ "token": token,
+ "protocol": request.scheme + "://",
+ "domain": request.get_host(),
+ },
+ )
+ # message = strip_tags(message)
# send_mail(subject, message, 'That Computer Scientist <' + settings.EMAIL_HOST_USER + '>', [new_email])
- if (send_email(sender='[email protected]', sender_name='Shifoo', recipient=new_email, subject=subject, body_html=message, body_text=message)):
- messages.success(request, 'Verification email was sent! Please check your email.')
- return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
+ if send_email(
+ sender="[email protected]",
+ sender_name="Shifoo",
+ recipient=new_email,
+ subject=subject,
+ body_html=message,
+ body_text=message,
+ ):
+ messages.success(
+ request, "Verification email was sent! Please check your email."
+ )
+ return HttpResponseRedirect(request.META.get("HTTP_REFERER"))
else:
- messages.error(request, 'Unable to change email! Please try again later.')
- return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
-
+ messages.error(request, "Unable to change email! Please try again later.")
+ return HttpResponseRedirect(request.META.get("HTTP_REFERER"))
+
else:
- messages.error(request, 'Unable to change email! Please try again later.')
- return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
-
+ messages.error(request, "Unable to change email! Please try again later.")
+ return HttpResponseRedirect(request.META.get("HTTP_REFERER"))
+
+
def send_verification_email(request):
# this is a post only view
- if request.method == 'POST':
- username = request.POST.get('username')
- subject = 'Verify your email address'
+ if request.method == "POST":
+ username = request.POST.get("username")
+ subject = "Verify your email address"
user = User.objects.get(username=username)
- uid, token = store_token(token_type='verifyemail', user=user, email=user.email)
-
- message = render_to_string('verification_email.html', {
- 'user': user.username if user.first_name is None else user.first_name,
- 'site_name': 'Shifoo',
- 'uid': uid,
- 'token': token,
- 'protocol': 'https://' if request.is_secure() else 'http://',
- 'domain': request.get_host(),
- })
- message = strip_tags(message)
- if (send_email(sender='[email protected]', sender_name='Shifoo', recipient=user.email, subject=subject, body_html=message, body_text=message)):
- messages.success(request, 'VESENT', extra_tags='loginError')
- return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
+ uid, token = store_token(token_type="verifyemail", user=user, email=user.email)
+
+ message = render_to_string(
+ "verification_email.html",
+ {
+ "user": user.username if user.first_name is None else user.first_name,
+ "site_name": "Shifoo",
+ "uid": uid,
+ "token": token,
+ "protocol": "https://" if request.is_secure() else "http://",
+ "domain": request.get_host(),
+ },
+ )
+ # message = strip_tags(message)
+ if send_email(
+ sender="[email protected]",
+ sender_name="Shifoo",
+ recipient=user.email,
+ subject=subject,
+ body_html=message,
+ body_text=message,
+ ):
+ messages.success(request, "VESENT", extra_tags="loginError")
+ return HttpResponseRedirect(request.META.get("HTTP_REFERER"))
else:
- messages.error(request, 'VESENDERR', extra_tags='loginError')
- return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
+ messages.error(request, "VESENDERR", extra_tags="loginError")
+ return HttpResponseRedirect(request.META.get("HTTP_REFERER"))
else:
- messages.error(request, 'VESENDERR', extra_tags='loginError')
- return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
+ messages.error(request, "VESENDERR", extra_tags="loginError")
+ return HttpResponseRedirect(request.META.get("HTTP_REFERER"))
+
def verify_email(request, mode, uid, token):
token_object = verify_token(mode, uid, token)
- redirect_to = reverse('blog:account') + '?tab=email' if mode == 'changeemail' else 'blog:home'
- success_message = 'Email was successfully changed!' if mode == 'changeemail' else 'VESUCCESS'
- error_message = 'Unable to verify email! Please try again later.'
+ redirect_to = (
+ reverse("blog:account") + "?tab=email" if mode == "changeemail" else "blog:home"
+ )
+ success_message = (
+ "Email was successfully changed!" if mode == "changeemail" else "VESUCCESS"
+ )
+ error_message = "Unable to verify email! Please try again later."
if token_object is not None and token_object.verified:
user = User.objects.get(pk=token_object.user_id)
user.email = token_object.email
user.save()
token_object.delete()
- messages.success(request, success_message, extra_tags='loginError' if mode == 'verifyemail' else '')
+ messages.success(
+ request,
+ success_message,
+ extra_tags="loginError" if mode == "verifyemail" else "",
+ )
return redirect(redirect_to)
else:
messages.error(request, error_message)
return redirect(redirect_to)
- \ No newline at end of file
+
+
+def reset_password(request, uid, token):
+ mode = "resetpassword"
+ token_object = verify_token(mode, uid, token)
+
+ # Token is not verified yet, but confirmed that it belongs to the user
+ # Now we send a form for the user to reset their password
+ if token_object is not None and token_object.verified:
+ print(token_object.user_id)
+ # redirect to forgotpassword/reset?uid=uid&token=token
+ return HttpResponseRedirect(
+ reverse("blog:resetpassword")
+ + "?uid="
+ + token_object.user_id
+ + "&token="
+ + token
+ )
+ else:
+ # Token is invalid
+ messages.error(
+ request,
+ "Unable to reset password! Please try again later.",
+ extra_tags="passwordReset",
+ )
+ return redirect("blog:forgotpassword")