Migrate from Replit infrastructure: Neon→PostgreSQL, GCS→S3, ReplitAuth→email/password, add Dockerfile
This commit is contained in:
+44
-156
@@ -1,31 +1,21 @@
|
||||
import * as client from "openid-client";
|
||||
import { Strategy, type VerifyFunction } from "openid-client/passport";
|
||||
import passport from "passport";
|
||||
import session from "express-session";
|
||||
import type { Express, RequestHandler } from "express";
|
||||
import memoize from "memoizee";
|
||||
import connectPg from "connect-pg-simple";
|
||||
import type { Express, RequestHandler, Request, Response, NextFunction } from "express";
|
||||
import bcrypt from "bcryptjs";
|
||||
import { storage } from "./storage";
|
||||
import { createHash } from "crypto";
|
||||
|
||||
if (!process.env.REPLIT_DOMAINS) {
|
||||
throw new Error("Environment variable REPLIT_DOMAINS not provided");
|
||||
declare module "express-session" {
|
||||
interface SessionData {
|
||||
userId?: string;
|
||||
isAdmin?: boolean;
|
||||
isSuperAdmin?: boolean;
|
||||
}
|
||||
}
|
||||
|
||||
const getOidcConfig = memoize(
|
||||
async () => {
|
||||
return await client.discovery(
|
||||
new URL(process.env.ISSUER_URL ?? "https://replit.com/oidc"),
|
||||
process.env.REPL_ID!
|
||||
);
|
||||
},
|
||||
{ maxAge: 3600 * 1000 }
|
||||
);
|
||||
|
||||
export function getSession() {
|
||||
const sessionTtl = 7 * 24 * 60 * 60 * 1000; // 1 week
|
||||
const pgStore = connectPg(session);
|
||||
const sessionStore = new pgStore({
|
||||
const sessionTtl = 7 * 24 * 60 * 60 * 1000;
|
||||
const PgStore = connectPg(session);
|
||||
const sessionStore = new PgStore({
|
||||
conString: process.env.DATABASE_URL,
|
||||
createTableIfMissing: false,
|
||||
ttl: sessionTtl,
|
||||
@@ -38,155 +28,53 @@ export function getSession() {
|
||||
saveUninitialized: false,
|
||||
cookie: {
|
||||
httpOnly: true,
|
||||
secure: true,
|
||||
secure: process.env.NODE_ENV === "production",
|
||||
maxAge: sessionTtl,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function updateUserSession(
|
||||
user: any,
|
||||
tokens: client.TokenEndpointResponse & client.TokenEndpointResponseHelpers
|
||||
) {
|
||||
user.claims = tokens.claims();
|
||||
user.access_token = tokens.access_token;
|
||||
user.refresh_token = tokens.refresh_token;
|
||||
user.expires_at = user.claims?.exp;
|
||||
}
|
||||
|
||||
function generateDeterministicUUID(replitId: string): string {
|
||||
// Create a deterministic UUID from Replit ID
|
||||
// This ensures the same Replit user always gets the same UUID
|
||||
const hash = createHash('sha256').update(`replit_${replitId}`).digest('hex');
|
||||
// Format as UUID v4: xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
|
||||
return [
|
||||
hash.substring(0, 8),
|
||||
hash.substring(8, 12),
|
||||
'4' + hash.substring(13, 16),
|
||||
(parseInt(hash.substring(16, 17), 16) & 0x3 | 0x8).toString(16) + hash.substring(17, 20),
|
||||
hash.substring(20, 32)
|
||||
].join('-');
|
||||
}
|
||||
|
||||
async function upsertUser(claims: any) {
|
||||
// Generate a deterministic UUID from Replit ID
|
||||
const userId = generateDeterministicUUID(claims["sub"]);
|
||||
|
||||
await storage.upsertUser({
|
||||
id: userId,
|
||||
email: claims["email"],
|
||||
firstName: claims["first_name"],
|
||||
lastName: claims["last_name"],
|
||||
profileImageUrl: claims["profile_image_url"],
|
||||
});
|
||||
}
|
||||
|
||||
export async function setupAuth(app: Express) {
|
||||
app.set("trust proxy", 1);
|
||||
app.use(getSession());
|
||||
app.use(passport.initialize());
|
||||
app.use(passport.session());
|
||||
|
||||
const config = await getOidcConfig();
|
||||
|
||||
const verify: VerifyFunction = async (
|
||||
tokens: client.TokenEndpointResponse & client.TokenEndpointResponseHelpers,
|
||||
verified: passport.AuthenticateCallback
|
||||
) => {
|
||||
const user = {};
|
||||
updateUserSession(user, tokens);
|
||||
await upsertUser(tokens.claims());
|
||||
verified(null, user);
|
||||
};
|
||||
|
||||
for (const domain of process.env.REPLIT_DOMAINS!.split(",")) {
|
||||
const strategy = new Strategy(
|
||||
{
|
||||
name: `replitauth:${domain}`,
|
||||
config,
|
||||
scope: "openid email profile offline_access",
|
||||
callbackURL: `https://${domain}/api/callback`,
|
||||
},
|
||||
verify,
|
||||
);
|
||||
passport.use(strategy);
|
||||
}
|
||||
|
||||
passport.serializeUser((user: Express.User, cb) => cb(null, user));
|
||||
passport.deserializeUser((user: Express.User, cb) => cb(null, user));
|
||||
|
||||
app.get("/api/login", (req, res, next) => {
|
||||
passport.authenticate(`replitauth:${req.hostname}`, {
|
||||
prompt: "login consent",
|
||||
scope: ["openid", "email", "profile", "offline_access"],
|
||||
})(req, res, next);
|
||||
// POST /api/auth/login — email + password
|
||||
app.post("/api/auth/login", async (req: Request, res: Response) => {
|
||||
const { email, password } = req.body || {};
|
||||
if (!email || !password) return res.status(400).json({ error: "Email and password required" });
|
||||
try {
|
||||
const user = await storage.getUserByEmail(email);
|
||||
if (!user || !user.passwordHash) return res.status(401).json({ error: "Invalid credentials" });
|
||||
const ok = await bcrypt.compare(password, user.passwordHash);
|
||||
if (!ok || !user.isActive) return res.status(401).json({ error: "Invalid credentials" });
|
||||
req.session.userId = user.id;
|
||||
req.session.isAdmin = !!user.isAdmin || !!user.isSuperAdmin;
|
||||
req.session.isSuperAdmin = !!user.isSuperAdmin;
|
||||
return res.json({ user: { id: user.id, email: user.email, username: user.username, isAdmin: req.session.isAdmin } });
|
||||
} catch (e: any) {
|
||||
console.error("Login err:", e);
|
||||
return res.status(500).json({ error: "Login failed" });
|
||||
}
|
||||
});
|
||||
|
||||
app.get("/api/callback", (req, res, next) => {
|
||||
passport.authenticate(`replitauth:${req.hostname}`, {
|
||||
successReturnToOrRedirect: "/admin",
|
||||
failureRedirect: "/api/login",
|
||||
})(req, res, next);
|
||||
app.post("/api/auth/logout", (req: Request, res: Response) => {
|
||||
req.session.destroy(() => res.json({ ok: true }));
|
||||
});
|
||||
|
||||
app.get("/api/logout", (req, res) => {
|
||||
req.logout(() => {
|
||||
res.redirect(
|
||||
client.buildEndSessionUrl(config, {
|
||||
client_id: process.env.REPL_ID!,
|
||||
post_logout_redirect_uri: `${req.protocol}://${req.hostname}`,
|
||||
}).href
|
||||
);
|
||||
});
|
||||
});
|
||||
app.get("/api/login", (_req, res) => res.redirect("/login"));
|
||||
app.get("/api/callback", (_req, res) => res.redirect("/login"));
|
||||
app.get("/api/logout", (req, res) => { req.session.destroy(() => res.redirect("/")); });
|
||||
}
|
||||
|
||||
export const isAuthenticated: RequestHandler = async (req, res, next) => {
|
||||
const user = req.user as any;
|
||||
|
||||
if (!req.isAuthenticated() || !user.expires_at) {
|
||||
return res.status(401).json({ message: "Unauthorized" });
|
||||
}
|
||||
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
if (now <= user.expires_at) {
|
||||
return next();
|
||||
}
|
||||
|
||||
const refreshToken = user.refresh_token;
|
||||
if (!refreshToken) {
|
||||
res.status(401).json({ message: "Unauthorized" });
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const config = await getOidcConfig();
|
||||
const tokenResponse = await client.refreshTokenGrant(config, refreshToken);
|
||||
updateUserSession(user, tokenResponse);
|
||||
return next();
|
||||
} catch (error) {
|
||||
res.status(401).json({ message: "Unauthorized" });
|
||||
return;
|
||||
}
|
||||
export const isAuthenticated: RequestHandler = (req: any, res, next) => {
|
||||
if (!req.session?.userId) return res.status(401).json({ message: "Unauthorized" });
|
||||
req.user = { claims: { sub: req.session.userId } }; // compat with old code expecting req.user.claims.sub
|
||||
next();
|
||||
};
|
||||
|
||||
export const isAdmin: RequestHandler = async (req, res, next) => {
|
||||
const user = req.user as any;
|
||||
|
||||
if (!req.isAuthenticated() || !user.claims?.sub) {
|
||||
return res.status(401).json({ message: "Unauthorized" });
|
||||
}
|
||||
|
||||
try {
|
||||
// Generate the same deterministic UUID from Replit ID
|
||||
const userId = generateDeterministicUUID(user.claims.sub);
|
||||
const dbUser = await storage.getUser(userId);
|
||||
if (!dbUser || !dbUser.isAdmin) {
|
||||
return res.status(403).json({ message: "Admin access required" });
|
||||
}
|
||||
next();
|
||||
} catch (error) {
|
||||
console.error("Error checking admin status:", error);
|
||||
res.status(500).json({ message: "Internal server error" });
|
||||
}
|
||||
};
|
||||
export const isAdmin: RequestHandler = (req: any, res, next) => {
|
||||
if (!req.session?.userId) return res.status(401).json({ message: "Unauthorized" });
|
||||
if (!req.session.isAdmin) return res.status(403).json({ message: "Forbidden" });
|
||||
req.user = { claims: { sub: req.session.userId } };
|
||||
next();
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user