v0.1.0 — Moon Base initial scaffold: auth, garden plant registry + log

This commit is contained in:
Bonna Moon
2026-06-15 16:14:48 -05:00
commit 99918fffbc
47 changed files with 2764 additions and 0 deletions

110
src/lib/auth.ts Normal file
View File

@@ -0,0 +1,110 @@
import { NextAuthOptions, getServerSession } from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import { compare } from "bcryptjs";
import { db } from "@/lib/db";
import { UserRole } from "@prisma/client";
declare module "next-auth" {
interface Session {
user: {
id: string;
email: string;
name: string;
role: UserRole;
mustChangePassword: boolean;
};
}
interface User {
id: string;
role: UserRole;
mustChangePassword: boolean;
}
}
declare module "next-auth/jwt" {
interface JWT {
id: string;
role: UserRole;
mustChangePassword: boolean;
}
}
export const authOptions: NextAuthOptions = {
session: { strategy: "jwt" },
pages: { signIn: "/login", error: "/login" },
providers: [
CredentialsProvider({
name: "credentials",
credentials: {
email: { label: "Username or email", type: "text" },
password: { label: "Password", type: "password" },
},
async authorize(credentials) {
if (!credentials?.email || !credentials?.password) return null;
const id = credentials.email.trim();
const user = await db.user.findFirst({
where: {
active: true,
OR: [
{ email: id.toLowerCase() },
{ username: { equals: id, mode: "insensitive" } },
],
},
select: {
id: true,
name: true,
email: true,
passwordHash: true,
role: true,
mustChangePassword: true,
},
});
if (!user) return null;
const ok = await compare(credentials.password, user.passwordHash);
if (!ok) return null;
return {
id: user.id,
email: user.email,
name: user.name,
role: user.role,
mustChangePassword: user.mustChangePassword,
};
},
}),
],
callbacks: {
async jwt({ token, user, trigger }) {
if (user) {
token.id = user.id;
token.role = user.role;
token.mustChangePassword = user.mustChangePassword;
}
if (trigger === "update") {
const fresh = await db.user.findUnique({
where: { id: token.id },
select: { mustChangePassword: true },
});
if (fresh) token.mustChangePassword = fresh.mustChangePassword;
}
return token;
},
async session({ session, token }) {
session.user.id = token.id;
session.user.role = token.role;
session.user.mustChangePassword = token.mustChangePassword;
return session;
},
},
};
export const getSession = () => getServerSession(authOptions);
export async function requireAuth() {
const session = await getSession();
if (!session) throw new Error("Unauthorized");
return session;
}
export function isAdmin(role: UserRole): boolean {
return role === "ADMIN";
}