- users.password_hash/password_set_at/disabled_at (migration 0002_local_users) - core/local-users.ts: scrypt, passwordLogin with attempt limits, create/reset/disable - isSuperadmin(db, user) = platform.admins; isUserAllowed honours disabled_at - web: /auth/password + login form, /users for superadmins, Settings → password - Gitea login with a local user's login is refused (giteaLoginRefusal) - local users: projects in peppa-bot namespace, members without Gitea collaboration - CLI: peppa user add|passwd|disable|enable; tests in testkit Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
38 lines
2.2 KiB
TypeScript
38 lines
2.2 KiB
TypeScript
import { exchangeOAuthCode, getUserByLogin, giteaLoginRefusal, GiteaClient, isLoginAllowed, isUserAllowed, upsertUserFromGitea } from "@peppa/core";
|
||
import { loadEnv } from "@peppa/shared";
|
||
import { cookies } from "next/headers";
|
||
import { NextResponse, type NextRequest } from "next/server";
|
||
import { NEXT_COOKIE, publicOrigin, safeNext, sessionCookie, STATE_COOKIE } from "@/lib/auth";
|
||
import { db } from "@/lib/db";
|
||
|
||
export async function GET(req: NextRequest) {
|
||
const env = loadEnv();
|
||
const origin = await publicOrigin();
|
||
const fail = (msg: string) => NextResponse.redirect(`${origin}/login?error=${encodeURIComponent(msg)}`);
|
||
const code = req.nextUrl.searchParams.get("code");
|
||
const state = req.nextUrl.searchParams.get("state");
|
||
const expected = (await cookies()).get(STATE_COOKIE)?.value;
|
||
if (!code || !state || !expected || state !== expected) return fail("Вход не подтверждён (state не совпал) — попробуйте ещё раз");
|
||
if (!env.GITEA_OAUTH_CLIENT_ID || !env.GITEA_OAUTH_CLIENT_SECRET) return fail("OAuth не настроен");
|
||
try {
|
||
const tokens = await exchangeOAuthCode(env.GITEA_URL, env.GITEA_OAUTH_CLIENT_ID, env.GITEA_OAUTH_CLIENT_SECRET, code, `${origin}/auth/callback`);
|
||
const me = await new GiteaClient(env.GITEA_URL, tokens.access_token).me();
|
||
// PEP-68: a local user's login is never merged with a Gitea account; disabled users stay out.
|
||
const refusal = await giteaLoginRefusal(db, me.login);
|
||
if (refusal) return fail(refusal);
|
||
const existing = await getUserByLogin(db, me.login);
|
||
if (!(await isLoginAllowed(db, me.login)) && !(existing && (await isUserAllowed(db, existing)))) {
|
||
return fail("Нет доступа к Пеппе — попросите администратора");
|
||
}
|
||
const user = await upsertUserFromGitea(db, me, tokens);
|
||
const res = NextResponse.redirect(`${origin}${safeNext((await cookies()).get(NEXT_COOKIE)?.value)}`);
|
||
res.cookies.delete({ name: NEXT_COOKIE, path: "/auth" });
|
||
const c = sessionCookie(user.id);
|
||
res.cookies.set(c.name, c.value, c.options);
|
||
res.cookies.delete({ name: STATE_COOKIE, path: "/auth" });
|
||
return res;
|
||
} catch (e) {
|
||
return fail(`Не удалось войти: ${(e as Error).message}`);
|
||
}
|
||
}
|