Fakultas Ilmu Komputer UI

Commit 340b17e8 authored by Usman Sidiq's avatar Usman Sidiq
Browse files

Merge branch 'PBI-3-registrasi_login' into 'staging'

Pbi 3 registrasi login

See merge request !60
parents 124b0753 1a9c66f4
Pipeline #48775 passed with stages
in 11 minutes and 49 seconds
# 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):
longitude = models.FloatField()
alamat = models.CharField(max_length=100)
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()
POINT_FIELD = ""+str(latitude)+","+str(longitude)
......@@ -57,7 +57,7 @@ class Fasilitas(models.Model):
dislike = models.IntegerField(default=0)
rating = models.IntegerField(default=3)
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)
class Komentar(models.Model):
......
......@@ -3,7 +3,8 @@ from rest_framework import serializers
from .models import Lokasi
class LokasiSerializer(serializers.HyperlinkedModelSerializer):
image = serializers.ImageField(required=False)
class Meta:
model = Lokasi
fields = ('id', 'name', 'latitude', 'longitude', 'alamat', 'no_telp', 'image')
\ No newline at end of file
\ No newline at end of file
......@@ -81,7 +81,7 @@ class FasilitasRelatedViewTest(InformasiFasilitasViewTest):
kwargs={'nama_lokasi': self.default_lokasi_name})
response = client.post(urls, {'deskripsi': PENJELASAN,
'rating': 2,
'tag': 'KR RT'})
'tag': 'KR RT', 'image': 'test.jpg'})
self.assertEqual(response.status_code, HTTPStatus.CREATED)
def test_cannot_get_add_fasilitas(self):
......
from django.urls import path
from . import views
from .views import *
urlpatterns = [
path('lokasi/list/', views.lokasi_list, name='lokasi-list'),
......
......@@ -11,6 +11,11 @@ from rest_framework.permissions import IsAuthenticated
from .serializers import LokasiSerializer
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"
......@@ -48,7 +53,7 @@ def lokasi_details(request, nama_lokasi):
def add_lokasi(request):
try:
if request.method == 'POST':
data = request.POST
data = request.data
serializer = LokasiSerializer(data=data)
if serializer.is_valid():
serializer.save()
......@@ -58,7 +63,6 @@ def add_lokasi(request):
except Exception as err:
return JsonResponse({'response': str(err)}, status=HTTPStatus.NOT_FOUND)
@api_view(['PUT'])
@authentication_classes([TokenAuthentication])
@permission_classes([IsAuthenticated])
......@@ -120,8 +124,8 @@ def add_fasilitas(request, nama_lokasi):
rating = request.POST['rating']
tag = request.POST['tag'].split()
image = ""
if 'image' in request.POST.keys():
image = str(request.POST['image'])
if 'image' in request.FILES.keys():
image = request.FILES['image']
fasilitas = Fasilitas.objects.create(lokasi=lokasi,
user=user,
deskripsi=deskripsi,
......@@ -149,7 +153,8 @@ def detail_fasilitas(request, nama_lokasi, id):
fasilitas.like = Likes.objects.filter(fasilitas=fasilitas).count()
fasilitas.dislike = Dislikes.objects.filter(
fasilitas=fasilitas).count()
return_json = {"nama_lokasi": lokasi.name,
return_json = {"id": fasilitas.id,
"nama_lokasi": lokasi.name,
"deskripsi": fasilitas.deskripsi,
"creator": user.last_name,
"creator_email": user.email,
......
from http import HTTPStatus as status
from django.contrib.auth.models import User
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
......@@ -15,7 +17,6 @@ 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
......@@ -36,9 +37,8 @@ def missing_key_message(key):
@permission_classes([])
def user_list(request):
if request.method == 'GET':
user_list = BisaGoUser.objects.all()
json_return = []
for user in user_list:
for user in BisaGoUser.objects.all():
json_return.append({"username":user.user.email,
"name": user.user.last_name,
"email": user.user.email,
......@@ -83,12 +83,12 @@ def register_user(request):
})
mail = EmailMessage(mail_subject, message, to=[email])
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)
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:
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'])
......@@ -109,5 +109,5 @@ def activate(request, uidb64, token):
return JsonResponse({'response' : 'User activated'}, status = status.CREATED)
else:
return JsonResponse({'response' : request_error_message('get')}, status = status.BAD_REQUEST)
else :
else:
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"]
try:
user = User.objects.get(email=email)
except User.DoesNotExist:
user, status = _request_token_from_google(email, access_token)
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):
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.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/
import dj_database_url
import os
from datetime import timedelta
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
......@@ -190,6 +191,7 @@ REST_FRAMEWORK = {
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication',
'rest_framework_simplejwt.authentication.JWTAuthentication',
],
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
......@@ -208,3 +210,13 @@ EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = os.getenv("EMAIL_HOST_USER")
EMAIL_HOST_PASSWORD = os.getenv("EMAIL_HOST_PASSWORD")
EMAIL_PORT = 587
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
from django.urls import path,include
from rest_framework import routers
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.urls
import oauth.views
from django.views.generic import TemplateView
......@@ -35,7 +38,9 @@ urlpatterns = [
path('api/', include(new_rest_api.urls)),
path('o/', include('oauth2_provider.urls', namespace='oauth2_provider')),
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('layanan-khusus/', include('layanan_khusus.urls'))
]
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
......@@ -16,6 +16,7 @@ django-multiselectfield==0.1.12
django-oauth-toolkit==1.3.2
django-rest-auth==0.9.5
djangorestframework==3.11.0
djangorestframework-simplejwt==4.4.0
google-api-python-client==1.7.11
google-auth==1.11.2
google-auth-httplib2==0.0.3
......
{% autoescape off %}
Hi {{ user.username }},
Please click on the link to confirm your registration,
Hai {{ user.username }},
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 %}
Terima kasih dan selamat menggunakan bisaGO.
Salam,
bisaGO dev Team
{% 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