class JwtError {
readonly _tag = "JwtError";
}
class UserConnectionError {
readonly _tag = "UserConnectionError";
}
type JwtPayload = { id: number; name: string; time: number; iat: number };
const auth = async (pathname: string, user: string | undefined) => {
if (!pathname.startsWith("/admin")) return true;
if (pathname.startsWith("/admin/login")) return true;
if (!user) return false;
const jwtVerification = Effect.try({
try: () => jwt.verify(user, process.env.JWT_SECRET!) as JwtPayload,
catch: () => new JwtError(),
});
const checkUserExists = (id: number, name: string) => {
return Effect.tryPromise({
try: async () => {
const res = await pg
.select({ count: sql<number>`count(*)` })
.from(users)
.where(and(eq(users.id, id), eq(users.name, name)));
return res[0].count > 0;
},
catch: () => new UserConnectionError(),
});
};
const program = pipe(
jwtVerification,
Effect.flatMap(({ id, name }) => checkUserExists(id, name)),
);
const handling = Effect.match(program, {
onSuccess: (x) => x,
onFailure(error) {
if (error._tag === "UserConnectionError") {
console.log(`Error: ${error._tag}`);
}
return false;
},
});
return Effect.runPromise(handling);
};
export default auth;
class JwtError {
readonly _tag = "JwtError";
}
class UserConnectionError {
readonly _tag = "UserConnectionError";
}
type JwtPayload = { id: number; name: string; time: number; iat: number };
const auth = async (pathname: string, user: string | undefined) => {
if (!pathname.startsWith("/admin")) return true;
if (pathname.startsWith("/admin/login")) return true;
if (!user) return false;
const jwtVerification = Effect.try({
try: () => jwt.verify(user, process.env.JWT_SECRET!) as JwtPayload,
catch: () => new JwtError(),
});
const checkUserExists = (id: number, name: string) => {
return Effect.tryPromise({
try: async () => {
const res = await pg
.select({ count: sql<number>`count(*)` })
.from(users)
.where(and(eq(users.id, id), eq(users.name, name)));
return res[0].count > 0;
},
catch: () => new UserConnectionError(),
});
};
const program = pipe(
jwtVerification,
Effect.flatMap(({ id, name }) => checkUserExists(id, name)),
);
const handling = Effect.match(program, {
onSuccess: (x) => x,
onFailure(error) {
if (error._tag === "UserConnectionError") {
console.log(`Error: ${error._tag}`);
}
return false;
},
});
return Effect.runPromise(handling);
};
export default auth;