Fakultas Ilmu Komputer UI

Commit 10fdd0a4 authored by Ryan Karyadiputera's avatar Ryan Karyadiputera
Browse files

test3

parent cfa3ee72
Pipeline #76875 failed with stage
in 1 minute and 31 seconds
venv
env
__pycache__/
*.pyc
.example.env.dev
.example.env.production
.example.env.staging
sip/settings/dev.py
sip/settings/production.py
\ No newline at end of file
# Created by https://www.toptal.com/developers/gitignore/api/python,django,vscode,sonarqube,sonar
# Edit at https://www.toptal.com/developers/gitignore?templates=python,django,vscode,sonarqube,sonar
### Quick Push Script
push.py
push.cmd
### Quick Coverage Check Script
coverage.cmd
### Django ###
*.log
*.pot
*.pyc
__pycache__/
local_settings.py
db.sqlite3
sip/db.sqlite3
db.sqlite3-journal
media
# If your build process includes running collectstatic, then you probably don't need or want to include staticfiles/
# in your Git repository. Update and uncomment the following line accordingly.
# <django-project-name>/staticfiles/
### Django.Python Stack ###
# Byte-compiled / optimized / DLL files
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
pip-wheel-metadata/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
pytestdebug.log
# Translations
*.mo
# Django stuff:
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
doc/_build/
# PyBuilder
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
.python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
pythonenv*
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# profiling data
.prof
### Python ###
# Byte-compiled / optimized / DLL files
# C extensions
# Distribution / packaging
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
# Installer logs
# Unit test / coverage reports
# Translations
# Django stuff:
# Flask stuff:
# Scrapy stuff:
# Sphinx documentation
# PyBuilder
# Jupyter Notebook
# IPython
# pyenv
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
# Celery stuff
# SageMath parsed files
# Environments
# Spyder project settings
# Rope project settings
# mkdocs documentation
# mypy
# Pyre type checker
# pytype static type analyzer
# profiling data
### Sonar ###
#Sonar generated dir
/.sonar/
### SonarQube ###
# SonarQube ignore files.
#
# https://docs.sonarqube.org/display/SCAN/Analyzing+with+SonarQube+Scanner
# Sonar Scanner working directories
.sonar/
.scannerwork/
# http://www.sonarlint.org/commandline/
# SonarLint working directories, configuration files (including credentials)
.sonarlint/
### vscode ###
.vscode/*
.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
*.code-workspace
# End of https://www.toptal.com/developers/gitignore/api/python,django,vscode,sonarqube,sonar
# Data seed
data_seed/lembaga*
data_seed_v2
# Script bash
migrate.local
check-code.sh
serve.sh
credentials
**/media/
# Backend database
db_backend/
stages:
- flake8
- build
- deploy
variables:
PIP_CACHE_DIR: "$CI_PROJECT_DIR/.cache/pip"
image: python:latest
cache:
key: test
paths:
- .cache/pip
- venv/
before_script:
- python3 -V
- pip3 install virtualenv
- virtualenv venv
- source venv/bin/activate
- pip3 install -r requirements.txt
- echo "DJANGO_SECRET_KEY=$DJANGO_SECRET_KEY" > sip/settings/.env
- echo "AWS_ACCESS_KEY_ID=$AWS_ACCESS_KEY_ID" >> sip/settings/.env
- echo "AWS_SECRET_ACCESS_KEY=$AWS_SECRET_ACCESS_KEY" >> sip/settings/.env
- echo "AWS_STORAGE_BUCKET_NAME=$AWS_STORAGE_BUCKET_NAME" >> sip/settings/.env
heroku-deploy:
image: ruby:2.4
stage: deploy
cache: {}
before_script:
- gem install dpl
- wget -qO- https://cli-assets.heroku.com/install-ubuntu.sh | sh
script:
- dpl --provider=heroku --app=$HEROKU_APPNAME --api-key=$HEROKU_APIKEY
- export HEROKU_API_KEY=$HEROKU_APIKEY
only:
- staging
- /^.*URGENT-.*$/
# pull official base image
FROM python:3.9.1-alpine
# set work directory
WORKDIR /usr/src/app
# set environment variables
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1
# install dependencies
RUN pip install --upgrade pip
COPY ./requirements.txt .
RUN pip install -r requirements.txt
# copy project
COPY . .
CMD [ "gunicorn", "sip.wsgi:application", "--bind", "0.0.0.0:8000" ]
\ No newline at end of file
web: DJANGO_SETTINGS_MODULE=sip.settings.staging gunicorn sip.wsgi --log-file -
release: chmod 777 migrate.sh && ./migrate.sh
\ No newline at end of file
# MKPPL-SI Penilaian dan Evaluasi Praktikum
## __Getting Started__
Pastikan **python3** dan **git** sudah terinstall pada laptop/komputer Anda.
```bash
git clone https://gitlab.cs.ui.ac.id/ppl-fasilkom-ui/2020/mkppl-si-penilaian-dan-evaluasi-praktikum.git
cd mkppl-si-penilaian-dan-evaluasi-praktikum
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt
```
## __Setup Local__
### Settings Directory Tree
```
...
+-- sip
| +-- settings
| | +-- static (generated)
| | +-- dev.py (for local)
| | +-- production.py (for production)
| | +-- staging.py (for staging)
|
...
```
### __Environment Variables__
Contoh bentuk file `.env.dev`, ini akan di-*load* pada `settings/dev.py`
***Catatan: file ini dapat berubah menyesuaikan flow, ini hanya contoh.***
```
SECRET_KEY="sm1l3_sw33t_s1st3r_sUrpr1s3_s3rvc1c3"
DB_NAME=db_name
DB_USER=admin
DB_PASS=db_password
DB_HOST=db
DB_PORT=5432
POSTGRES_USER=postgres
POSTGRES_PASSWORD=postgres_password
POSTGRES_DB=postgres_db_name
```
### __How To Run on Local Development__
1. Buat .env di folder sip/settings/ dengan secret key-nya. Tambahin line ini di file-nya:
```bash
DJANGO_SECRET_KEY="s3cr3t_k3y_c4nn0t_h4ck3d_by_l33t_1337"
```
2. Lakukan makemigrations dan migrate
```bash
python manage.py makemigrations --settings=sip.settings.dev
python manage.py migrate --settings=sip.settings.dev
```
3. Jalankan aplikasi menggunakan `manage.py runserver` pada port 8000, spesifikasi settings yang digunakan adalah `dev` atau local.
```bash
python manage.py runserver 8000 --settings=<path>.sip.settings.dev
```
### __Pipelines and Coverage__
[![pipeline status](https://gitlab.cs.ui.ac.id/ppl-fasilkom-ui/2021/BB/departemen-ilmu-kesejahteraan-sosial-ui-sistem-informasi-penilaian-dan-database-praktikum-i-dan-ii/praktikum-backend/badges/staging/pipeline.svg)](https://gitlab.cs.ui.ac.id/ppl-fasilkom-ui/2021/BB/departemen-ilmu-kesejahteraan-sosial-ui-sistem-informasi-penilaian-dan-database-praktikum-i-dan-ii/praktikum-backend/commits/staging/)
[![coverage report](https://gitlab.cs.ui.ac.id/ppl-fasilkom-ui/2021/BB/departemen-ilmu-kesejahteraan-sosial-ui-sistem-informasi-penilaian-dan-database-praktikum-i-dan-ii/praktikum-backend/badges/staging/coverage.svg)](https://gitlab.cs.ui.ac.id/ppl-fasilkom-ui/2021/BB/departemen-ilmu-kesejahteraan-sosial-ui-sistem-informasi-penilaian-dan-database-praktikum-i-dan-ii/praktikum-backend/commits/staging/)
#
# Automated API request
#
# Python version : >= 3
#
# Tutorial : Gw ga make teori-teori segala kayak clean code, maklumin kalo kode-nya jelek. Ini contoh basic cara make toolnya:
#
# 1. Jalanin "python api_tester.py default"
# 2. Login dengan masukin username, password, sama role
# 3. kasih api yang mau dipake habis selesai login, contoh /auth/profile/mahasiwa (Kalo login jadi mahasiswa)
# 4. Masukin data yang perlu make json, kalo ga perlu data pas request ke api-nya, teken enter aja
# 5. Liat response-nya
# 6. Kalo mau keluar dari programnya, teken CTRL-C aja
#
# Note yang penting : urllib.request setau gw cuman bisa nebak method GET sama POST buat http kalo ga dispecify tipe requestnya, kalo make method lain kayak PUT buat upload file nanti gw bikin socket manual buat itu.
#
import sys
import json
import getpass
import urllib.request
invalid_login_flag = True
def banner():
print("")
print(" (`\ .-') /` ('-. _ (`-. ('-. _ (`-. _ (`-. ")
print(" `.( OO ),' ( OO ).-. ( (OO ) _( OO) ( (OO ) ( (OO ) ")
print(" ,----. ,--./ .--. .-----. / . --. /_.` \(,------. _.` \ _.` \ ,--. ")
print(" ' .-./-') | | | ' .--./ | \-. \(__...--'' | .---' (__...--''(__...--'' | |.-') ")
print(" | |_( O- )| | | |, | |('-..-'-' | || / | | | | | / | | | / | | | | OO ) ")
print(" | | .--, \| |.'.| |_) /_) |OO )\| |_.' || |_.' |(| '--. | |_.' | | |_.' | | |`-' | ")
print("(| | '. (_/| | || |`-'| | .-. || .___.' | .--' | .___.' | .___.'(| '---.' ")
print(" | '--' | | ,'. | (_' '--'\ | | | || | | `---. | | | | | | ")
print(" `------' '--' '--' `-----' `--' `--'`--' `------' `--' `--' `------' ")
print("")
def list_command():
print("[*] List command yang tersedia (buat sesi awal doang) : ")
print("\tapi , langsung akses api tanpa login")
print("\tbanner , buat nge-print banner")
print("\tcommands , buat buka tulisan list command ini")
print("\tlogin , biar login dulu baru langsung akses api\n")
def api_req(api_obj):
global invalid_login_flag
while True:
print("[NOTE] Pastiin awalan alamat api-nya pake '/' (ex: /api/v1/mahasiswa)")
api = input("api_tester.py >> Alamat API (kalo mau keluar dari sesi api masukin 'exit', kalo mau liat tokennya masukin 'token') : ")
if api == "exit":
if invalid_login_flag == False:
invalid_login_flag = True
break
if invalid_login_flag:
break
elif api == "token":
try:
print("Token : " + api_obj.get_token() + "\n")
except:
print("[-] Tidak ada token\n")
elif api == "banner":
banner()
else:
api_obj.set_api(api)
print("Berikut bakal nanya data, kalo api-nya gaperlu data teken enter aja\n")
data_json = input("api_tester.py >> Data (dalem bentuk json) : ")
api_obj.set_data(data_json)
api_obj.request()
return
class APITester:
def __init__(self, domain):
self.domain = domain
def set_api(self, api):
self.api = api
def set_data(self, data):
self.data = data
def get_token(self):
return self.token
def login(self):
global invalid_login_flag
tipe_ = int(input("[*] Tipe akun (1 buat SSO, 2 buat django admin) : "))
if tipe_ == 1:
self.api = "/auth/login/sso/"
elif tipe_ == 2:
self.api = "/auth/login/supervisor-lembaga/"
else:
print("[*] Tipe akun invalid")
return
username = input("[*] Username : ")
passwd = input("[*] Password (tidak ke-echo, pastiin passwordnya bener) : ")
role = int(input("[*] Role ( 1 untuk Mahasiswa, 2 untuk Spv Sekolah, 3 untuk Koor Kuliah, 4 untuk Spv Lembaga, 5 untuk Admin) : "))
if role == 1:
self.data = "{\"username\":\""+username.replace("\"", "\\\"")+"\",\"password\":\""+passwd.replace("\"", "\\\"")+"\",\"role\":\"Mahasiswa\"}"
elif role == 2:
self.data = "{\"username\":\""+username.replace("\"", "\\\"")+"\",\"password\":\""+passwd.replace("\"", "\\\"")+"\",\"role\":\"Supervisor Sekolah\"}"
elif role == 3:
self.data = "{\"username\":\""+username.replace("\"", "\\\"")+"\",\"password\":\""+passwd.replace("\"", "\\\"")+"\",\"role\":\"Koordinator Kuliah\"}"
elif role == 4:
self.data = "{\"username\":\""+username.replace("\"", "\\\"")+"\",\"password\":\""+passwd.replace("\"", "\\\"")+"\",\"role\":\"Supervisor Lembaga\"}"
elif role == 5:
self.data = "{\"username\":\""+username.replace("\"", "\\\"")+"\",\"password\":\""+passwd.replace("\"", "\\\"")+"\",\"role\":\"Administrator\"}"
else:
print("[-] Role tidak valid")
print("[-] Mohon coba lagi dari awal")
return False
# Request ke API-nya
header = {
"User-Agent" : "Mozilla/5.0",
"Accept" : "*/*",
"Accept-Encoding" : "text/plain,application/json",
"Content-Type" : "application/json",
"Content-Length" : str(len(self.data)),
}
req = urllib.request.Request(self.domain+self.api, self.data.encode("ascii"), header)
try:
res = urllib.request.urlopen(req)
resData = res.read().decode("ascii")
apiRes = json.loads(resData)
self.token = apiRes["token"]
print("[+] Login berhasil")
print("[+] Token : " + str(self.token)[:15] + "...\n")
invalid_login_flag = False
return True
except urllib.error.HTTPError:
print("[-] Gagal Login")
print("[*] Mohon coba lagi")
return False
def request(self):
print("[*] Mengirim request ke " + self.api)
header = {
"User-Agent" : "Mozilla/5.0",
"Accept" : "*/*",
"Accept-Encoding" : "text/plain,application/json",
"Content-Type" : "application/json",
"Content-Length" : str(len(self.data)),
}
try:
if self.token:
header["Authorization"] = "Bearer "+self.token
except:
print("[*] Tidak ada token")
if self.data == "":
req = urllib.request.Request(self.domain+self.api, headers=header)
else:
req = urllib.request.Request(self.domain+self.api, self.data.encode("ascii"), header)
try:
res = urllib.request.urlopen(req)
resData = res.read().decode("ascii")
apiRes = json.loads(resData)
print("\n+ - Response - +\n\n" + str(apiRes) + "\n\n+ - Response - +\n")
except urllib.error.HTTPError as e:
if "404" in str(e):
print("[-] API tidak ditemukan")
else:
print("[-] Terjadi suatu kesalahan")
print(str(e)+"\n")
if __name__ == "__main__":
if len(sys.argv) < 2:
banner()
print("[Cara make] python api_tester.py (domain)")
print("[Catatan] Kasih 'default' di bagian 'domain' buat konek ke ppl-berkah-backend.herokuapp.com")
else:
try:
if sys.argv[1] == "default":
domain = "https://ppl-berkah-backend.herokuapp.com"
else:
domain = sys.argv[1]
banner()
list_command()
api_obj = APITester(domain)
while True:
cmd = input(sys.argv[0]+" > ")
if cmd == "login":
print("[*] Login terlebih dahulu")
while invalid_login_flag:
result = api_obj.login()
if result:
api_req(api_obj)
print("[*] Sesi login selesai\n")
break
elif cmd == "api":
api_req(api_obj)
elif cmd == "banner":
banner()
elif cmd == "commands":
list_command()
elif cmd == "exit":
sys.exit()
else:
print("[-] Command invalid\n")
except KeyboardInterrupt:
print("\n\n[-] CTRL-C keteken\n")
sys.exit()
\ No newline at end of file
from .models import (
Mahasiswa,
SupervisorSekolah,
SupervisorLembaga,
KoordinatorKuliah,
Administrator,
User,
Periode,
Config
)
from django.contrib import admin
"""Profile model admin class."""
@admin.register(Mahasiswa)
class MahasiswaAdmin(admin.ModelAdmin):
pass
"""Profile model admin class."""
@admin.register(SupervisorSekolah)
class SupervisorSekolahAdmin(admin.ModelAdmin):
pass
"""Profile model admin class."""