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:
Power BI Dev
2026-10-18 08:09:09 +07:00
co-authored by Claude Opus 5.5
parent 549fe53a11
commit b09785fc62
9 changed files with 416 additions and 8 deletions
+93 -5
View File
@@ -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", ""))