Commit dcb4c85a authored by Tarsvini's avatar Tarsvini

commit 1

lab_9
parent 9ea070d3
Pipeline #14827345 failed with stages
in 40 seconds
import requests
DRONE_API = 'https://www.enterkomputer.com/api/product/drone.json'
SOUNDCARD_API = 'https://www.enterkomputer.com/api/product/soundcard.json'
OPTICAL_API = 'https://www.enterkomputer.com/api/product/optical.json'
def get_drones():
drones = requests.get(DRONE_API)
return drones
# lengkapi pemanggilan utk SOUNDCARD_API dan OPTICAL_API untuk mengerjakan CHALLENGE
import requests
API_MAHASISWA = "https://api-dev.cs.ui.ac.id/siakngcs/mahasiswa/"
API_VERIFY_USER = "https://akun.cs.ui.ac.id/oauth/token/verify/"
def get_access_token(username, password):
try:
url = "https://akun.cs.ui.ac.id/oauth/token/"
payload = "username=" + username + "&password=" + password + "&grant_type=password"
headers = {
'authorization': "Basic WDN6TmtGbWVwa2RBNDdBU05NRFpSWDNaOWdxU1UxTHd5d3U1V2VwRzpCRVFXQW43RDl6a2k3NEZ0bkNpWVhIRk50Ymg3eXlNWmFuNnlvMU1uaUdSVWNGWnhkQnBobUU5TUxuVHZiTTEzM1dsUnBwTHJoTXBkYktqTjBxcU9OaHlTNGl2Z0doczB0OVhlQ3M0Ym1JeUJLMldwbnZYTXE4VU5yTEFEMDNZeA==",
'cache-control': "no-cache",
'content-type': "application/x-www-form-urlencoded"
}
response = requests.request("POST", url, data=payload, headers=headers)
return response.json()["access_token"]
except Exception as e:
return None
# raise Exception("username atau password sso salah, input : [{}, {}]".format(username, password,))
def get_client_id():
client_id = 'X3zNkFmepkdA47ASNMDZRX3Z9gqSU1Lwywu5WepG'
return client_id
def verify_user(access_token):
print ("#get identity number")
parameters = {"access_token": access_token, "client_id": get_client_id()}
response = requests.get(API_VERIFY_USER, params=parameters)
print ("response => ", response.json())
return response.json()
def get_data_user(access_token, id):
print ("#get data user => ", id)
parameters = {"access_token": access_token, "client_id": get_client_id()}
response = requests.get(API_MAHASISWA+id, params=parameters)
print ("response => ", response.text)
print ("response => ", response.json())
return response.json()
from django.contrib import messages
from django.http import HttpResponseRedirect
from django.urls import reverse
from .csui_helper import get_access_token, verify_user
#authentication
def auth_login(request):
print ("#==> auth_login ")
if request.method == "POST":
username = request.POST['username']
password = request.POST['password']
#call csui_helper
access_token = get_access_token(username, password)
if access_token is not None:
ver_user = verify_user(access_token)
kode_identitas = ver_user['identity_number']
role = ver_user['role']
# set session
request.session['user_login'] = username
request.session['access_token'] = access_token
request.session['kode_identitas'] = kode_identitas
request.session['role'] = role
messages.success(request, "Anda berhasil login")
else:
messages.error(request, "Username atau password salah")
return HttpResponseRedirect(reverse('lab-9:index'))
def auth_logout(request):
print ("#==> auth logout")
request.session.flush() # menghapus semua session
messages.info(request, "Anda berhasil logout. Semua session Anda sudah dihapus")
return HttpResponseRedirect(reverse('lab-9:index'))
{% extends "lab_9/layout/base.html" %}
{% block content %}
<div class="row">
<div class="col-md-6 col-md-offset-3">
<div class="rata-tengah">
<div class="judul">
<h1> Login menggunakan COOKIES </h1>
<p class="text-danger"> Jangan menggunakan <b> akun SSO asli </b> </p>
<p class="text-danger"> karena Username dan password akan disimpan di dalam cookie </p>
</div>
<form action="{% url 'lab-9:cookie_auth_login' %}" method="POST">
{% csrf_token %}
<p>
<label for="username"> Your username* </label>
<input type="text" id="username" name="username" required>
</p>
<p>
<label for="password"> Your password* </label>
<input type="password" id="password" name="password" required>
</p>
<input type="submit" class="btn btn-primary">
</form>
</div>
</div>
</div>
{% endblock %}
{% extends "lab_9/layout/base.html" %}
{% block content %}
<br>
<div class="panel panel-default">
<div class="panel-heading">
<h2> [Cookie] Profile </h2>
</div>
<div class="panel-body">
<p> Username : {{ request.COOKIES.user_login }} </p>
</div>
<div class="panel-footer">
<a href="{% url 'lab-9:cookie_clear' %}" class="btn btn-danger"> Reset Cookies (Logout) </a>
</div>
</div>
{% endblock %}
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.contrib import messages
#catatan: tidak bisa menampilkan messages jika bukan menggunakan method 'render'
from .api_enterkomputer import get_drones
response = {}
# NOTE : untuk membantu dalam memahami tujuan dari suatu fungsi (def)
# Silahkan jelaskan menggunakan bahasa kalian masing-masing, di bagian atas
# sebelum fungsi tersebut.
# ======================================================================== #
# User Func
# Apa yang dilakukan fungsi INI? #silahkan ganti ini dengan penjelasan kalian
def index(request):
print ("#==> masuk index")
if 'user_login' in request.session:
return HttpResponseRedirect(reverse('lab-9:profile'))
else:
html = 'lab_9/session/login.html'
return render(request, html, response)
def set_data_for_session(res, request):
response['author'] = request.session['user_login']
response['access_token'] = request.session['access_token']
response['kode_identitas'] = request.session['kode_identitas']
response['role'] = request.session['role']
response['drones'] = get_drones().json()
# print ("#drones = ", get_drones().json(), " - response = ", response['drones'])
## handling agar tidak error saat pertama kali login (session kosong)
if 'drones' in request.session.keys():
response['fav_drones'] = request.session['drones']
# jika tidak ditambahkan else, cache akan tetap menyimpan data
# sebelumnya yang ada pada response, sehingga data tidak up-to-date
else:
response['fav_drones'] = []
def profile(request):
print ("#==> profile")
## sol : bagaimana cara mencegah error, jika url profile langsung diakses
if 'user_login' not in request.session.keys():
return HttpResponseRedirect(reverse('lab-9:index'))
## end of sol
set_data_for_session(response, request)
html = 'lab_9/session/profile.html'
return render(request, html, response)
# ======================================================================== #
### Drones
def add_session_drones(request, id):
ssn_key = request.session.keys()
if not 'drones' in ssn_key:
print ("# init drones ")
request.session['drones'] = [id]
else:
drones = request.session['drones']
print ("# existing drones => ", drones)
if id not in drones:
print ('# add new item, then save to session')
drones.append(id)
request.session['drones'] = drones
messages.success(request, "Berhasil tambah drone favorite")
return HttpResponseRedirect(reverse('lab-9:profile'))
def del_session_drones(request, id):
print ("# DEL drones")
drones = request.session['drones']
print ("before = ", drones)
drones.remove(id) #untuk remove id tertentu dari list
request.session['drones'] = drones
print ("after = ", drones)
messages.error(request, "Berhasil hapus dari favorite")
return HttpResponseRedirect(reverse('lab-9:profile'))
def clear_session_drones(request):
print ("# CLEAR session drones")
print ("before 1 = ", request.session['drones'])
del request.session['drones']
messages.error(request, "Berhasil reset favorite drones")
return HttpResponseRedirect(reverse('lab-9:profile'))
# ======================================================================== #
# COOKIES
# Apa yang dilakukan fungsi INI? #silahkan ganti ini dengan penjelasan kalian
def cookie_login(request):
print ("#==> masuk login")
if is_login(request):
return HttpResponseRedirect(reverse('lab-9:cookie_profile'))
else:
html = 'lab_9/cookie/login.html'
return render(request, html, response)
def cookie_auth_login(request):
print ("# Auth login")
if request.method == "POST":
user_login = request.POST['username']
user_password = request.POST['password']
if my_cookie_auth(user_login, user_password):
print ("#SET cookies")
res = HttpResponseRedirect(reverse('lab-9:cookie_login'))
res.set_cookie('user_login', user_login)
res.set_cookie('user_password', user_password)
return res
else:
msg = "Username atau Password Salah"
messages.error(request, msg)
return HttpResponseRedirect(reverse('lab-9:cookie_login'))
else:
return HttpResponseRedirect(reverse('lab-9:cookie_login'))
def cookie_profile(request):
print ("# cookie profile ")
# method ini untuk mencegah error ketika akses URL secara langsung
if not is_login(request):
print ("belum login")
return HttpResponseRedirect(reverse('lab-9:cookie_login'))
else:
# print ("cookies => ", request.COOKIES)
in_uname = request.COOKIES['user_login']
in_pwd= request.COOKIES['user_password']
# jika cookie diset secara manual (usaha hacking), distop dengan cara berikut
# agar bisa masuk kembali, maka hapus secara manual cookies yang sudah diset
if my_cookie_auth(in_uname, in_pwd):
html = "lab_9/cookie/profile.html"
res = render(request, html, response)
return res
else:
print ("#login dulu")
msg = "Kamu tidak punya akses :P "
messages.error(request, msg)
html = "lab_9/cookie/login.html"
return render(request, html, response)
def cookie_clear(request):
res = HttpResponseRedirect('/lab-9/cookie/login')
res.delete_cookie('lang')
res.delete_cookie('user_login')
msg = "Anda berhasil logout. Cookies direset"
messages.info(request, msg)
return res
# Apa yang dilakukan fungsi ini?
def my_cookie_auth(in_uname, in_pwd):
my_uname = "utest" #SILAHKAN ganti dengan USERNAME yang kalian inginkan
my_pwd = "ptest" #SILAHKAN ganti dengan PASSWORD yang kalian inginkan
return in_uname == my_uname and in_pwd == my_pwd
#Apa yang dilakukan fungsi ini?
def is_login(request):
return 'user_login' in request.COOKIES and 'user_password' in request.COOKIES
{% extends "lab_9/layout/base.html" %}
{% block content %}
<div class="row">
<div class="col-md-6 col-md-offset-3">
<div class="rata-tengah">
<div class="judul">
<h1> Halaman Login </h1>
<p class="text-info"> Gunakan <b> akun SSO </b> untuk login </p>
</div>
<form action="{% url 'lab-9:auth_login' %}" method="POST">
{% csrf_token %}
<p>
<label for="username"> Your username </label>
<input type="text" id="username" name="username" required>
</p>
<p>
<label for="password"> Your password </label>
<input type="password" id="password" name="password" required>
</p>
<input type="submit" class="btn btn-primary">
</form>
</div>
</div>
</div>
{% endblock %}
{% extends "lab_9/layout/base.html" %}
{% block content %}
<!-- Content Here -->
<div class="pojok-kanan">
</div>
<br>
<div class="panel panel-default">
<div class="panel-heading">
<h2> [Session] Profile </h2>
</div>
<div class="panel-body">
<p> Username : {{ author }} </p>
<p> NPM : {{kode_identitas}} </p>
<p> Role : {{ role }} </p>
</div>
<div class="panel-footer">
<a href="{% url 'lab-9:auth_logout' %}" class="btn btn-danger pull-right" onclick="return confirm('Keluar?')">
Logout </a>
<a href="{% url 'lab-9:cookie_login' %}" class="btn btn-info"> Masuk Halaman Cookies </a>
</div>
</div>
<div>
<!-- Nav tabs -->
<ul class="nav nav-tabs nav-justified" role="tablist">
<li role="presentation" class="active">
<a href="#drones" aria-controls="home" role="tab" data-toggle="tab"> Drones </a>
</li>
<li role="presentation">
<a href="#soundcard" aria-controls="settings" role="tab" data-toggle="tab"> Soundcard </a>
</li>
<li role="presentation">
<a href="#" aria-controls="settings" role="tab" data-toggle="tab"> Optical </a>
</li>
</ul>
<!-- Tab panes -->
<div class="tab-content">
<div role="tabpanel" class="tab-pane fade in active" id="drones">
{% include 'lab_9/tables/drones.html' %}
</div>
<div role="tabpanel" class="tab-pane fade" id="soundcard">
<!-- Apply the same here -->
</div>
<div role="tabpanel" class="tab-pane fade" id="optical">
<!-- Apply the same here -->
</div>
</div>
</div>
{% endblock %}
<div class="panel panel-info">
<div class="panel-heading">
<h2> Daftar Drones : {{ drones | length}} </h2>
<a href="{% url 'lab-9:clear_session_drones' %}" class="btn btn-danger" onclick="return confirm('Reset data?')">
Reset Favorite Drones
</a>
</div>
<div class="panel-body">
<table class="table">
<thead>
<th> No</th>
<th> Nama</th>
<th> Harga</th>
<th> Jumlah</th>
<th> Aksi </th>
</thead>
<tbody>
{% for drone in drones %}
<tr>
<td> {{ forloop.counter }}</td>
<td> {{ drone.name }}</td>
<td> {{ drone.price }}</td>
<td> {{ drone.quantity }}</td>
<td>
{% if not drone.id in fav_drones %}
<a href="{% url 'lab-9:add_session_drones' drone.id %}" class="btn btn-primary"> Favoritkan </a>
{% else %}
<a href="{%url 'lab-9:del_session_drones' drone.id %}" class="btn btn-primary"> Hapus dari favorit </a>
{% endif %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
from django.conf.urls import urls
from .views import index,profile,
\add_session_drones,del_ssession_drones,clear_session_drones,
\cookie_login,cookie_profile,cookie_clear
#sol to challenge
from .views import add_session_item, del_session_item, clear_session_item
# /sol
from .custom_auth import auth_login, auth_logout
urlpatterns = [
url(r'^$', index, name='index'),
url(r'^profile/$', profile, name='profile'),
#custom auth
url(r'^custom_auth/login/$', auth_login, name='auth_login'),
url(r'^custom_auth/logout/$', auth_logout, name='auth_logout'),
#add/delete drones
url(r'^add_session_drones/(?P<id>\d+)/$', add_session_drones, name='add_session_drones'),
url(r'^del_session_drones/(?P<id>\d+)/$', del_session_drones, name=''),
url(r'^clear_session_drones/$',clear_session_drones, name='clear_session_drones'),
#cookie
url(r'^cookie/login/$', cookie_login, name='cookie_login'),
url(r'^cookie/auth_login/$', cookie_auth_login, name='cookie_auth_login'),
url(r'^cookie/profile/$', cookie_profile, name='cookie_profile'),
url(r'^cookie/clear/$', cookie_clear, name='cookie_clear'), #sekaligus logout dari cookie
#general function : solution to challenge
url(r'^add_session_item/(?P<key>\w+)/(?P<id>\d+)/$', add_session_item, name='add_session_item'),
url(r'^del_session_item/(?P<key>\w+)/(?P<id>\d+)/$', del_session_item, name='del_session_item'),
url(r'^clear_session_item/(?P<key>\w+)/$', clear_session_item, name='clear_session_item'),
]
\ No newline at end of file
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.contrib import messages
#catatan: tidak bisa menampilkan messages jika bukan menggunakan method 'render'
from .api_enterkomputer import get_drones
response = {}
# NOTE : untuk membantu dalam memahami tujuan dari suatu fungsi (def)
# Silahkan jelaskan menggunakan bahasa kalian masing-masing, di bagian atas
# sebelum fungsi tersebut.
# ======================================================================== #
# User Func
# Apa yang dilakukan fungsi INI? #silahkan ganti ini dengan penjelasan kalian
def index(request):
print ("#==> masuk index")
if 'user_login' in request.session:
return HttpResponseRedirect(reverse('lab-9:profile'))
else:
html = 'lab_9/session/login.html'
return render(request, html, response)
def set_data_for_session(res, request):
response['author'] = request.session['user_login']
response['access_token'] = request.session['access_token']
response['kode_identitas'] = request.session['kode_identitas']
response['role'] = request.session['role']
response['drones'] = get_drones().json()
# print ("#drones = ", get_drones().json(), " - response = ", response['drones'])
## handling agar tidak error saat pertama kali login (session kosong)
if 'drones' in request.session.keys():
response['fav_drones'] = request.session['drones']
# jika tidak ditambahkan else, cache akan tetap menyimpan data
# sebelumnya yang ada pada response, sehingga data tidak up-to-date
else:
response['fav_drones'] = []
def profile(request):
print ("#==> profile")
## sol : bagaimana cara mencegah error, jika url profile langsung diakses
if 'user_login' not in request.session.keys():
return HttpResponseRedirect(reverse('lab-9:index'))
## end of sol
set_data_for_session(response, request)
html = 'lab_9/session/profile.html'
return render(request, html, response)
# ======================================================================== #
### Drones
def add_session_drones(request, id):
ssn_key = request.session.keys()
if not 'drones' in ssn_key:
print ("# init drones ")
request.session['drones'] = [id]
else:
drones = request.session['drones']
print ("# existing drones => ", drones)
if id not in drones:
print ('# add new item, then save to session')
drones.append(id)
request.session['drones'] = drones
messages.success(request, "Berhasil tambah drone favorite")
return HttpResponseRedirect(reverse('lab-9:profile'))
def del_session_drones(request, id):
print ("# DEL drones")
drones = request.session['drones']
print ("before = ", drones)
drones.remove(id) #untuk remove id tertentu dari list
request.session['drones'] = drones
print ("after = ", drones)
messages.error(request, "Berhasil hapus dari favorite")
return HttpResponseRedirect(reverse('lab-9:profile'))
def clear_session_drones(request):
print ("# CLEAR session drones")
print ("before 1 = ", request.session['drones'])
del request.session['drones']
messages.error(request, "Berhasil reset favorite drones")
return HttpResponseRedirect(reverse('lab-9:profile'))
# ======================================================================== #
# COOKIES
# Apa yang dilakukan fungsi INI? #silahkan ganti ini dengan penjelasan kalian
def cookie_login(request):
print ("#==> masuk login")
if is_login(request):
return HttpResponseRedirect(reverse('lab-9:cookie_profile'))
else:
html = 'lab_9/cookie/login.html'
return render(request, html, response)
def cookie_auth_login(request):
print ("# Auth login")
if request.method == "POST":
user_login = request.POST['username']
user_password = request.POST['password']
if my_cookie_auth(user_login, user_password):
print ("#SET cookies")
res = HttpResponseRedirect(reverse('lab-9:cookie_login'))
res.set_cookie('user_login', user_login)
res.set_cookie('user_password', user_password)
return res
else:
msg = "Username atau Password Salah"
messages.error(request, msg)
return HttpResponseRedirect(reverse('lab-9:cookie_login'))
else:
return HttpResponseRedirect(reverse('lab-9:cookie_login'))
def cookie_profile(request):
print ("# cookie profile ")
# method ini untuk mencegah error ketika akses URL secara langsung
if not is_login(request):
print ("belum login")
return HttpResponseRedirect(reverse('lab-9:cookie_login'))
else:
# print ("cookies => ", request.COOKIES)
in_uname = request.COOKIES['user_login']
in_pwd= request.COOKIES['user_password']
# jika cookie diset secara manual (usaha hacking), distop dengan cara berikut
# agar bisa masuk kembali, maka hapus secara manual cookies yang sudah diset
if my_cookie_auth(in_uname, in_pwd):
html = "lab_9/cookie/profile.html"
res = render(request, html, response)
return res
else:
print ("#login dulu")
msg = "Kamu tidak punya akses :P "
messages.error(request, msg)
html = "lab_9/cookie/login.html"
return render(request, html, response)
def cookie_clear(request):
res = HttpResponseRedirect('/lab-9/cookie/login')
res.delete_cookie('lang')
res.delete_cookie('user_login')
msg = "Anda berhasil logout. Cookies direset"
messages.info(request, msg)
return res
# Apa yang dilakukan fungsi ini?
def my_cookie_auth(in_uname, in_pwd):
my_uname = "utest" #SILAHKAN ganti dengan USERNAME yang kalian inginkan
my_pwd = "ptest" #SILAHKAN ganti dengan PASSWORD yang kalian inginkan
return in_uname == my_uname and in_pwd == my_pwd
#Apa yang dilakukan fungsi ini?
def is_login(request):
return 'user_login' in request.COOKIES and 'user_password' in request.COOKIES
### General Function
def add_session_item(request, key, id):
print ("#ADD session item")
ssn_key = request.session.keys()
if not key in ssn_key:
request.session[key] = [id]
else:
items = request.session[key]
if id not in items:
items.append(id)
request.session[key] = items
msg = "Berhasil tambah " + key +" favorite"
messages.success(request, msg)
return HttpResponseRedirect(reverse('lab-9:profile'))
def del_session_item(request, key, id):
print ("# DEL session item")
items = request.session[key]
print ("before = ", items)
items.remove(id)
request.session[key] = items
print ("after = ", items)
msg = "Berhasil hapus item " + key + " dari favorite"
messages.error(request, msg)
return HttpResponseRedirect(reverse('lab-9:profile'))
def clear_session_item(request, key):
del request.session[key]
msg = "Berhasil hapus session : favorite " + key
messages.error(request, msg)
return HttpResponseRedirect(reverse('lab-9:index'))
# Create your views here.
# ======================================================================== #
......@@ -46,6 +46,7 @@ INSTALLED_APPS = [
'lab_6',
'lab_7',
'lab_8',
'lab_9',
]
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
......
......@@ -24,6 +24,7 @@ import lab_5.urls as lab_5
import lab_6.urls as lab_6
import lab_7.urls as lab_7
import lab_8.urls as lab_8
import lab_9.urls as lab_9
from lab_1.views import index as index_lab1
from django.views.generic.base import RedirectView
......@@ -41,4 +42,5 @@ urlpatterns = [
url(r'^lab-6/', include(lab_6, namespace='lab-6')),
url(r'^lab-7/', include(lab_7, namespace='lab-7')),
url(r'^lab-8/', include(lab_8, namespace='lab-8')),
url(r'^lab-9/', include(lab_9, namespace='lab-9')),
]
Markdown is supported
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