Fakultas Ilmu Komputer UI

Commit d3e32aeb authored by Bayukanta Iqbal Gunawan's avatar Bayukanta Iqbal Gunawan
Browse files

Merge branch 'staging' into docker

parents 655a37da e94a9f10
# Generated by Django 2.1.5 on 2020-06-01 16:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('informasi_fasilitas', '0002_dislikes_likes'),
]
operations = [
migrations.AlterField(
model_name='fasilitas',
name='image',
field=models.ImageField(default='', upload_to='fasilitas/'),
preserve_default=False,
),
migrations.AlterField(
model_name='lokasi',
name='image',
field=models.ImageField(upload_to='lokasi/'),
),
]
# Generated by Django 2.1.5 on 2020-06-01 16:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('informasi_fasilitas', '0003_auto_20200601_2353'),
]
operations = [
migrations.AlterField(
model_name='fasilitas',
name='image',
field=models.ImageField(default=None, upload_to='fasilitas/'),
),
]
# Generated by Django 2.1.5 on 2020-06-01 17:43
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('informasi_fasilitas', '0004_auto_20200601_2354'),
]
operations = [
migrations.AlterField(
model_name='fasilitas',
name='image',
field=models.ImageField(default=None, null=True, upload_to='fasilitas/'),
),
]
...@@ -40,7 +40,7 @@ class Lokasi(models.Model): ...@@ -40,7 +40,7 @@ class Lokasi(models.Model):
longitude = models.FloatField() longitude = models.FloatField()
alamat = models.CharField(max_length=100) alamat = models.CharField(max_length=100)
no_telp = models.CharField(max_length=16) no_telp = models.CharField(max_length=16)
image = models.ImageField(upload_to="static/img", null=True) image = models.ImageField(upload_to='lokasi/')
objects = models.Manager() objects = models.Manager()
POINT_FIELD = ""+str(latitude)+","+str(longitude) POINT_FIELD = ""+str(latitude)+","+str(longitude)
...@@ -57,7 +57,7 @@ class Fasilitas(models.Model): ...@@ -57,7 +57,7 @@ class Fasilitas(models.Model):
dislike = models.IntegerField(default=0) dislike = models.IntegerField(default=0)
rating = models.IntegerField(default=3) rating = models.IntegerField(default=3)
tag = MultiSelectField(choices=FACILITIES, null=True, default=None) tag = MultiSelectField(choices=FACILITIES, null=True, default=None)
image = models.ImageField(upload_to="static/img", null=True, default=None) image = models.ImageField(upload_to="fasilitas/", null=True, default=None)
is_verified = models.BooleanField(default=False) is_verified = models.BooleanField(default=False)
class Komentar(models.Model): class Komentar(models.Model):
...@@ -77,4 +77,4 @@ class Dislikes(models.Model): ...@@ -77,4 +77,4 @@ class Dislikes(models.Model):
objects = models.Manager() objects = models.Manager()
user = models.ForeignKey(User, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE)
fasilitas = models.ForeignKey(Fasilitas, on_delete=models.CASCADE) fasilitas = models.ForeignKey(Fasilitas, on_delete=models.CASCADE)
created = models.DateTimeField(auto_now_add=True) created = models.DateTimeField(auto_now_add=True)
\ No newline at end of file
...@@ -3,7 +3,8 @@ from rest_framework import serializers ...@@ -3,7 +3,8 @@ from rest_framework import serializers
from .models import Lokasi from .models import Lokasi
class LokasiSerializer(serializers.HyperlinkedModelSerializer): class LokasiSerializer(serializers.HyperlinkedModelSerializer):
image = serializers.ImageField(required=False)
class Meta: class Meta:
model = Lokasi model = Lokasi
fields = ('id', 'name', 'latitude', 'longitude', 'alamat', 'no_telp', 'image') fields = ('id', 'name', 'latitude', 'longitude', 'alamat', 'no_telp', 'image')
\ No newline at end of file
\ No newline at end of file
...@@ -29,7 +29,7 @@ class FasilitasRelatedViewTest(InformasiFasilitasViewTest): ...@@ -29,7 +29,7 @@ class FasilitasRelatedViewTest(InformasiFasilitasViewTest):
'dislike': self.default_dislike, 'dislike': self.default_dislike,
'rating': self.default_rating, 'rating': self.default_rating,
'tag': ['KR', 'RT'], 'tag': ['KR', 'RT'],
'image': str(fasilitas.image), 'image': '/media/' + str(fasilitas.image),
'is_verified': False} 'is_verified': False}
} }
...@@ -81,7 +81,7 @@ class FasilitasRelatedViewTest(InformasiFasilitasViewTest): ...@@ -81,7 +81,7 @@ class FasilitasRelatedViewTest(InformasiFasilitasViewTest):
kwargs={'nama_lokasi': self.default_lokasi_name}) kwargs={'nama_lokasi': self.default_lokasi_name})
response = client.post(urls, {'deskripsi': PENJELASAN, response = client.post(urls, {'deskripsi': PENJELASAN,
'rating': 2, 'rating': 2,
'tag': 'KR RT'}) 'tag': 'KR RT', 'image': 'test.jpg'})
self.assertEqual(response.status_code, HTTPStatus.CREATED) self.assertEqual(response.status_code, HTTPStatus.CREATED)
def test_cannot_get_add_fasilitas(self): def test_cannot_get_add_fasilitas(self):
......
from django.urls import path from django.urls import path
from . import views from . import views
from .views import *
urlpatterns = [ urlpatterns = [
path('lokasi/list/', views.lokasi_list, name='lokasi-list'), path('lokasi/list/', views.lokasi_list, name='lokasi-list'),
......
...@@ -11,6 +11,11 @@ from rest_framework.permissions import IsAuthenticated ...@@ -11,6 +11,11 @@ from rest_framework.permissions import IsAuthenticated
from .serializers import LokasiSerializer from .serializers import LokasiSerializer
from .models import Lokasi, Fasilitas, Komentar, Likes, Dislikes from .models import Lokasi, Fasilitas, Komentar, Likes, Dislikes
from rest_framework.parsers import FileUploadParser
from rest_framework.views import APIView
TIME_FORMAT = "%d-%m-%Y %H:%M:%S" TIME_FORMAT = "%d-%m-%Y %H:%M:%S"
...@@ -48,7 +53,7 @@ def lokasi_details(request, nama_lokasi): ...@@ -48,7 +53,7 @@ def lokasi_details(request, nama_lokasi):
def add_lokasi(request): def add_lokasi(request):
try: try:
if request.method == 'POST': if request.method == 'POST':
data = request.POST data = request.data
serializer = LokasiSerializer(data=data) serializer = LokasiSerializer(data=data)
if serializer.is_valid(): if serializer.is_valid():
serializer.save() serializer.save()
...@@ -58,7 +63,6 @@ def add_lokasi(request): ...@@ -58,7 +63,6 @@ def add_lokasi(request):
except Exception as err: except Exception as err:
return JsonResponse({'response': str(err)}, status=HTTPStatus.NOT_FOUND) return JsonResponse({'response': str(err)}, status=HTTPStatus.NOT_FOUND)
@api_view(['PUT']) @api_view(['PUT'])
@authentication_classes([TokenAuthentication]) @authentication_classes([TokenAuthentication])
@permission_classes([IsAuthenticated]) @permission_classes([IsAuthenticated])
...@@ -101,7 +105,7 @@ def list_fasilitas(request, nama_lokasi): ...@@ -101,7 +105,7 @@ def list_fasilitas(request, nama_lokasi):
fasilitas_details["dislike"] = fasilitas.dislike fasilitas_details["dislike"] = fasilitas.dislike
fasilitas_details["rating"] = fasilitas.rating fasilitas_details["rating"] = fasilitas.rating
fasilitas_details["tag"] = fasilitas.tag fasilitas_details["tag"] = fasilitas.tag
fasilitas_details["image"] = str(fasilitas.image) fasilitas_details["image"] = '/media/'+str(fasilitas.image)
fasilitas_details["is_verified"] = fasilitas.is_verified fasilitas_details["is_verified"] = fasilitas.is_verified
return JsonResponse(return_json, status=HTTPStatus.OK) return JsonResponse(return_json, status=HTTPStatus.OK)
except Exception as error: except Exception as error:
...@@ -120,8 +124,8 @@ def add_fasilitas(request, nama_lokasi): ...@@ -120,8 +124,8 @@ def add_fasilitas(request, nama_lokasi):
rating = request.POST['rating'] rating = request.POST['rating']
tag = request.POST['tag'].split() tag = request.POST['tag'].split()
image = "" image = ""
if 'image' in request.POST.keys(): if 'image' in request.FILES.keys():
image = str(request.POST['image']) image = request.FILES['image']
fasilitas = Fasilitas.objects.create(lokasi=lokasi, fasilitas = Fasilitas.objects.create(lokasi=lokasi,
user=user, user=user,
deskripsi=deskripsi, deskripsi=deskripsi,
...@@ -149,7 +153,8 @@ def detail_fasilitas(request, nama_lokasi, id): ...@@ -149,7 +153,8 @@ def detail_fasilitas(request, nama_lokasi, id):
fasilitas.like = Likes.objects.filter(fasilitas=fasilitas).count() fasilitas.like = Likes.objects.filter(fasilitas=fasilitas).count()
fasilitas.dislike = Dislikes.objects.filter( fasilitas.dislike = Dislikes.objects.filter(
fasilitas=fasilitas).count() fasilitas=fasilitas).count()
return_json = {"nama_lokasi": lokasi.name, return_json = {"id": fasilitas.id,
"nama_lokasi": lokasi.name,
"deskripsi": fasilitas.deskripsi, "deskripsi": fasilitas.deskripsi,
"creator": user.last_name, "creator": user.last_name,
"creator_email": user.email, "creator_email": user.email,
...@@ -158,7 +163,7 @@ def detail_fasilitas(request, nama_lokasi, id): ...@@ -158,7 +163,7 @@ def detail_fasilitas(request, nama_lokasi, id):
"dislike": fasilitas.dislike, "dislike": fasilitas.dislike,
"rating": fasilitas.rating, "rating": fasilitas.rating,
"tag": fasilitas.tag, "tag": fasilitas.tag,
"image": str(fasilitas.image), "image": '/media/' + str(fasilitas.image),
"is_verified": fasilitas.is_verified} "is_verified": fasilitas.is_verified}
return JsonResponse(return_json, status=HTTPStatus.OK) return JsonResponse(return_json, status=HTTPStatus.OK)
except KeyError as missing_key: except KeyError as missing_key:
......
from http import HTTPStatus as status
from django.contrib.auth.models import User from django.contrib.auth.models import User
from django.http import JsonResponse from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt from django.views.decorators.csrf import csrf_exempt
...@@ -15,7 +17,6 @@ from rest_framework.decorators import api_view, permission_classes, authenticati ...@@ -15,7 +17,6 @@ from rest_framework.decorators import api_view, permission_classes, authenticati
from registrasi.models import BisaGoUser from registrasi.models import BisaGoUser
from django.db.utils import IntegrityError from django.db.utils import IntegrityError
from http import HTTPStatus as status
from django.contrib.sites.models import Site from django.contrib.sites.models import Site
from django.utils.encoding import force_bytes, force_text 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 urlsafe_base64_encode, urlsafe_base64_decode
...@@ -36,9 +37,8 @@ def missing_key_message(key): ...@@ -36,9 +37,8 @@ def missing_key_message(key):
@permission_classes([]) @permission_classes([])
def user_list(request): def user_list(request):
if request.method == 'GET': if request.method == 'GET':
user_list = BisaGoUser.objects.all()
json_return = [] json_return = []
for user in user_list: for user in BisaGoUser.objects.all():
json_return.append({"username":user.user.email, json_return.append({"username":user.user.email,
"name": user.user.last_name, "name": user.user.last_name,
"email": user.user.email, "email": user.user.email,
...@@ -83,12 +83,12 @@ def register_user(request): ...@@ -83,12 +83,12 @@ def register_user(request):
}) })
mail = EmailMessage(mail_subject, message, to=[email]) mail = EmailMessage(mail_subject, message, to=[email])
mail.send() mail.send()
BisaGoUser.objects.create(user= user, phone_number=phone_number) BisaGoUser.objects.create(user=user, phone_number=phone_number)
return JsonResponse({'response' : 'User created', 'email':email, 'name':name}, status = status.CREATED) return JsonResponse({'response' : 'User created', 'email':email, 'name':name}, status = status.CREATED)
except KeyError as e: except KeyError as e:
return JsonResponse({'response' : missing_key_message(str(e))}, status = status.INTERNAL_SERVER_ERROR) return JsonResponse({'response' : missing_key_message(str(e))}, status=status.INTERNAL_SERVER_ERROR)
except IntegrityError as e: except IntegrityError as e:
return JsonResponse({'response' : 'User is already exist'}, status = status.INTERNAL_SERVER_ERROR) return JsonResponse({'response' : 'User is already exist'}, status=status.INTERNAL_SERVER_ERROR)
@api_view(['GET']) @api_view(['GET'])
...@@ -109,5 +109,5 @@ def activate(request, uidb64, token): ...@@ -109,5 +109,5 @@ def activate(request, uidb64, token):
return JsonResponse({'response' : 'User activated'}, status = status.CREATED) return JsonResponse({'response' : 'User activated'}, status = status.CREATED)
else: else:
return JsonResponse({'response' : request_error_message('get')}, status = status.BAD_REQUEST) return JsonResponse({'response' : request_error_message('get')}, status = status.BAD_REQUEST)
else : else:
return JsonResponse({'response' : request_error_message("get")}, status = status.BAD_REQUEST) return JsonResponse({'response' : request_error_message("get")}, status = status.BAD_REQUEST)
from django.shortcuts import render import requests
import random
from urllib.parse import parse_qs, urlparse
from rest_framework.utils import json
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework_simplejwt.tokens import RefreshToken
from rest_framework.permissions import IsAuthenticated
from rest_framework.authtoken.models import Token
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse, HttpResponse
from django.contrib.auth import authenticate
from django.contrib.auth.base_user import BaseUserManager
from django.contrib.auth.hashers import make_password
from django.contrib.auth.models import User
from pplbackend.settings import GOOGLE_OAUTH2_CLIENT_ID, GOOGLE_OAUTH2_CLIENT_SECRET
from registrasi.models import BisaGoUser
@csrf_exempt
def request_token(request):
if request.method == "POST":
email = request.POST["username"]
password = request.POST["password"]
google = request.POST.get("google", False)
response = {}
status = 200
if google:
access_token = request.POST["access_token"]
name = request.POST["name"]
try:
user = User.objects.get(email=email)
except User.DoesNotExist:
user, status = _request_token_from_google(email, access_token, name)
else:
try:
user = authenticate(request, username=email, password=password)
except User.DoesNotExist:
response["response"] = "User not exist"
return JsonResponse(response, status=404)
if status != 200:
return response
if user is not None:
if user.is_active:
#print("user active")
token, create = Token.objects.get_or_create(user=user)
response = {}
response['username'] = user.username
response['token'] = token.key
response['token_type'] = "token"
return JsonResponse(response, status=200)
else:
response["response"] = "Please activate your account"
return JsonResponse(response, status=400)
else:
response["response"] = "Wrong password"
return JsonResponse(response, status=400)
@csrf_exempt
def _request_token_from_google(email, access_token, name):
payload = {'access_token': access_token} # validate the token
req = requests.get('https://www.googleapis.com/oauth2/v2/userinfo', params=payload)
data = json.loads(req.text)
if 'error' in data:
content = {'message': 'wrong google token / this google token is already expired.'}
return None, JsonResponse(content, status=404)
user = User()
user.username = email
# provider random default password
user.password = make_password(BaseUserManager().make_random_password())
user.email = email
user.is_active = True
user.last_name = name
user.save()
random_generated_phone_number = 'x'.join([str(random.randint(0, 9)) for i in range(8)])
BisaGoUser.objects.create(user=user, phone_number=random_generated_phone_number)
return user, 200
@csrf_exempt
def validate_google_token(email, access_token):
payload = {'access_token': access_token} # validate the token
req = requests.get('https://www.googleapis.com/oauth2/v2/userinfo', params=payload)
data = json.loads(req.text)
if 'error' in data:
content = {'message': 'wrong google token / this google token is already expired.'}
return None, JsonResponse(content, status=404)
return User.objects.get(email=email)
# Create your views here.
...@@ -12,6 +12,7 @@ https://docs.djangoproject.com/en/3.0/ref/settings/ ...@@ -12,6 +12,7 @@ https://docs.djangoproject.com/en/3.0/ref/settings/
import dj_database_url import dj_database_url
import os import os
from datetime import timedelta
# Build paths inside the project like this: os.path.join(BASE_DIR, ...) # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
...@@ -194,6 +195,7 @@ REST_FRAMEWORK = { ...@@ -194,6 +195,7 @@ REST_FRAMEWORK = {
'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.TokenAuthentication',
'rest_framework_simplejwt.authentication.JWTAuthentication',
], ],
'DEFAULT_PERMISSION_CLASSES': [ 'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated', 'rest_framework.permissions.IsAuthenticated',
...@@ -211,4 +213,14 @@ EMAIL_USE_TLS = True ...@@ -211,4 +213,14 @@ EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = os.getenv("EMAIL_HOST_USER") EMAIL_HOST_USER = os.getenv("EMAIL_HOST_USER")
EMAIL_HOST_PASSWORD = os.getenv("EMAIL_HOST_PASSWORD") EMAIL_HOST_PASSWORD = os.getenv("EMAIL_HOST_PASSWORD")
EMAIL_PORT = 587 EMAIL_PORT = 587
\ No newline at end of file
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
GOOGLE_OAUTH2_CLIENT_ID = os.getenv("GOOGLE_OAUTH2_CLIENT_ID")
GOOGLE_OAUTH2_CLIENT_SECRET = os.getenv("GOOGLE_OAUTH_CLIENT_SECRET")
SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': timedelta(days=1),
'REFRESH_TOKEN_LIFETIME': timedelta(days=90),
}
\ No newline at end of file
...@@ -17,8 +17,11 @@ from django.contrib import admin ...@@ -17,8 +17,11 @@ from django.contrib import admin
from django.urls import path,include from django.urls import path,include
from rest_framework import routers from rest_framework import routers
from rest_framework.authtoken import views from rest_framework.authtoken import views
from django.conf.urls.static import static
from django.conf import settings
import new_rest_api.views import new_rest_api.views
import new_rest_api.urls import new_rest_api.urls
import oauth.views
from django.views.generic import TemplateView from django.views.generic import TemplateView
...@@ -35,7 +38,9 @@ urlpatterns = [ ...@@ -35,7 +38,9 @@ urlpatterns = [
path('api/', include(new_rest_api.urls)), path('api/', include(new_rest_api.urls)),
path('o/', include('oauth2_provider.urls', namespace='oauth2_provider')), path('o/', include('oauth2_provider.urls', namespace='oauth2_provider')),
path('', include(router.urls)), path('', include(router.urls)),
path('api-token-auth/', views.obtain_auth_token, name='api-token-auth'), path('api-token-auth/', oauth.views.request_token, name='api-token-auth'),
path('request-token/', views.obtain_auth_token, name='token-request-auth'),
#path('api-token-auth/', views.obtain_auth_token, name='api-token-auth'),
path('informasi-fasilitas/', include('informasi_fasilitas.urls')), path('informasi-fasilitas/', include('informasi_fasilitas.urls')),
path('layanan-khusus/', include('layanan_khusus.urls')) path('layanan-khusus/', include('layanan_khusus.urls'))
] ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
...@@ -8,6 +8,7 @@ django-multiselectfield==0.1.12 ...@@ -8,6 +8,7 @@ django-multiselectfield==0.1.12
django-oauth-toolkit==1.3.2 django-oauth-toolkit==1.3.2
django-rest-auth==0.9.5 django-rest-auth==0.9.5
djangorestframework==3.11.0 djangorestframework==3.11.0
djangorestframework-simplejwt==4.4.0
google-api-python-client==1.7.11 google-api-python-client==1.7.11
google-auth==1.11.2 google-auth==1.11.2
google-auth-httplib2==0.0.3 google-auth-httplib2==0.0.3
......
{% autoescape off %} {% autoescape off %}
Hi {{ user.username }}, Hai {{ user.username }},
Please click on the link to confirm your registration, Selamat datang di aplikasi bisaGO.
Sebelum anda bisa menggunakan akun anda, silahkan melakukan aktivasi dengan meng-klik link di bawah ini.
http://{{ domain }}{% url 'activate' uidb64=uid token=token %} http://{{ domain }}{% url 'activate' uidb64=uid token=token %}
Terima kasih dan selamat menggunakan bisaGO.
Salam,
bisaGO dev Team
{% endautoescape %} {% 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