Skip to content
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

Restructure project #1012

Merged
merged 10 commits into from
Sep 15, 2021
111 changes: 1 addition & 110 deletions project/accounts/authentication.py
Original file line number Diff line number Diff line change
@@ -1,29 +1,17 @@
from django.conf import settings
from django.contrib.auth import authenticate, logout, login
from django.contrib.auth import get_user_model
from django.contrib.auth.tokens import PasswordResetTokenGenerator
from django.contrib.sites.shortcuts import get_current_site
from django.http import (
JsonResponse,
HttpResponse,
HttpResponseServerError,
HttpResponseRedirect,
HttpResponseBadRequest,
)
from django.shortcuts import get_object_or_404
from django.template.response import TemplateResponse # TODO: move this out to views
from django.utils.crypto import salted_hmac
from django.utils.encoding import force_bytes, force_text
from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
from django.utils.http import int_to_base36
from django.views.decorators.debug import sensitive_post_parameters
from django.template.loader import render_to_string


from accounts.utils import send_email
from accounts.models import Profile
from .forms import ProfileRegistrationForm, PasswordResetForm, RecoverUserForm
from core.custom_decorators import require_post_params
from .forms import PasswordResetForm, RecoverUserForm


User = get_user_model()
Expand Down Expand Up @@ -76,103 +64,6 @@ def send_activation_email(user, domain):
)


@sensitive_post_parameters("password")
@require_post_params(params=["username", "password"])
def cw_login(request):
"""
USAGE:
This is used to authenticate the user and log them in.

:returns (200, ok) (400, Inactive User) (400, Invalid username or password)
"""

username = request.POST.get("username", "")
password = request.POST.get("password", "")
remember = request.POST.get("remember", "false")

user = authenticate(username=username, password=password)
if user is not None:
if remember == "false":
request.session.set_expiry(0)

login(request, user)

if user.is_active:

account = get_object_or_404(Profile, user=user)
request.session["login_user_firstname"] = account.first_name
request.session["login_user_image"] = account.profile_image_thumb_url

return HttpResponse()
else:
response = {"message": "Inactive user", "error": "USER_INACTIVE"}
return JsonResponse(response, status=400)
else:
# Return an 'invalid login' error message.
response = {"message": "Invalid username or password", "error": "INVALID_LOGIN"}
return JsonResponse(response, status=400)


def cw_logout(request):
"""Use this to logout the current user """

logout(request)
return HttpResponseRedirect("/")


@sensitive_post_parameters("password")
@require_post_params(params=["username", "password", "email"])
def cw_register(request):
"""
USAGE:
This is used to register new users to civiwiki

PROCESS:
- Gets new users username and password
- Sets the user to active
- Then creates a new user verification link and emails it to the new user

Return:
(200, ok) (500, Internal Error)
"""
form = ProfileRegistrationForm(request.POST or None)
if request.method == "POST":
# Form Validation
if form.is_valid():
username = form.clean_username()
password = form.clean_password()
email = form.clean_email()

# Create a New Profile
try:
user = User.objects.create_user(username, email, password)

account = Profile(user=user)
account.save()

user.is_active = True
user.save()

domain = get_current_site(request).domain

send_activation_email(user, domain)

login(request, user)
return HttpResponse()

except Exception as e:
return HttpResponseServerError(reason=str(e))

else:
response = {
"success": False,
"errors": [error[0] for error in form.errors.values()],
}
return JsonResponse(response, status=400)
else:
return HttpResponseBadRequest(reason="POST Method Required")


def activate_view(request, uidb64, token):
"""
This shows different views to the user when they are verifying
Expand Down
6 changes: 2 additions & 4 deletions project/accounts/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,11 @@
from django.core.files.images import get_image_dimensions
from django import forms
from django.contrib.auth.forms import (
UserCreationForm,
SetPasswordForm,
PasswordResetForm as AuthRecoverUserForm,
)
from django.forms.models import ModelForm
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth.tokens import default_token_generator
from django.contrib.sites.shortcuts import get_current_site
from django.utils.encoding import force_bytes
Expand All @@ -24,9 +22,9 @@
User = get_user_model()


class ProfileRegistrationForm(ModelForm):
class UserRegistrationForm(ModelForm):
"""
This class is used to register new account in Civiwiki
This class is used to register a new user in Civiwiki

Components:
- Email - from registration form
Expand Down
31 changes: 0 additions & 31 deletions project/accounts/templates/accounts/login.html

This file was deleted.

3 changes: 0 additions & 3 deletions project/accounts/tests.py

This file was deleted.

Empty file.
65 changes: 65 additions & 0 deletions project/accounts/tests/test_forms.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
from django.contrib.auth import get_user_model
from django.test import TestCase
from accounts.forms import UserRegistrationForm


class UserRegistrationFormTest(TestCase):
"""A class to test user registration form"""

def setUp(self) -> None:
self.data = {
"username": "testuser",
"email": "[email protected]",
"password": "password123"
}

def test_user_creation_form_with_success(self):
"""Whether form works as expected for the valid inputs"""

form = UserRegistrationForm(self.data)
self.assertTrue(form.is_valid())
self.assertEqual(form.errors, {})
form.save()
self.assertTrue(get_user_model().objects.count(), 1)

def test_form_is_unsuccessful_for_short_password(self):
"""Whether a user does not have a short password"""

self.data['password'] = "123"
form = UserRegistrationForm(self.data)
self.assertFalse(form.is_valid())
self.assertNotEqual(form.errors, {})
self.assertTrue(form.has_error('password'))
self.assertEqual(get_user_model().objects.count(), 0)

def test_form_is_unsuccessful_for_only_digit_password(self):
"""Whether a user does not have an only-digit password"""

self.data['password'] = "12345678"
form = UserRegistrationForm(self.data)
self.assertFalse(form.is_valid())
self.assertNotEqual(form.errors, {})
self.assertTrue(form.has_error('password'))
self.assertEqual(get_user_model().objects.count(), 0)

def test_form_is_unsuccessful_for_invalid_username(self):
"""Whether a user does not have an invalid username"""

self.data['username'] = "......."
form = UserRegistrationForm(self.data)
self.assertFalse(form.is_valid())
self.assertNotEqual(form.errors, {})
self.assertTrue(form.has_error('username'))
self.assertEqual(get_user_model().objects.count(), 0)

def test_form_is_unsuccessful_for_existing_username_and_email(self):
"""Whether a user does not have an existing username and email"""

form = UserRegistrationForm(self.data)
form.save()
form = UserRegistrationForm(self.data)
self.assertFalse(form.is_valid())
self.assertNotEqual(form.errors, {})
self.assertTrue(form.has_error('username'))
self.assertTrue(form.has_error('email'))
self.assertEqual(get_user_model().objects.count(), 1)
74 changes: 74 additions & 0 deletions project/accounts/tests/test_models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
from django.contrib.auth import get_user_model
from django.test import TestCase
from accounts.models import Profile


class BaseTestCase(TestCase):
"""Base test class to set up test cases"""

def setUp(self) -> None:
user = get_user_model().objects.create_user(username="testuser", email="[email protected]", password="password123")
self.test_profile = Profile.objects.create(user=user, first_name="Test", last_name="User", about_me="About Me")


class ProfileModelTests(BaseTestCase):
"""A class to test Profile model"""

def test_profile_creation(self):
"""Whether the fields of created Profile instance is correct"""

self.assertEqual(self.test_profile.first_name, "Test")
self.assertEqual(self.test_profile.last_name, "User")
self.assertEqual(self.test_profile.about_me, "About Me")
self.assertEqual(self.test_profile.full_name, "Test User")

def test_profile_has_default_image_url(self):
"""Whether a profile has a default image"""

self.assertEqual(self.test_profile.profile_image_url, '/static/img/no_image_md.png')


class ProfileManagerTests(BaseTestCase):
"""A class to test ProfileManager"""

def test_profile_summarize_with_no_history_no_followers_no_following(self):
"""Whether profile summarize is correct without history, followers, and followings"""

data = {
"username": self.test_profile.user.username,
"first_name": self.test_profile.first_name,
"last_name": self.test_profile.last_name,
"about_me": self.test_profile.about_me,
"history": [],
"profile_image": self.test_profile.profile_image_url,
"followers": [],
"following": [],
}
self.assertEqual(Profile.objects.summarize(self.test_profile), data)

def test_profile_chip_summarize(self):
"""Whether profile chip summarize is correct"""

data = {
"username": self.test_profile.user.username,
"first_name": self.test_profile.first_name,
"last_name": self.test_profile.last_name,
"profile_image": self.test_profile.profile_image_url,
}
self.assertEqual(Profile.objects.chip_summarize(self.test_profile), data)

def test_profile_card_summarize(self):
"""Whether profile card summarize is correct"""

data = {
"id": self.test_profile.user.id,
"username": self.test_profile.user.username,
"first_name": self.test_profile.first_name,
"last_name": self.test_profile.last_name,
"about_me": self.test_profile.about_me,
"profile_image": self.test_profile.profile_image_url,
"follow_state": False,
"request_profile": self.test_profile.first_name,
}
self.assertEqual(
Profile.objects.card_summarize(self.test_profile, Profile.objects.get(user=self.test_profile.user)), data)
Loading