Login dengan Google UNTAN (OpenID Connect) yang dihubungkan ke akun aplikasi
- app/google_auth.py: authorization-code flow tanpa dependensi tambahan; klaim id_token diperiksa (iss, aud, exp, nonce, email_verified) dan email wajib domain GOOGLE_DOMAIN (bawaan untan.ac.id + subdomain). Aktif hanya bila GOOGLE_CLIENT_ID & SECRET terisi. - Akun Google ditautkan (pengguna.google_sub) oleh pemilik dari menu Akun, atau otomatis pada login pertama bila email sama dengan email akun / data induk mahasiswa. Tanpa pembuatan akun otomatis; satu Google satu akun; akun nonaktif ditolak. - Putus oleh pemilik mematikan tautan otomatis via email; putus oleh kaprodi (Data Master -> Dosen) mengizinkannya lagi. Login NIP/NPM + password tetap tersedia. - Uji: tests/uji_google.py (tiruan endpoint token Google). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
549fe53a11
commit
b09785fc62
@@ -605,6 +605,9 @@ def _migrasi(conn) -> None:
|
||||
conn.execute("ALTER TABLE pengguna ADD COLUMN aktif INTEGER NOT NULL DEFAULT 1")
|
||||
if "email" not in kol:
|
||||
conn.execute("ALTER TABLE pengguna ADD COLUMN email TEXT NOT NULL DEFAULT ''")
|
||||
# login Google: ID akun Google (klaim 'sub', tetap meski email berubah) yang dihubungkan
|
||||
if "google_sub" not in kol:
|
||||
conn.execute("ALTER TABLE pengguna ADD COLUMN google_sub TEXT NOT NULL DEFAULT ''")
|
||||
|
||||
|
||||
def kode_periode(tahun: str, jenis: str) -> str:
|
||||
@@ -926,6 +929,53 @@ def pengguna_by_id(user_id: int) -> dict | None:
|
||||
return dict(row) if row else None
|
||||
|
||||
|
||||
# ── akun Google terhubung ────────────────────────────────────────────────────
|
||||
|
||||
def pengguna_by_google(sub: str) -> dict | None:
|
||||
if not sub or sub == GOOGLE_DIPUTUS:
|
||||
return None
|
||||
with get_conn() as conn:
|
||||
row = conn.execute("SELECT * FROM pengguna WHERE google_sub=? AND aktif=1", (sub,)).fetchone()
|
||||
return dict(row) if row else None
|
||||
|
||||
|
||||
def pengguna_by_email(email: str) -> dict | None:
|
||||
"""Akun aktif ber-email ini (email akun, atau email data induk mahasiswa → akun NPM).
|
||||
Ambigu (lebih dari satu akun) → None, agar tidak salah menautkan."""
|
||||
email = (email or "").strip().lower()
|
||||
if not email:
|
||||
return None
|
||||
with get_conn() as conn:
|
||||
rows = conn.execute("SELECT * FROM pengguna WHERE lower(email)=? AND aktif=1", (email,)).fetchall()
|
||||
if not rows:
|
||||
rows = conn.execute(
|
||||
"SELECT p.* FROM pengguna p JOIN mhs m ON m.npm = p.username "
|
||||
"WHERE lower(m.email)=? AND p.aktif=1", (email,)).fetchall()
|
||||
return dict(rows[0]) if len(rows) == 1 else None
|
||||
|
||||
|
||||
def hubungkan_google(uid: int, sub: str, email: str) -> None:
|
||||
"""Tautkan akun Google ke akun; email akun diisi bila masih kosong."""
|
||||
with get_conn() as conn:
|
||||
conn.execute("UPDATE pengguna SET google_sub=?, email=CASE WHEN email='' THEN ? ELSE email END "
|
||||
"WHERE id=?", (sub, email, uid))
|
||||
|
||||
|
||||
GOOGLE_DIPUTUS = "-" # diputus pemilik akun: tautan otomatis lewat email dimatikan
|
||||
|
||||
|
||||
def putus_google(uid: int, oleh_pemilik: bool = True) -> None:
|
||||
"""Putus tautan. Oleh pemilik → tidak tertaut otomatis lagi (hanya lewat Hubungkan);
|
||||
oleh kaprodi (mis. salah akun) → tautan otomatis via email kembali diizinkan."""
|
||||
with get_conn() as conn:
|
||||
conn.execute("UPDATE pengguna SET google_sub=? WHERE id=?",
|
||||
(GOOGLE_DIPUTUS if oleh_pemilik else "", uid))
|
||||
|
||||
|
||||
def google_terhubung(p: dict) -> bool:
|
||||
return (p.get("google_sub") or "") not in ("", GOOGLE_DIPUTUS)
|
||||
|
||||
|
||||
def daftar_pengguna(termasuk_mahasiswa: bool = False) -> list[dict]:
|
||||
"""Akun dosen/kaprodi (+ mahasiswa bila diminta) beserta penugasan & jumlah wali."""
|
||||
syarat = "" if termasuk_mahasiswa else "WHERE role<>'mahasiswa'"
|
||||
@@ -1404,7 +1454,8 @@ def daftar_dosen(periode: str | None = None, termasuk_nonaktif: bool = True) ->
|
||||
periode = periode or tahun_aktif()
|
||||
with get_conn() as conn:
|
||||
rows = [dict(r) for r in conn.execute(
|
||||
"SELECT id, username, nama, role, aktif, email FROM pengguna WHERE role<>'mahasiswa'"
|
||||
"SELECT id, username, nama, role, aktif, email, google_sub NOT IN ('', '-') AS google FROM pengguna "
|
||||
"WHERE role<>'mahasiswa'"
|
||||
+ ("" if termasuk_nonaktif else " AND aktif=1") + " ORDER BY aktif DESC, nama")]
|
||||
kls = {r[0]: r[1] for r in conn.execute(
|
||||
"SELECT user_id, COUNT(*) FROM pengajar WHERE periode=? GROUP BY user_id", (periode,))}
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Login dengan Google (OpenID Connect, authorization-code flow) — tanpa dependensi tambahan.
|
||||
|
||||
Google hanya membuktikan identitas; peran & penugasan tetap milik akun aplikasi. Akun Google
|
||||
dihubungkan ke akun aplikasi (kolom pengguna.google_sub) oleh pemiliknya sendiri dari menu
|
||||
Akun, atau otomatis pada login pertama bila emailnya sama dengan email akun yang terdaftar.
|
||||
|
||||
Env: GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET (keduanya wajib; kosong = fitur tersembunyi),
|
||||
GOOGLE_DOMAIN (bawaan "untan.ac.id": email harus domain ini atau subdomainnya),
|
||||
GOOGLE_REDIRECT_URI (opsional; bawaan <base_url>/auth/google/callback).
|
||||
"""
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
URL_OTORISASI = "https://accounts.google.com/o/oauth2/v2/auth"
|
||||
URL_TOKEN = "https://oauth2.googleapis.com/token"
|
||||
PENERBIT = {"https://accounts.google.com", "accounts.google.com"}
|
||||
|
||||
|
||||
class GagalGoogle(Exception):
|
||||
"""Proses login Google gagal; pesan aman ditampilkan ke pengguna."""
|
||||
|
||||
|
||||
def _env(nama: str, bawaan: str = "") -> str:
|
||||
return (os.environ.get(nama) or bawaan).strip()
|
||||
|
||||
|
||||
def aktif() -> bool:
|
||||
return bool(_env("GOOGLE_CLIENT_ID") and _env("GOOGLE_CLIENT_SECRET"))
|
||||
|
||||
|
||||
def domain() -> str:
|
||||
return _env("GOOGLE_DOMAIN", "untan.ac.id").lower()
|
||||
|
||||
|
||||
def domain_sah(email: str) -> bool:
|
||||
"""email@untan.ac.id atau email@<sub>.untan.ac.id (informatika., student., teknik., …)."""
|
||||
d = domain()
|
||||
bagian = (email or "").lower().rsplit("@", 1)
|
||||
return len(bagian) == 2 and (bagian[1] == d or bagian[1].endswith("." + d))
|
||||
|
||||
|
||||
def redirect_uri(base_url: str) -> str:
|
||||
return _env("GOOGLE_REDIRECT_URI") or base_url.rstrip("/") + "/auth/google/callback"
|
||||
|
||||
|
||||
def url_masuk(redirect: str, state: str, nonce: str) -> str:
|
||||
return URL_OTORISASI + "?" + urllib.parse.urlencode({
|
||||
"client_id": _env("GOOGLE_CLIENT_ID"), "redirect_uri": redirect, "response_type": "code",
|
||||
"scope": "openid email profile", "state": state, "nonce": nonce,
|
||||
"prompt": "select_account", "hd": domain(),
|
||||
})
|
||||
|
||||
|
||||
def _payload_jwt(token: str) -> dict:
|
||||
try:
|
||||
bagian = token.split(".")[1]
|
||||
return json.loads(base64.urlsafe_b64decode(bagian + "=" * (-len(bagian) % 4)))
|
||||
except (IndexError, ValueError):
|
||||
raise GagalGoogle("Jawaban Google tidak dapat dibaca.")
|
||||
|
||||
|
||||
def _minta_token(code: str, redirect: str) -> dict:
|
||||
data = urllib.parse.urlencode({
|
||||
"code": code, "client_id": _env("GOOGLE_CLIENT_ID"),
|
||||
"client_secret": _env("GOOGLE_CLIENT_SECRET"),
|
||||
"redirect_uri": redirect, "grant_type": "authorization_code",
|
||||
}).encode()
|
||||
req = urllib.request.Request(URL_TOKEN, data=data, method="POST",
|
||||
headers={"Content-Type": "application/x-www-form-urlencoded"})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=10) as r:
|
||||
return json.loads(r.read())
|
||||
except urllib.error.HTTPError as e:
|
||||
raise GagalGoogle(f"Google menolak permintaan masuk (HTTP {e.code}).")
|
||||
except (urllib.error.URLError, TimeoutError, ValueError):
|
||||
raise GagalGoogle("Tidak dapat menghubungi Google. Coba lagi sebentar lagi.")
|
||||
|
||||
|
||||
def tukar_kode(code: str, redirect: str, nonce: str) -> dict:
|
||||
"""Kode otorisasi → klaim identitas terverifikasi {sub, email, nama}.
|
||||
|
||||
id_token diterima langsung dari endpoint token Google lewat TLS, sehingga cukup
|
||||
memeriksa klaimnya (OpenID Connect Core §3.1.3.7) tanpa verifikasi tanda tangan."""
|
||||
jawab = _minta_token(code, redirect)
|
||||
if "id_token" not in jawab:
|
||||
raise GagalGoogle("Google tidak mengirim identitas.")
|
||||
k = _payload_jwt(jawab["id_token"])
|
||||
if k.get("iss") not in PENERBIT or k.get("aud") != _env("GOOGLE_CLIENT_ID"):
|
||||
raise GagalGoogle("Identitas Google tidak ditujukan untuk aplikasi ini.")
|
||||
if float(k.get("exp") or 0) < time.time() or k.get("nonce") != nonce:
|
||||
raise GagalGoogle("Sesi login Google kedaluwarsa. Ulangi masuk.")
|
||||
email = (k.get("email") or "").strip().lower()
|
||||
if not k.get("sub") or not email or k.get("email_verified") not in (True, "true"):
|
||||
raise GagalGoogle("Email akun Google belum terverifikasi.")
|
||||
if not domain_sah(email):
|
||||
raise GagalGoogle(f"Gunakan akun Google kampus (@{domain()}), bukan akun pribadi.")
|
||||
return {"sub": str(k["sub"]), "email": email, "nama": k.get("name") or ""}
|
||||
+93
-5
@@ -11,6 +11,7 @@ from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, Redirect
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from fastapi.templating import Jinja2Templates
|
||||
|
||||
from . import google_auth
|
||||
from . import auth, cqi, db, hitung, nilai_xlsx
|
||||
from .generator.laporan_cpl_docx import build_laporan_cpl
|
||||
from .generator.portofolio_docx import build_portofolio
|
||||
@@ -46,6 +47,7 @@ def foto_mhs(npm: str) -> str:
|
||||
|
||||
|
||||
templates.env.globals["foto_mhs"] = foto_mhs
|
||||
templates.env.globals["google_aktif"] = google_auth.aktif
|
||||
|
||||
|
||||
def fmt_ambang(x) -> str:
|
||||
@@ -64,7 +66,7 @@ db.kurikulum()
|
||||
|
||||
# ── autentikasi: semua halaman wajib login ───────────────────────────────────
|
||||
|
||||
PUBLIK = {"/login", "/setup", "/favicon.ico"}
|
||||
PUBLIK = {"/login", "/setup", "/favicon.ico", "/auth/google", "/auth/google/callback"}
|
||||
|
||||
# ── peran ────────────────────────────────────────────────────────────────────
|
||||
# Hak akses mengikuti IDENTITAS pengguna (penugasan, perwalian, role akun);
|
||||
@@ -86,7 +88,8 @@ def peran_tersedia(user: dict) -> list[str]:
|
||||
|
||||
# mahasiswa hanya boleh membuka beranda, raport miliknya, akun, dan keluar
|
||||
def _jalur_mahasiswa(path: str, npm: str) -> bool:
|
||||
return (path in ("/", "/keluar", "/akun", "/cari", "/peran", "/kurikulum", "/kurikulum/ekspor.xlsx")
|
||||
return (path in ("/", "/keluar", "/akun", "/akun/google/putus", "/cari", "/peran", "/kurikulum",
|
||||
"/kurikulum/ekspor.xlsx")
|
||||
or path.startswith(f"/raport/{npm}"))
|
||||
|
||||
|
||||
@@ -193,11 +196,11 @@ async def setup_simpan(request: Request):
|
||||
|
||||
|
||||
@app.get("/login", response_class=HTMLResponse)
|
||||
def login_form(request: Request):
|
||||
def login_form(request: Request, pesan: str = ""):
|
||||
if not db.ada_pengguna():
|
||||
return RedirectResponse("/setup", status_code=303)
|
||||
return render(request, "login.html",
|
||||
{"mode": "login", "pesan": "", "tahun": db.tahun_aktif()})
|
||||
{"mode": "login", "pesan": pesan[:300], "tahun": db.tahun_aktif()})
|
||||
|
||||
|
||||
@app.post("/login")
|
||||
@@ -234,7 +237,10 @@ async def ganti_peran(request: Request):
|
||||
|
||||
@app.get("/akun", response_class=HTMLResponse)
|
||||
def akun(request: Request, pesan: str = "", galat: str = ""):
|
||||
return render(request, "akun.html", {"pesan": pesan, "galat": galat})
|
||||
u = db.pengguna_by_id(request.state.user["id"])
|
||||
return render(request, "akun.html", {"pesan": pesan, "galat": galat, "google_aktif": google_auth.aktif(),
|
||||
"google_terhubung": db.google_terhubung(u), "email_akun": u.get("email") or "",
|
||||
"google_domain": google_auth.domain()})
|
||||
|
||||
|
||||
@app.post("/akun")
|
||||
@@ -256,6 +262,88 @@ async def akun_simpan(request: Request):
|
||||
return r
|
||||
|
||||
|
||||
# ═════════════════════════ LOGIN GOOGLE (app/google_auth.py) ═════════════════════════
|
||||
# Satu alur OAuth untuk dua tujuan: "masuk" (halaman login) dan "hubung" (menu Akun, pengguna
|
||||
# sudah login). state & nonce disimpan di cookie singkat HttpOnly dan dicocokkan saat callback.
|
||||
|
||||
_COOKIE_G = "g_oauth"
|
||||
|
||||
|
||||
def _ke_login(pesan: str) -> RedirectResponse:
|
||||
return RedirectResponse("/login?pesan=" + quote_plus(pesan), status_code=303)
|
||||
|
||||
|
||||
@app.get("/auth/google")
|
||||
def google_mulai(request: Request, tujuan: str = "masuk"):
|
||||
if not google_auth.aktif():
|
||||
return _ke_login("Login dengan Google belum diaktifkan.")
|
||||
tujuan = "hubung" if tujuan == "hubung" else "masuk"
|
||||
if tujuan == "hubung" and not db.user_dari_sesi(request.cookies.get("sesi", "")):
|
||||
return _ke_login("Masuk dulu dengan NIP/NPM untuk menghubungkan akun Google.")
|
||||
state, nonce = auth.token_baru(), auth.token_baru()
|
||||
r = RedirectResponse(google_auth.url_masuk(google_auth.redirect_uri(str(request.base_url)), state, nonce),
|
||||
status_code=303)
|
||||
r.set_cookie(_COOKIE_G, f"{state}|{nonce}|{tujuan}", max_age=600, httponly=True, samesite="lax",
|
||||
secure=request.url.scheme == "https")
|
||||
return r
|
||||
|
||||
|
||||
@app.get("/auth/google/callback")
|
||||
def google_kembali(request: Request, code: str = "", state: str = "", error: str = ""):
|
||||
simpan = (request.cookies.get(_COOKIE_G) or "").split("|")
|
||||
tujuan = simpan[2] if len(simpan) == 3 else "masuk"
|
||||
gagal_ke = "/akun?galat=" if tujuan == "hubung" else "/login?pesan="
|
||||
|
||||
def gagal(pesan: str) -> RedirectResponse:
|
||||
r = RedirectResponse(gagal_ke + quote_plus(pesan), status_code=303)
|
||||
r.delete_cookie(_COOKIE_G)
|
||||
return r
|
||||
|
||||
if error:
|
||||
return gagal("Login Google dibatalkan." if error == "access_denied" else f"Google menolak: {error}.")
|
||||
if len(simpan) != 3 or not code or not state or state != simpan[0]:
|
||||
return gagal("Sesi login Google tidak valid atau kedaluwarsa. Ulangi.")
|
||||
try:
|
||||
g = google_auth.tukar_kode(code, google_auth.redirect_uri(str(request.base_url)), simpan[1])
|
||||
except google_auth.GagalGoogle as e:
|
||||
return gagal(str(e))
|
||||
pemilik = db.pengguna_by_google(g["sub"])
|
||||
|
||||
if tujuan == "hubung":
|
||||
u = db.user_dari_sesi(request.cookies.get("sesi", ""))
|
||||
if not u:
|
||||
return gagal("Sesi aplikasi berakhir. Masuk lagi lalu ulangi.")
|
||||
if pemilik and pemilik["id"] != u["id"]:
|
||||
return gagal(f"Akun Google {g['email']} sudah terhubung ke akun lain.")
|
||||
db.hubungkan_google(u["id"], g["sub"], g["email"])
|
||||
r = RedirectResponse("/akun?pesan=" + quote_plus(f"Akun Google {g['email']} terhubung. "
|
||||
"Berikutnya Anda bisa masuk dengan Google."), status_code=303)
|
||||
r.delete_cookie(_COOKIE_G)
|
||||
return r
|
||||
|
||||
p = pemilik
|
||||
if not p:
|
||||
# login pertama: tautkan otomatis bila email Google sama dengan email akun terdaftar
|
||||
p = db.pengguna_by_email(g["email"])
|
||||
if p and p.get("google_sub") and p["google_sub"] != g["sub"]:
|
||||
p = None
|
||||
if p:
|
||||
db.hubungkan_google(p["id"], g["sub"], g["email"])
|
||||
if not p:
|
||||
return gagal(f"Akun Google {g['email']} belum terhubung ke akun aplikasi. Masuk dengan NIP/NPM, "
|
||||
"lalu hubungkan di menu Akun — atau minta kaprodi mendaftarkan email Anda.")
|
||||
r = _masuk(p["id"])
|
||||
r.delete_cookie(_COOKIE_G)
|
||||
return r
|
||||
|
||||
|
||||
@app.post("/akun/google/putus")
|
||||
def google_putus(request: Request):
|
||||
db.putus_google(request.state.user["id"])
|
||||
return RedirectResponse("/akun?pesan=Akun+Google+diputus.+Masuk+kembali+memakai+NIP/NPM+dan+password.",
|
||||
status_code=303)
|
||||
|
||||
|
||||
@app.get("/keluar")
|
||||
def keluar(request: Request):
|
||||
db.hapus_sesi(request.cookies.get("sesi", ""))
|
||||
|
||||
@@ -292,6 +292,9 @@ async def dosen_ubah(request: Request, uid: int):
|
||||
if aksi == "aktif":
|
||||
db.ubah_dosen(uid, aktif=True)
|
||||
return _ke("/master/dosen", f"{p['nama']} diaktifkan kembali.")
|
||||
if aksi == "putus_google":
|
||||
db.putus_google(uid, oleh_pemilik=False)
|
||||
return _ke("/master/dosen", f"Tautan akun Google {p['nama']} diputus.")
|
||||
if aksi == "reset":
|
||||
db.ubah_password(uid, auth.hash_password(p["username"]))
|
||||
return _ke("/master/dosen", f"Password {p['nama']} dikembalikan ke NIP.")
|
||||
|
||||
@@ -28,5 +28,21 @@
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
{% if google_aktif %}
|
||||
<div class="card mt-6" id="akun-google">
|
||||
{{ ui.card_header('Akun Google', sub='Masuk tanpa password memakai akun Google kampus (@' ~ google_domain ~ ' dan subdomainnya). Login NIP/NPM tetap bisa dipakai.', ikon='brand-google') }}
|
||||
<div class="card-body">
|
||||
{% if google_terhubung %}
|
||||
<p class="mb-4"><span class="badge bg-label-success me-2"><i class="icon-base ti tabler-circle-check icon-xs"></i> Terhubung</span>{{ email_akun }}</p>
|
||||
<form method="post" action="/akun/google/putus" onsubmit="return confirm('Putus akun Google? Anda tetap bisa masuk dengan NIP/NPM dan password.')">
|
||||
<button class="btn btn-label-danger" type="submit"><i class="icon-base ti tabler-unlink icon-sm me-1"></i>Putus akun Google</button>
|
||||
</form>
|
||||
{% else %}
|
||||
<p class="mb-4 text-body-secondary">Belum terhubung.{% if email_akun %} Email terdaftar: <b>{{ email_akun }}</b> — masuk dengan Google memakai email ini akan terhubung otomatis.{% endif %}</p>
|
||||
<a class="btn btn-primary" href="/auth/google?tujuan=hubung"><i class="icon-base ti tabler-brand-google icon-sm me-1"></i>Hubungkan akun Google</a>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
{% endif %}
|
||||
</div></div>
|
||||
{% endblock %}
|
||||
|
||||
@@ -52,6 +52,12 @@
|
||||
{{ 'Buat Akun Kaprodi & Masuk' if mode == 'setup' else 'Masuk' }}
|
||||
</button>
|
||||
</form>
|
||||
{% if mode == 'login' and google_aktif() %}
|
||||
<div class="divider my-5"><div class="divider-text">atau</div></div>
|
||||
<a class="btn btn-label-secondary d-flex align-items-center justify-content-center gap-2 w-100" href="/auth/google">
|
||||
<i class="icon-base ti tabler-brand-google icon-md"></i>Masuk dengan Google UNTAN</a>
|
||||
<div class="form-text text-center mt-2">Akun Google kampus yang sudah dihubungkan di menu Akun, atau yang emailnya terdaftar di aplikasi.</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
<div class="text-center mt-4">
|
||||
|
||||
@@ -36,7 +36,7 @@
|
||||
<td>
|
||||
<details>
|
||||
<summary class="fw-medium text-heading" style="cursor:pointer;list-style:none">{{ d.nama }}{% if d.role == 'kaprodi' %} <span class="badge bg-label-primary">Kaprodi</span>{% endif %}
|
||||
<small class="d-block text-body-secondary">{{ d.email or 'ubah nama/email…' }}</small></summary>
|
||||
<small class="d-block text-body-secondary">{{ d.email or 'ubah nama/email…' }}{% if d.google %} <span class="badge bg-label-success" title="Akun Google terhubung — bisa masuk dengan Google"><i class="icon-base ti tabler-brand-google icon-xs"></i> terhubung</span>{% endif %}</small></summary>
|
||||
<form method="post" action="/master/dosen/{{ d.id }}" class="d-flex flex-wrap gap-2 mt-2">
|
||||
<input class="form-control form-control-sm" name="nama" value="{{ d.nama }}" style="max-width:260px" aria-label="Nama">
|
||||
<input class="form-control form-control-sm" name="email" value="{{ d.email }}" placeholder="email" style="max-width:200px" aria-label="Email">
|
||||
@@ -53,6 +53,7 @@
|
||||
<form method="post" action="/master/dosen/{{ d.id }}" class="d-inline">
|
||||
{% if d.aktif %}
|
||||
<button class="btn btn-sm btn-text-secondary" type="submit" name="aksi" value="reset" title="Kembalikan password ke NIP"><i class="icon-base ti tabler-key icon-sm"></i></button>
|
||||
{% if d.google %}<button class="btn btn-sm btn-text-secondary" type="submit" name="aksi" value="putus_google" title="Putus tautan akun Google" onclick="return confirm('Putus tautan akun Google {{ d.nama }}?')"><i class="icon-base ti tabler-unlink icon-sm"></i></button>{% endif %}
|
||||
{% if d.id != user.id %}<button class="btn btn-sm btn-text-warning" type="submit" name="aksi" value="nonaktif" onclick="return confirm('Nonaktifkan {{ d.nama }}? Akun tidak bisa masuk; data lama tetap.')">Nonaktifkan</button>{% endif %}
|
||||
{% else %}
|
||||
<button class="btn btn-sm btn-text-success" type="submit" name="aksi" value="aktif">Aktifkan</button>
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@
|
||||
cd "$(dirname "$0")/.." || exit 1
|
||||
ROOT="$(pwd -W 2>/dev/null || pwd)"
|
||||
gagal=0
|
||||
for u in uji_peran uji_autosave uji_simpan uji_klinik3 uji_cqi uji_impor uji_siklus uji_kurikulum; do
|
||||
for u in uji_peran uji_autosave uji_simpan uji_klinik3 uji_cqi uji_impor uji_siklus uji_kurikulum uji_google; do
|
||||
cp data/app.db tests/uji.db
|
||||
if PYTHONIOENCODING=utf-8 python "tests/$u.py" "$ROOT" > "tests/$u.log" 2>&1; then echo "OK $u"; else echo "GAGAL $u (lihat tests/$u.log)"; gagal=1; fi
|
||||
done
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
"""Uji login Google (salinan DB): tersembunyi tanpa env, hubungkan dari Akun, masuk dengan
|
||||
Google, tautan otomatis via email, domain kampus, state/nonce, satu Google satu akun, putus.
|
||||
Jawaban endpoint token Google ditiru (tanpa jaringan)."""
|
||||
import base64, json, os, sys, time
|
||||
from urllib.parse import parse_qs, urlparse, unquote_plus
|
||||
SP = os.path.dirname(os.path.abspath(__file__))
|
||||
os.environ["DB_PATH"] = os.path.join(SP, "uji.db")
|
||||
sys.path.insert(0, sys.argv[1])
|
||||
from fastapi.testclient import TestClient
|
||||
from app import main, db, auth, google_auth
|
||||
|
||||
gagal = []
|
||||
def cek(ok, pesan):
|
||||
print(("OK " if ok else "GAGAL"), pesan)
|
||||
if not ok: gagal.append(pesan)
|
||||
|
||||
kap = next(p for p in db.daftar_pengguna() if p["role"] == "kaprodi")
|
||||
dsn = next(p for p in db.daftar_pengguna() if p["role"] == "dosen")
|
||||
for k in ("GOOGLE_CLIENT_ID", "GOOGLE_CLIENT_SECRET"):
|
||||
os.environ.pop(k, None)
|
||||
|
||||
def klien(u=None):
|
||||
c = TestClient(main.app)
|
||||
if u:
|
||||
t = auth.token_baru(); db.buat_sesi(u["id"], t); c.cookies.set("sesi", t)
|
||||
return c
|
||||
|
||||
# 1) tanpa env: tombol tersembunyi, rute menolak
|
||||
c = klien()
|
||||
cek("Masuk dengan Google" not in c.get("/login").text, "tanpa GOOGLE_CLIENT_ID: tombol login Google tersembunyi")
|
||||
cek("Hubungkan akun Google" not in klien(dsn).get("/akun").text, "tanpa env: kartu Akun Google tersembunyi")
|
||||
cek("/login" in c.get("/auth/google", follow_redirects=False).headers["location"], "tanpa env: /auth/google dialihkan ke login")
|
||||
|
||||
os.environ["GOOGLE_CLIENT_ID"] = "uji.apps.googleusercontent.com"
|
||||
os.environ["GOOGLE_CLIENT_SECRET"] = "rahasia-uji"
|
||||
cek("Masuk dengan Google" in c.get("/login").text, "dengan env: tombol login Google tampil")
|
||||
|
||||
# tiruan Google: klaim id_token untuk kode berikutnya
|
||||
KLAIM = {}
|
||||
def tiru(code, redirect):
|
||||
k = {"iss": "https://accounts.google.com", "aud": os.environ["GOOGLE_CLIENT_ID"],
|
||||
"exp": time.time() + 300, "email_verified": True, **KLAIM}
|
||||
bagian = base64.urlsafe_b64encode(json.dumps(k).encode()).decode().rstrip("=")
|
||||
return {"id_token": f"x.{bagian}.y"}
|
||||
google_auth._minta_token = tiru
|
||||
|
||||
def alur(c, tujuan="masuk", **klaim):
|
||||
"""Jalankan /auth/google → callback; kembalikan respons callback."""
|
||||
r = c.get(f"/auth/google?tujuan={tujuan}", follow_redirects=False)
|
||||
if "accounts.google.com" not in r.headers.get("location", ""):
|
||||
return r
|
||||
q = parse_qs(urlparse(r.headers["location"]).query)
|
||||
KLAIM.clear(); KLAIM.update({"nonce": q["nonce"][0], **klaim})
|
||||
return c.get(f"/auth/google/callback?code=abc&state={q['state'][0]}", follow_redirects=False)
|
||||
|
||||
# 2) URL otorisasi
|
||||
r = c.get("/auth/google", follow_redirects=False)
|
||||
q = parse_qs(urlparse(r.headers["location"]).query)
|
||||
cek(q["redirect_uri"][0].endswith("/auth/google/callback") and q["hd"][0] == "untan.ac.id"
|
||||
and q["scope"][0] == "openid email profile" and "g_oauth" in r.headers.get("set-cookie", ""),
|
||||
"URL Google: redirect_uri, hd=untan.ac.id, scope dasar, cookie state")
|
||||
|
||||
# 3) belum terhubung & email tak terdaftar → ditolak, tidak membuat akun
|
||||
n0 = len(db.daftar_pengguna(True))
|
||||
r = alur(klien(), sub="g-asing", email="orang@informatika.untan.ac.id")
|
||||
cek("/login" in r.headers["location"] and "belum terhubung" in unquote_plus(r.headers["location"])
|
||||
and len(db.daftar_pengguna(True)) == n0, "email tak terdaftar: ditolak, tanpa akun baru")
|
||||
|
||||
# 4) domain bukan kampus / email belum verifikasi
|
||||
r = alur(klien(), sub="g-gmail", email="dosen@gmail.com")
|
||||
cek("akun Google kampus" in unquote_plus(r.headers["location"]), "Gmail pribadi ditolak")
|
||||
r = alur(klien(), sub="g-x", email="x@untan.ac.id.evil.com")
|
||||
cek("akun Google kampus" in unquote_plus(r.headers["location"]), "domain tiruan (untan.ac.id.evil.com) ditolak")
|
||||
r = alur(klien(), sub="g-nv", email="nv@untan.ac.id", email_verified=False)
|
||||
cek("belum terverifikasi" in unquote_plus(r.headers["location"]), "email belum terverifikasi ditolak")
|
||||
|
||||
# 5) state & nonce
|
||||
c5 = klien(); r = c5.get("/auth/google", follow_redirects=False)
|
||||
r = c5.get("/auth/google/callback?code=abc&state=PALSU", follow_redirects=False)
|
||||
cek("tidak valid" in unquote_plus(r.headers["location"]), "state tidak cocok ditolak")
|
||||
r = alur(klien(), sub="g1", email="a@untan.ac.id", nonce="lain")
|
||||
cek("kedaluwarsa" in unquote_plus(r.headers["location"]), "nonce tidak cocok ditolak")
|
||||
r = klien().get("/auth/google/callback?error=access_denied&state=x", follow_redirects=False)
|
||||
cek("dibatalkan" in unquote_plus(r.headers["location"]), "pengguna membatalkan di Google")
|
||||
|
||||
# 6) hubungkan dari menu Akun (sudah login), lalu masuk dengan Google
|
||||
cd = klien(dsn)
|
||||
cek("Hubungkan akun Google" in cd.get("/akun").text, "Akun: tombol Hubungkan tampil")
|
||||
r = alur(cd, "hubung", sub="g-dosen", email="dosen.uji@informatika.untan.ac.id")
|
||||
cek(r.headers["location"].startswith("/akun?pesan=") and db.pengguna_by_id(dsn["id"])["google_sub"] == "g-dosen",
|
||||
"hubungkan: sub tersimpan di akun dosen")
|
||||
cek(db.pengguna_by_id(dsn["id"])["email"] in ("dosen.uji@informatika.untan.ac.id", dsn.get("email") or "x"),
|
||||
"hubungkan: email akun terisi bila sebelumnya kosong")
|
||||
cn = klien(); r = alur(cn, sub="g-dosen", email="dosen.uji@informatika.untan.ac.id")
|
||||
cek(r.status_code == 303 and r.headers["location"] == "/" and "sesi=" in r.headers.get("set-cookie", ""),
|
||||
"masuk dengan Google → sesi dosen")
|
||||
cek(cn.get("/akun").status_code == 200 and dsn["nama"] in cn.get("/akun").text, "sesi Google = akun dosen yang benar")
|
||||
cek(klien().get("/auth/google?tujuan=hubung", follow_redirects=False).headers["location"].startswith("/login"),
|
||||
"hubung tanpa login → diminta masuk dulu")
|
||||
|
||||
# 7) satu akun Google hanya untuk satu akun aplikasi
|
||||
r = alur(klien(kap), "hubung", sub="g-dosen", email="dosen.uji@informatika.untan.ac.id")
|
||||
cek("sudah terhubung ke akun lain" in unquote_plus(r.headers["location"])
|
||||
and db.pengguna_by_id(kap["id"])["google_sub"] == "", "Google yang sama tidak bisa ditautkan ke akun kedua")
|
||||
|
||||
# 8) tautan otomatis lewat email terdaftar (login pertama)
|
||||
db.ubah_dosen(kap["id"], email="kaprodi.uji@untan.ac.id")
|
||||
r = alur(klien(), sub="g-kap", email="Kaprodi.Uji@untan.ac.id")
|
||||
cek(r.headers["location"] == "/" and db.pengguna_by_id(kap["id"])["google_sub"] == "g-kap",
|
||||
"email terdaftar (beda huruf besar/kecil) → tertaut otomatis & masuk")
|
||||
|
||||
# 9) akun nonaktif tidak bisa masuk dengan Google
|
||||
db.ubah_dosen(dsn["id"], aktif=False)
|
||||
r = alur(klien(), sub="g-dosen", email="dosen.uji@informatika.untan.ac.id")
|
||||
cek("/login" in r.headers["location"], "akun nonaktif: masuk dengan Google ditolak")
|
||||
db.ubah_dosen(dsn["id"], aktif=True)
|
||||
|
||||
# 10) putus (pengguna) & putus oleh kaprodi
|
||||
cd = klien(dsn)
|
||||
cd.post("/akun/google/putus", follow_redirects=False)
|
||||
cek(not db.google_terhubung(db.pengguna_by_id(dsn["id"])), "pengguna memutus akun Google sendiri")
|
||||
r = alur(klien(), sub="g-dosen", email="dosen.uji@informatika.untan.ac.id")
|
||||
cek("/login" in r.headers["location"], "diputus pemilik: Google lama tidak tertaut otomatis lagi")
|
||||
cek("Hubungkan akun Google" in klien(dsn).get("/akun").text, "diputus pemilik: Akun kembali menawarkan Hubungkan")
|
||||
r = alur(klien(dsn), "hubung", sub="g-dosen", email="dosen.uji@informatika.untan.ac.id")
|
||||
cek(db.google_terhubung(db.pengguna_by_id(dsn["id"])), "pemilik bisa menghubungkan lagi secara sengaja")
|
||||
ck = klien(kap)
|
||||
cek("terhubung" in ck.get("/master/dosen").text, "Data Master Dosen: lencana Google terhubung tampil")
|
||||
ck.post(f"/master/dosen/{kap['id']}", data={"aksi": "putus_google"}, follow_redirects=False)
|
||||
cek(db.pengguna_by_id(kap["id"])["google_sub"] == "", "kaprodi memutus tautan Google dari Data Master")
|
||||
r = alur(klien(), sub="g-kap2", email="kaprodi.uji@untan.ac.id")
|
||||
cek(db.pengguna_by_id(kap["id"])["google_sub"] == "g-kap2", "diputus kaprodi: tautan otomatis via email kembali boleh")
|
||||
|
||||
# 11) login NIP tetap jalan
|
||||
r = klien().post("/login", data={"nip": kap["username"], "password": kap["username"]}, follow_redirects=False)
|
||||
cek(r.status_code in (200, 303), "login NIP/password tetap tersedia")
|
||||
|
||||
print("TOTAL GAGAL:", len(gagal))
|
||||
sys.exit(1 if gagal else 0)
|
||||
Reference in New Issue
Block a user