Commit 11e5ef3f authored by Tarsvini's avatar Tarsvini

commit 1 lab_10

parent 639657aa
Pipeline #14906109 passed with stages
in 4 minutes and 20 seconds
No preview for this file type
from django.contrib import admin
# Register your models here.
from django.apps import AppConfig
class Lab10Config(AppConfig):
name = 'lab_10'
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'))
# -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-12-09 04:18
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='MovieKu',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('kode_movie', models.CharField(max_length=50, verbose_name='Kode Movie')),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
],
),
migrations.CreateModel(
name='Pengguna',
fields=[
('kode_identitas', models.CharField(max_length=20, primary_key=True, serialize=False, verbose_name='Kode Identitas')),
('nama', models.CharField(max_length=200, verbose_name='Nama')),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
],
),
migrations.AddField(
model_name='movieku',
name='pengguna',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='lab_10.Pengguna'),
),
]
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
# Create your models here.
class Pengguna(models.Model):
kode_identitas = models.CharField('Kode Identitas', max_length=20, primary_key=True, )
nama = models.CharField('Nama', max_length=200)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class MovieKu(models.Model):
pengguna = models.ForeignKey(Pengguna)
kode_movie = models.CharField("Kode Movie", max_length=50)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
import requests
API_KEY = "" #TODO Implement, fill your OMDB API Key Here
def search_movie(judul, tahun):
print ("METHOD SEARCH MOVIE")
get_tahun = ""
if not tahun == "-":
get_tahun = "&y="+tahun
url = "http://www.omdbapi.com/?s=" + judul + get_tahun + "&apikey=" + API_KEY ;
req = requests.get(url)
resp = req.json()
data_exist = False
stResponse = resp['Response']
print ("RESPONSE => ", stResponse)
if stResponse == "True":
count_results = resp['totalResults']
#cukup ambil 30 data saja
cp = (int(count_results) / 10)
if cp > 3: pages = 3
elif cp > 0 and cp <= 3: pages = cp
else: pages = 1
data_exist = True
past_url = url
all_data = []
if data_exist:
for page in range(pages):
page += 1
get_page = "&page="+str(page)
new_url = past_url + get_page;
new_req = requests.get(new_url).json()
get_datas = new_req['Search']
for data in get_datas:
all_data.append(data)
return all_data
def get_detail_movie(id):
url = "http://www.omdbapi.com/?i="+id+"&apikey="+API_KEY;
req = requests.get(url)
rj = req.json() # dict
my_list = create_json_from_dict(rj)
return my_list
def create_json_from_dict(your_dict):
your_data = {}
for key in your_dict:
cvalue = (your_dict.get(key))
nk = str(key).lower()
if type(cvalue) == list:
nv = cvalue
else:
nv = cvalue.encode('ascii','ignore')
your_data[nk] = nv
return your_data
{% extends "lab_10/layout/base.html" %}
{% block content %}
<!-- Content Here -->
<section id="data-dashboard">
<div class="panel panel-default">
<div class="panel-heading">
<h2> Dashboard </h2>
</div>
<div class="panel-body">
<p> Username : {{ author }} </p>
<p> NPM : {{kode_identitas}} </p>
<p> Role : {{ role }} </p>
<p>
<a href="{% url 'lab-10:movie_list' %}" class="btn btn-primary"> Daftar Movie </a> |
<a href="{% url 'lab-10:list_watch_later' %}" class="btn btn-warning"> Daftar Watch Later </a>
</p>
</div>
<div class="panel-footer">
<a href="{% url 'lab-10:auth_logout' %}" class="btn btn-danger" onclick="return confirm('Keluar?')">
Logout </a>
</div>
</div>
</section>
<hr>
{% endblock %}
{% extends "lab_10/layout/base.html" %}
{% block content %}
<div class="row">
<h1> Catatan : Buatlah halaman detail movie sesuai selera dan kreatifitas kalian </h1>
<br>
<h2> Raw Data (json) </h2>
<p> {{ movie }} </p>
<hr>
<h2> Contoh cara mengambil judul: </h2>
<h1 style="color:red"> {{ movie.title}} </h1>
<br>
<div class="box">
{% if added %}
<button class="btn btn-success"> Added to Watch Later </button>
{% else %}
<a href="{% url 'lab-10:add_watch_later' id %}" class="btn btn-warning"> Add to Watch Later </a>
{% endif%}
</div>
</div>
{% endblock %}
{% load staticfiles %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="description" content="LAB 9">
<meta name="author" content="{{author}}">
<!-- bootstrap csss -->
<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
<style>
.rata-tengah {
text-align: center;
margin : 20px;
}
.judul {
text-transform:uppercase;
margin-bottom: 50px;
margin-top: 50px;
}
</style>
<title>
{% block title %} Lab 10 By {{author}} {% endblock %}
</title>
</head>
<body>
<header>
<h1 style="text-align:center">
<small><em> Hello! </em></small>
</h1>
<!-- Your Header Here -->
</header>
<content>
<div class="container">
{% for message in messages %}
<div class="alert {{ message.tags }} alert-dismissible" role="alert" id="django-messages">
<button type="button" class="close" data-dismiss="alert" aria-label="Close" style="margin-right: 15px;">
<span aria-hidden="true">&times;</span>
</button>
{{ message }}
</div>
{% endfor %}
{% block content %}
<!-- Your Content Here -->
{% endblock %}
</div>
</content>
<footer>
<hr>
{% block footer %}
<h1 style="text-align:center">
<small><em> Made by Tarsvini Ravinther </em></small>
</h1>
<!-- Your Footer Here -->
{% endblock %}
</footer>
<!-- Jquery n Bootstrap Script -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="application/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>
</html>
{% extends "lab_10/layout/base.html" %}
{% block content %}
<div class="row">
<div class="col-md-6 col-md-offset-3">
<div class="rata-tengah">
<div class="judul" style="color: white">
<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" style="color: white"> Username :</label>
<input type="text" id="username" name="username" required>
</p>
<p>
<label for="password" style="color: white"> Password :</label>
<input type="password" id="password" name="password" required>
</p>
<input id="login" type="submit" class="btn btn-primary" value="Login">
</form>
</div>
</div>
</div>
{% endblock %}
{% extends "lab_10/layout/base.html" %}
{% block content %}
<!-- User Login Here -->
{% if user_login %}
<a href="" class="btn btn-primary btn-lg"> Logout </a>
{% else %}
<p>
<a href="{% url 'lab-10:list_watch_later' %}" class="btn btn-primary btn-lg "> Daftar <em>Watch Later </em> </a>
</p>
{% endif %}
<br>
<!-- List Movie -->
<div class="panel panel-info">
<div class="panel-heading">
<h2> List Movie </h2>
</div>
<div class="panel-body">
<div style="margin:20px; padding:20px; background-color:lightsteelblue; border-radius:3px;">
<form method="GET" action="{% url 'lab-10:movie_list' %}" class="form-inline">
<label> Nama </label> <input type="text" class="form-control" name="judul" placeholder="Judul"
value="{{judul}}">
<label> Tahun </label> <input type="text" class="form-control" name="tahun" placeholder="Tahun "
value="{{tahun}}">
<input type="submit" class="btn btn-primary pull-right">
</form>
</div>
<hr>
<div class="table table-responsive">
<table class="table table-hover" id="myTable" style="width: none;">
<thead>
<th> Judul</th>
<th> Tahun</th>
<th> Poster</th>
<th> Detail</th>
</thead>
</table>
</div>
</div>
</div>
<!-- Jquery script -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(e) {
$('#myTable').DataTable( {
"ajax": {
"dataType" : 'json',
"contentType": "application/json; charset=utf-8",
"url": {% autoescape off %} {{ jsonUrlDT }} {% endautoescape%} ,
"dataSrc":"dataku",
},
"columns" : [
{"data" : "Title"},
{"data" : "Year"},
{
"data" : "Poster",
"fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
$(nTd).html("<img src='"+ oData.Poster +"' style='height:50%' class='img-responsive img-thumbnail'/>");
}
},
{
"data" : null,
"fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
$(nTd).html("<a href='/lab-10/movie/detail/"+ oData.imdbID +"' class='btn btn-primary'> Detail </a>");
}
}
],
} );
});
</script>
{% endblock %}
{% extends "lab_10/layout/base.html" %}
{% block content %}
<div class="row">
{% for movie in watch_later_movies %}
<p> {{ movie }} </p>
{% endfor %}
</div>
{% endblock %}
from django.test import TestCase
# Create your tests here.
from django.conf.urls import url
from .views import *
from .custom_auth import auth_login, auth_logout
urlpatterns = [
# custom auth
url(r'^custom_auth/login/$', auth_login, name='auth_login'),
url(r'^custom_auth/logout/$', auth_logout, name='auth_logout'),
# index dan dashboard
url(r'^$', index, name='index'),
url(r'^dashboard/$', dashboard, name='dashboard'),
#movie
url(r'^movie/list/$', movie_list, name='movie_list'),
url(r'^movie/detail/(?P<id>.*)/$', movie_detail, name='movie_detail'),
# Session dan Model (Watch Later)
url(r'^movie/watch_later/add/(?P<id>.*)/$', add_watch_later, name='add_watch_later'),
url(r'^movie/watch_later/$', list_watch_later, name='list_watch_later'),
#API
url(r'^api/movie/(?P<judul>.*)/(?P<tahun>.*)/$', api_search_movie, name='api_search_movie'),
]
from .models import Pengguna, MovieKu
from .omdb_api import get_detail_movie
def check_movie_in_database(request, kode_movie):
is_exist = False
kode_identitas = get_data_user(request, 'kode_identitas')
pengguna = Pengguna.objects.get(kode_identitas=kode_identitas)
count_movie = MovieKu.objects.filter(pengguna=pengguna, kode_movie=kode_movie).count()
if count_movie > 0 :
is_exist = True
return is_exist
def check_movie_in_session(request, kode_movie):
is_exist = False
ssn_key = request.session.keys()
if 'movies' in ssn_key:
movies = request.session['movies']
if kode_movie in movies:
is_exist = True
return is_exist
def add_item_to_database(request, id):
kode_identitas = get_data_user(request, 'kode_identitas')
pengguna = Pengguna.objects.get(kode_identitas=kode_identitas)
movieku = MovieKu()
movieku.kode_movie = id
movieku.pengguna = pengguna
movieku.save()
def add_item_to_session(request, id):
ssn_key = request.session.keys()
if not 'movies' in ssn_key:
request.session['movies'] = [id]
else:
movies = request.session['movies']
# check apakah di session sudah ada key yang sama
if id not in movies:
movies.append(id)
request.session['movies'] = movies
def get_data_user(request, tipe):
data = None
if tipe == "user_login" and 'user_login' in request.session:
data = request.session['user_login']
elif tipe == "kode_identitas" and 'kode_identitas' in request.session:
data = request.session['kode_identitas']
return data
def create_new_user(request):
nama = get_data_user(request, 'user_login')
kode_identitas = get_data_user(request, 'kode_identitas')
pengguna = Pengguna()
pengguna.kode_identitas = kode_identitas
pengguna.nama = nama
pengguna.save()
return pengguna
def get_parameter_request(request):
if request.GET.get("judul"):
judul = request.GET.get("judul")
else:
judul = "-"
if request.GET.get("tahun"):
tahun = request.GET.get("tahun")
else:
tahun = "-"
return judul, tahun
# after login, save movies from session
def save_movies_to_database(pengguna, list_movie_id):
#looping get id, cek apakah exist berdasarkan user, jika tidak ada, maka tambah
for movie_id in list_movie_id:
if not (MovieKu.objects.filter(pengguna = pengguna, kode_movie = movie_id).count()) > 0:
new_movie = MovieKu()
new_movie.pengguna = pengguna
new_movie.kode_movie = movie_id
new_movie.save()
#return movies user from db
def get_my_movies_from_database(request):
resp = []
kode_identitas = get_data_user(request, 'kode_identitas')
pengguna = Pengguna.objects.get(kode_identitas=kode_identitas)
items = MovieKu.objects.filter(pengguna=pengguna)
for item in items:
resp.append(item.kode_movie)
return resp
#get my movies from session
def get_my_movies_from_session(request):
resp = []
ssn_key = request.session.keys()
if 'movies' in ssn_key:
resp = request.session['movies']
return resp
#get detail list movie from api
def get_list_movie_from_api(my_list):
print ("GET LIST DATA")
list_movie = []
for movie in my_list:
list_movie.append(get_detail_movie(movie))
return list_movie
# Create your views here.
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json
from django.contrib import messages
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render
from django.urls import reverse
from .omdb_api import get_detail_movie, search_movie
from .utils import *
response = {}
# Create your views here.
### USER
def index(request):
# print ("#==> masuk index")
if 'user_login' in request.session:
return HttpResponseRedirect(reverse('lab-10:dashboard'))
else:
response['author'] = get_data_user(request, 'user_login')
html = 'lab_10/login.html'
return render(request, html, response)
def dashboard(request):
print ("#==> dashboard")
if not 'user_login' in request.session.keys():
return HttpResponseRedirect(reverse('lab-10:index'))
else:
set_data_for_session(request)
kode_identitas = get_data_user(request, 'kode_identitas')
try:
pengguna = Pengguna.objects.get(kode_identitas = kode_identitas)
except Exception as e:
pengguna = create_new_user(request)
movies_id = get_my_movies_from_session(request)
save_movies_to_database(pengguna, movies_id)
html = 'lab_10/dashboard.html'
return render(request, html, response)
### MOVIE : LIST and DETAIL
def movie_list(request):
judul, tahun = get_parameter_request(request)
urlDataTables = "/lab-10/api/movie/" + judul + "/" + tahun
jsonUrlDT = json.dumps(urlDataTables)
response['jsonUrlDT'] = jsonUrlDT
response['judul'] = judul
response['tahun'] = tahun
get_data_session(request)
html = 'lab_10/movie/list.html'
return render(request, html, response)
def movie_detail(request, id):
print ("MOVIE DETAIL = ", id)
response['id'] = id
if get_data_user(request, 'user_login'):
is_added = check_movie_in_database(request, id)
else:
is_added = check_movie_in_session(request, id)
response['added'] = is_added
response['movie'] = get_detail_movie(id)
html = 'lab_10/movie/detail.html'
return render(request, html, response)
### WATCH LATER : ADD and LIST
def add_watch_later(request, id):
print ("ADD WL => ", id)
msg = "Berhasil tambah movie ke Watch Later"
if get_data_user(request, 'user_login'):
print ("TO DB")
is_in_db = check_movie_in_database(request, id)
if not is_in_db:
add_item_to_database(request, id)
else:
msg = "Movie already exist on DATABASE! Hacking detected!"
else:
print ("TO SESSION")
is_in_ssn = check_movie_in_session(request, id)
if not is_in_ssn:
add_item_to_session(request, id)
else:
msg = "Movie already exist on SESSION! Hacking detected!"
messages.success(request, msg)
return HttpResponseRedirect(reverse('lab-10:movie_detail', args=(id,)))
def list_watch_later(request):
# Implement this function by yourself
get_data_session(request)
moviesku = []
if get_data_user(request, 'user_login'):
moviesku = get_my_movies_from_database(request)
else:
moviesku = get_my_movies_from_session(request)
watch_later_movies = get_list_movie_from_api(moviesku)