Fakultas Ilmu Komputer UI

Commit 0b82fe81 authored by Bimo Iman Smartadi's avatar Bimo Iman Smartadi
Browse files

Panicfix

parents d0d65dda 27c50698
......@@ -63,7 +63,7 @@ It will return a json with key:
* `phone_number` : Your phone number
### 4. To register a location:
Make `POST` request to API endpoint `/informasi-lokasi/lokasi/add/` with the following key:
Make `POST` request to API endpoint `/informasi-fasilitas/lokasi/add/` with the following key:
* `name` : location name
* `altitude` : location altitude, a float.
* `longitude` : location longitude, a float.
......@@ -72,7 +72,7 @@ Make `POST` request to API endpoint `/informasi-lokasi/lokasi/add/` with the fol
* `image` : string of sourc image `.jpg`
### 5. To view a location list:
Make `GET` request to API endpoint `/informasi-lokasi/lokasi/list/`. <br>
Make `GET` request to API endpoint `/informasi-fasilitas/lokasi/list/`. <br>
It will return a json list of locations with key:
* `id` : id of location
* `name` : location name
......@@ -83,7 +83,7 @@ It will return a json list of locations with key:
* `image` : string of sourc image `.jpg`
### 6. To view a location details:
Make `GET` request to API endpoint `/informasi-lokasi/lokasi/detail/*nama_lokasi*/`. <br>
Make `GET` request to API endpoint `/informasi-fasilitas/lokasi/detail/*nama_lokasi*/`. <br>
It will return a json with key:
* `name` : location name
* `altitude` : location altitude, a float.
......@@ -93,7 +93,7 @@ It will return a json with key:
* `image` : string of source image `.jpg`
### 7. To register a facility:
Make `POST` request to API endpoint `/informasi-lokasi/lokasi/add-fasilitas/*nama-lokasi*/` with the following key:
Make `POST` request to API endpoint `/informasi-fasilitas/lokasi/add-fasilitas/*nama-lokasi*/` with the following key:
* `tag` : Fasility Tag
* The options are :
* KURSI_RODA = 'KR'
......@@ -121,7 +121,7 @@ Make `POST` request to API endpoint `/informasi-lokasi/lokasi/add-fasilitas/*nam
<b>Add this to your request header. `Authorization` with value `token *your_token_from_request*`</b>
### 8. To see a facility list from a location:
Make `GET` request to API endpoint `/informasi-lokasi/lokasi/list-fasilitas/*nama-lokasi*/`. <br>
Make `GET` request to API endpoint `/informasi-fasilitas/lokasi/list-fasilitas/*nama-lokasi*/`. <br>
It will return a json with the following key:
* `id`: id of the facility
* `nama_lokasi`: location name of the facility
......@@ -137,7 +137,7 @@ It will return a json with the following key:
* `is_verified`: Verified status
### 9. To see a facility details:
Make `GET` request to API endpoint `/informasi-lokasi/lokasi/detail-fasilitas/*nama-lokasi*/*id-fasilitas*/`. <br>
Make `GET` request to API endpoint `/informasi-fasilitas/lokasi/detail-fasilitas/*nama-lokasi*/*id-fasilitas*/`. <br>
It will return a json with the following key:
* `nama_lokasi`: location name of the facility
* `deskripsi`: the description
......@@ -152,7 +152,7 @@ It will return a json with the following key:
* `is_verified`: Verified status
### 10. To update a facility details:
Make `PUT` request to API endpoint `/informasi-lokasi/lokasi/update-fasilitas/*nama-lokasi*/*id-fasilitas*/`. <br>
Make `PUT` request to API endpoint `/informasi-fasilitas/lokasi/update-fasilitas/*nama-lokasi*/*id-fasilitas*/`. <br>
It requires a request with the following key:
* `deskripsi`: the description
* `rating`: rating of the facility. Default is 3
......@@ -164,14 +164,14 @@ It requires a request with the following key:
of the facility could update the facility</b>
### 11. To update a location phone_number:
Make `PUT` request to API endpoint `/informasi-lokasi/lokasi/update-lokasi/*nama-lokasi*/`. <br>
Make `PUT` request to API endpoint `/informasi-fasilitas/lokasi/update-lokasi/*nama-lokasi*/`. <br>
It requires a request with the following key:
* `no_telp`: the description
<b>Make sure you have token it your request header.</b>
<b>Add this to your request header. `Authorization` with value `token *your_token_from_request*`</b>
### 12. To like / dislike a facility:
Make `PUT` request to API endpoint `/informasi-lokasi/lokasi/like-facility/*nama-lokasi*/*operation*/`. <br>
Make `PUT` request to API endpoint `/informasi-fasilitas/lokasi/like-facility/*nama-lokasi*/*operation*/`. <br>
Replace the `operation` with:
* `like` : if you want to like the facility
* `dislike` : if you want to dislike the facility
......
......@@ -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),
),
]
# Generated by Django 2.1.5 on 2020-05-05 03:38
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('layanan_khusus', '0012_auto_20200505_0314'),
('layanan_khusus', '0018_auto_20200504_0208'),
]
operations = [
]
......@@ -2,6 +2,7 @@ import json
from http import HTTPStatus
from django.test import TestCase, Client
from django.db.utils import IntegrityError
from django.contrib.auth.models import User
from django.urls import path, include, reverse
from .models import Sekolah, Penyandang
from .serializers import SekolahSerializer
......@@ -100,7 +101,10 @@ def auth_setup():
'email': email,
'phone_number': 000000000,
'password': passcode
})
})
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': passcode})
content = json.loads(token_response.content.decode('utf-8'))
......
......@@ -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
argon2-cffi==19.2.0
astroid==2.4.0
astroid==2.0.4
cachetools==4.0.0
certifi==2018.8.24
cffi==1.14.0
......
{% 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