Fakultas Ilmu Komputer UI

Commit 33c48bc9 authored by Usman Sidiq's avatar Usman Sidiq
Browse files

Merge branch 'dev-sidiq' into 'PBI-6-melihat_halaman_detail_fasilitas_publik'

Implementasi email verification

See merge request !53
parents 2014ee53 17a7d2aa
Pipeline #45303 passed with stages
in 8 minutes and 53 seconds
......@@ -10,7 +10,6 @@ UnitTest:
coverage: '/TOTAL\s+\d+\s+\d+\s+(\d+)%/'
before_script:
- pip install -r requirements.txt
- python manage.py makemigrations
- python manage.py migrate
- python manage.py collectstatic --no-input
when: on_success
......
#!/bin/bash
python manage.py makemigrations
python manage.py migrate
......@@ -130,6 +130,9 @@ class InformasiFasilitasTest(TestCase):
def client_user_token(self):
Client().post('/api/register/', self.user_post)
test_user = User.objects.get(username=self.user_post["email"])
test_user.is_active = True
test_user.save()
token_response = Client().post('/api-token-auth/', {'username': self.user_post["email"],
'password': self.user_post["password"]})
content = json.loads(token_response.content.decode('utf-8'))
......@@ -139,6 +142,9 @@ class InformasiFasilitasTest(TestCase):
def client_user_token2(self):
Client().post('/api/register/', self.user_post)
test_user = User.objects.get(username=self.default_username_email)
test_user.is_active = True
test_user.save()
token_response = Client().post('/api-token-auth/', {'username': self.default_username_email,
'password': self.default_password})
content = json.loads(token_response.content.decode('utf-8'))
......@@ -160,6 +166,9 @@ class InformasiFasilitasViewTest(InformasiFasilitasTest):
'email': email,
'phone_number': 1000000,
'password': password})
test_user = User.objects.get(username=email)
test_user.is_active = True
test_user.save()
token_response = Client().post('/api-token-auth/',
{'username': email,
'password': password})
......
......@@ -66,13 +66,7 @@ class LokasiRelatedViewTest(InformasiFasilitasViewTest):
self.assertEqual(response.status_code, HTTPStatus.NOT_FOUND)
def test_cannot_get_add_lokasi(self):
Client().post('/api/register/', self.user_post)
token_response = Client().post('/api-token-auth/', {'username': self.user_post["email"],
'password': self.user_post["password"]})
content = json.loads(token_response.content.decode('utf-8'))
token = content['token']
client = Client(HTTP_AUTHORIZATION='token '+token)
client = self.client_user_token()
response = client.get(reverse('add-lokasi'))
self.assertEqual(response.status_code, HTTPStatus.METHOD_NOT_ALLOWED)
......@@ -109,13 +103,7 @@ class LokasiRelatedViewTest(InformasiFasilitasViewTest):
self.assertEqual(response_json, expected_json)
def test_put_update_detail_lokasi_success(self):
Client().post('/api/register/', self.user_post)
token_response = Client().post('/api-token-auth/', {'username': self.user_post["email"],
'password': self.user_post["password"]})
content = json.loads(token_response.content.decode('utf-8'))
token = content['token']
client = Client(HTTP_AUTHORIZATION='token '+token)
client = self.client_user_token()
urls = reverse('update-lokasi',
kwargs={'nama_lokasi': self.lokasi_test_1["name"]})
response = client.put(urls, data=urlencode({'no_telp': '0000000121', }),
......
# Generated by Django 2.1.5 on 2020-05-04 20:14
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('layanan_khusus', '0011_auto_20200430_1308'),
]
operations = [
migrations.AlterField(
model_name='sekolah',
name='jenis_sekolah',
field=models.CharField(choices=[('IK', 'Inklusi'), ('SG', 'Segregasi')], default='IK', max_length=2),
),
]
......@@ -5,7 +5,9 @@ from rest_framework import status
from django.test import TestCase, SimpleTestCase, Client
from django.urls import include, path, reverse
from registrasi.models import BisaGoUser
from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
from .tokens import account_activation_token
from django.utils.encoding import force_bytes, force_text
class UserTests(APITestCase):
urlpatterns = [
......@@ -17,7 +19,7 @@ class UserTests(APITestCase):
data = {'name': 'Astraykai',
'email':'astraykai@gmail.com',
'phone_number':'089892218567',
'password':'chingchenghanji',}
'password':'chingchenghanji'}
self.client.post(url, data)
def test_create_user(self):
......@@ -28,7 +30,8 @@ class UserTests(APITestCase):
data = {'name': 'Astray',
'email':'astrayyahoo@gmail.com',
'phone_number':'08989221856',
'password':'chingchenghanji',}
'password':'chingchenghanji',
'is_active': True}
response = self.client.post(url, data)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(BisaGoUser.objects.count(), 2)
......@@ -55,9 +58,59 @@ class UserTests(APITestCase):
json_test = json.loads(response.content)
self.assertEqual(len(json_test), 1)
def test_incomplete_create_user(self):
url = reverse('create-user')
data = {'name': 'Astray',
'email':'astrayyahoo@gmail.com',
'password':'chingchenghanji',
'is_active': True}
response = self.client.post(url, data)
self.assertEqual(response.status_code, status.HTTP_500_INTERNAL_SERVER_ERROR)
json_response = json.loads(response.content)
self.assertEqual(json_response['response'], 'bad request. \'phone_number\' key needed')
def test_user_already_exist(self):
url = reverse('create-user')
data = {'name': 'Astraykai',
'email':'astraykai@gmail.com',
'phone_number':'089892218567',
'password':'chingchenghanji',
'is_active': True}
response = self.client.post(url, data)
self.assertEqual(response.status_code, status.HTTP_500_INTERNAL_SERVER_ERROR)
json_response = json.loads(response.content)
self.assertEqual(json_response['response'], 'User is already exist')
def test_invalid_request(self):
url = reverse('user-list')
data = {'name': 'Astraykai',
'email':'astraykai@gmail.com',
'phone_number':'089892218567',
'password':'chingchenghanji',
'is_active': True}
response = self.client.post(url, data)
self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED)
json_response = json.loads(response.content)
def test_account_login(self):
pass
def test_without_verification(self):
url = reverse('api-token-auth')
data = {'username': 'astraykai@gmail.com',
'password':'chingchenghanji'}
response = self.client.post(url, data)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
def test_activation_function(self):
user = BisaGoUser.objects.get(phone_number='089892218567').user
uid = urlsafe_base64_encode(force_bytes(user.pk)).decode()
token = account_activation_token.make_token(user)
url = reverse('activate', kwargs={'uidb64' : uid, 'token' : token})
response = self.client.get(url)
json_response = json.loads(response.content)
self.assertEqual(json_response['response'], 'User activated')
class InfoTests(APITestCase, URLPatternsTestCase):
pass
from django.contrib.auth.tokens import PasswordResetTokenGenerator
from django.utils import six
class TokenGenerator(PasswordResetTokenGenerator):
def _make_hash_value(self, user, timestamp):
return (
six.text_type(user.pk) + six.text_type(timestamp) +
six.text_type(user.is_active)
)
account_activation_token = TokenGenerator()
\ No newline at end of file
......@@ -7,8 +7,10 @@ from django.views.generic import TemplateView
urlpatterns = [
path('user-list/', new_rest_api.views.user_list, name='user-list'),
path('user-detail/<str:email>', new_rest_api.views.user_details, name='user-details'),
path('user-detail/?email=<str:email>', new_rest_api.views.user_details, name='user-details-get'),
path('register/', new_rest_api.views.register_user, name='create-user'),
path('user-list/', new_rest_api.views.user_list,name='user-list'),
path('user-detail/<str:email>', new_rest_api.views.user_details,name='user-details'),
path('user-detail/?email=<str:email>', new_rest_api.views.user_details,name='user-details-get'),
path('register/', new_rest_api.views.register_user,name='create-user'),
path(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
new_rest_api.views.activate, name='activate'),
]
from http import HTTPStatus
from django.contrib.auth.models import User
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
......@@ -15,6 +14,15 @@ from rest_framework.decorators import api_view, permission_classes, authenticati
from registrasi.models import BisaGoUser
from django.db.utils import IntegrityError
from http import HTTPStatus as status
from django.contrib.sites.models import Site
from django.utils.encoding import force_bytes, force_text
from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
from django.template.loader import render_to_string
from .tokens import account_activation_token
from django.core.mail import EmailMessage
def request_error_message(request_kind):
return "get {} request instead".format(request_kind)
......@@ -35,9 +43,9 @@ def user_list(request):
"name": user.user.last_name,
"email": user.user.email,
"phone_number": user.phone_number})
return JsonResponse(json_return, safe=False, status=HTTPStatus.OK)
return JsonResponse(json_return, safe=False, status=status.OK)
else:
return JsonResponse({'response' : request_error_message("get")}, status=HTTPStatus.METHOD_NOT_ALLOWED)
return JsonResponse({'response' : request_error_message("get")}, status=status.METHOD_NOT_ALLOWED)
@api_view(['GET'])
@authentication_classes([])
......@@ -50,7 +58,7 @@ def user_details(request, email):
"name": user.last_name,
"email": user.email,
"phone_number": bisa_go_user.phone_number}
return JsonResponse(json_return, safe=False, status=HTTPStatus.OK)
return JsonResponse(json_return, safe=False, status=status.OK)
@api_view(['POST'])
......@@ -64,8 +72,43 @@ def register_user(request):
email = request.POST['email']
password = request.POST['password']
user = User.objects.create_user(username=email, email=email, password=password, last_name=name)
BisaGoUser.objects.create(user=user, phone_number=phone_number)
return JsonResponse({'response' : 'User created', 'email':email, 'name':name}, status=HTTPStatus.CREATED)
except KeyError as missing_key:
return JsonResponse({'response':missing_key_message(str(missing_key))}, status=HTTPStatus.BAD_REQUEST)
\ No newline at end of file
user.is_active = False
user.save()
mail_subject = "Activate your account"
message = render_to_string('acc_active_email.html', {
'user' : user,
'domain' : request.get_host,
'uid' : urlsafe_base64_encode(force_bytes(user.pk)).decode(),
'token' : account_activation_token.make_token(user),
})
mail = EmailMessage(mail_subject, message, to=[email])
mail.send()
BisaGoUser.objects.create(user= user, phone_number=phone_number)
return JsonResponse({'response' : 'User created', 'email':email, 'name':name}, status = status.CREATED)
except KeyError as e:
return JsonResponse({'response' : missing_key_message(str(e))}, status = status.INTERNAL_SERVER_ERROR)
except IntegrityError as e:
return JsonResponse({'response' : 'User is already exist'}, status = status.INTERNAL_SERVER_ERROR)
except MethodNotAllowed :
return JsonResponse({'response' : request_error_message("post")}, status=status.METHOD_NOT_ALLOWED)
@api_view(['GET'])
@authentication_classes([])
@permission_classes([])
def activate(request, uidb64, token):
if request.method == 'GET':
try:
uid = force_text(urlsafe_base64_decode(uidb64))
user = User.objects.get(pk=uid)
except(TypeError, ValueError, OverflowError, User.DoesNotExist):
user = None
if user is not None and account_activation_token.check_token(user, token):
user.is_active = True
user.save()
# login(request, user)
# return redirect('home')
return JsonResponse({'response' : 'User activated'}, status = status.CREATED)
else:
return JsonResponse({'response' : request_error_message('get')}, status = status.BAD_REQUEST)
else :
return JsonResponse({'response' : request_error_message("get")}, status = BAD_REQUEST)
......@@ -71,10 +71,11 @@ MIDDLEWARE = [
ROOT_URLCONF = 'pplbackend.urls'
TEMPLATES_ROOT = os.path.join(BASE_DIR, "templates")
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'DIRS': [TEMPLATES_ROOT],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
......@@ -201,3 +202,9 @@ PASSWORD_HASHERS = [
'django.contrib.auth.hashers.Argon2PasswordHasher',
'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
]
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = os.getenv("EMAIL_HOST_USER")
EMAIL_HOST_PASSWORD = os.getenv("EMAIL_HOST_PASSWORD")
EMAIL_PORT = 587
\ No newline at end of file
{% autoescape off %}
Hi {{ user.username }},
Please click on the link to confirm your registration,
http://{{ domain }}{% url 'activate' uidb64=uid token=token %}
{% endautoescape %}
\ No newline at end of file
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment