Skip to content

Commit

Permalink
Domain verification fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
Rajat Saxena committed Mar 14, 2024
1 parent 83be752 commit 0cdde27
Show file tree
Hide file tree
Showing 6 changed files with 81 additions and 51 deletions.
2 changes: 1 addition & 1 deletion apps/web/lib/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ export const capitalize = (s: string) => {
return s.charAt(0).toUpperCase() + s.slice(1);
};

export const isSubscriptionValid = (dateStr: Date): boolean => {
export const isDateInFuture = (dateStr: Date): boolean => {
return new Date(dateStr).getTime() > new Date().getTime();
};

Expand Down
45 changes: 28 additions & 17 deletions apps/web/middlewares/verify-domain.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import DomainModel, { Domain } from "../models/Domain";
import { responses } from "../config/strings";
import constants from "../config/constants";
import { isSubscriptionValid } from "../lib/utils";
import { isDateInFuture } from "../lib/utils";
import { NextApiResponse } from "next";
import ApiRequest from "../models/ApiRequest";
import { createUser } from "../graphql/users/logic";
Expand Down Expand Up @@ -56,31 +56,42 @@ export default async function verifyDomain(
});
}

try {
if (!process.env.SUBSCRIPTION_APP_ENDPOINT) {
throw new Error("Subscription app endpoint is missing");
}
if (
!domain.checkSubscriptionStatusAfter ||
(domain.checkSubscriptionStatusAfter &&
!isDateInFuture(domain.checkSubscriptionStatusAfter))
) {
try {
if (!process.env.SUBSCRIPTION_APP_ENDPOINT) {
throw new Error("Subscription app endpoint is missing");
}

const response = await fetch(
`${process.env.SUBSCRIPTION_APP_ENDPOINT}/school/${domain.name}/verify`,
);
if (response.ok) {
const data = await response.json();
if (!data) {
const response = await fetch(
`${process.env.SUBSCRIPTION_APP_ENDPOINT}/school/${domain.name}/verify`,
);
if (response.ok) {
const data = await response.json();
if (!data) {
return res.status(404).json({
message: responses.not_valid_subscription,
});
}
} else {
return res
.status(404)
.json({ message: responses.not_valid_subscription });
}
} else {
} catch (err: any) {
console.error(err);
return res
.status(404)
.json({ message: responses.not_valid_subscription });
}
} catch (err: any) {
console.error(err);
return res
.status(404)
.json({ message: responses.not_valid_subscription });

const currentDate = new Date();
const dateAfter24Hours = new Date(currentDate.getTime() + 86400000);
domain.checkSubscriptionStatusAfter = dateAfter24Hours;
await (domain as any).save();
}
} else {
domain = await DomainModel.findOne({
Expand Down
2 changes: 2 additions & 0 deletions apps/web/models/Domain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ export interface Domain {
draftTypefaces: Typeface[];
firstRun: boolean;
tags: string[];
checkSubscriptionStatusAfter: Date;
}

export const defaultTypeface: Typeface = {
Expand Down Expand Up @@ -55,6 +56,7 @@ const DomainSchema = new mongoose.Schema<Domain>(
draftTypefaces: { type: [TypefaceSchema], default: [defaultTypeface] },
firstRun: { type: Boolean, required: true, default: false },
tags: { type: [String], default: [] },
checkSubscriptionStatusAfter: { type: Date },
},
{
timestamps: true,
Expand Down
73 changes: 40 additions & 33 deletions apps/web/pages/api/auth/[...nextauth].ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import nc from "next-connect";
import { NextAuthOptions } from "next-auth";
import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
Expand All @@ -6,28 +7,50 @@ import User from "../../../models/User";
import VerificationToken from "../../../models/VerificationToken";
import connectToDatabase from "../../../services/db";
import { hashCode } from "../../../ui-lib/utils";
import Domain from "../../../models/Domain";
import { Domain } from "../../../models/Domain";
import { NextApiRequest, NextApiResponse } from "next";
import constants from "../../../config/constants";
import connectDb from "../../../middlewares/connect-db";
import verifyDomain from "../../../middlewares/verify-domain";
import { error } from "../../../services/logger";
import ApiRequest from "@models/ApiRequest";

export const authOptions: NextAuthOptions = {
export default nc<NextApiRequest, NextApiResponse>({
onError: (err, req, res, next) => {
error(err.message, {
fileName: `/api/auth/[...nextauth].ts`,
stack: err.stack,
});
res.status(500).json({ error: err.message });
},
onNoMatch: (req, res) => {
res.status(404).end("Page is not found");
},
})
.use(connectDb)
.use(verifyDomain)
.use(auth);

async function auth(req: NextApiRequest, res: NextApiResponse) {
return await NextAuth(req, res, getAuthOptions(req));
}

const getAuthOptions = (req: ApiRequest) => ({
...authOptions,
providers: [
CredentialsProvider({
name: "Email",
credentials: {},
async authorize(credentials, req) {
async authorize(credentials: any) {
const { email, code } = credentials;
let domain: string;
if (process.env.MULTITENANT === "true") {
domain = req.headers?.host?.split(".")[0];
} else {
domain = constants.domainNameForSingleTenancy;
}

return await authorize({ email, code, domain });
return await authorize({ email, code, domain: req.subdomain });
},
}),
],
});

export const authOptions: NextAuthOptions = {
providers: [],
pages: {
signIn: "/login",
},
Expand All @@ -45,37 +68,27 @@ async function authorize({
}: {
email: string;
code: string;
domain: string;
domain: Domain;
}) {
await connectToDatabase();

const tokenFilter = {
const verificationToken = await VerificationToken.findOneAndDelete({
email,
domain,
domain: domain.name,
code: hashCode(+code),
timestamp: { $gt: Date.now() },
};
const verificationToken =
await VerificationToken.findOneAndDelete(tokenFilter);
console.log(tokenFilter, verificationToken); // eslint-disable-line no-console
});
if (!verificationToken) {
throw new Error("Invalid code");
}

let domainObj = await Domain.findOne({
name: domain,
});
if (!domainObj) {
throw new Error("Invalid domain");
}

let user = await User.findOne({
domain: domainObj._id,
domain: domain._id,
email,
});
if (!user) {
user = await createUser({
domain: domainObj,
domain,
email,
});
}
Expand All @@ -85,9 +98,3 @@ async function authorize({
name: user.name,
};
}

export default async function auth(req: NextApiRequest, res: NextApiResponse) {
return await NextAuth(req, res, authOptions);
}

//export default NextAuth(authOptions)
5 changes: 5 additions & 0 deletions apps/web/pages/blog/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,11 @@ const getCourses = async (backend: string) => {
export async function getServerSideProps({ req }: any) {
const address = getBackendAddress(req.headers);
const page = await getPage(address);
if (!page) {
return {
notFound: true,
};
}
const courses = await getCourses(address);
return { props: { courses, page } };
}
Expand Down
5 changes: 5 additions & 0 deletions apps/web/pages/login.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -200,5 +200,10 @@ export async function getServerSideProps(context: any) {
const { req } = context;
const address = getBackendAddress(req.headers);
const page = await getPage(address);
if (!page) {
return {
notFound: true,
};
}
return { props: { page } };
}

0 comments on commit 0cdde27

Please sign in to comment.