Middleware and iframe updates

This commit is contained in:
Darren Clarke 2023-03-01 11:02:15 +00:00
parent d7624d723f
commit ba04aa108c
29 changed files with 69 additions and 4128 deletions

View file

@ -10,9 +10,13 @@ export const ZammadWrapper: FC<ZammadWrapperProps> = ({
path,
hideSidebar = true,
}) => {
const origin = typeof window !== 'undefined' && window.location.origin
? window.location.origin
: '';
const [display, setDisplay] = useState("hidden");
const url = `https://redaranj-bookish-tribble-56jwjx5wh4j4w-8003.preview.app.github.dev/zammad${path}`;
console.log({ base: process.env.LINK_URL, path, url })
const url = `${origin}/zammad${path}`;
console.log({ origin, path, url });
return (
< Iframe
id="link"
@ -20,8 +24,7 @@ export const ZammadWrapper: FC<ZammadWrapperProps> = ({
width="100%"
height="100%"
frameBorder={0}
styles={{ display }
}
styles={{ display }}
onLoad={() => {
const linkElement = document.querySelector("iframe");
if (
@ -43,8 +46,10 @@ export const ZammadWrapper: FC<ZammadWrapperProps> = ({
linkElement.contentDocument.querySelector(".sidebar").style =
"display: none";
}
setDisplay("inherit");
}
setDisplay("inherit");
}}
/>
);

View file

@ -1,45 +0,0 @@
// middleware.ts
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { withAuth } from "next-auth/middleware"
export default withAuth((request: NextRequest) => {
if (request.nextUrl.pathname.startsWith('/login')) {
return NextResponse.next()
}
// @ts-expect-error
if (!request.nextauth.token) {
return NextResponse.redirect("/login")
}
// @ts-expect-error
console.log({ token: request.nextauth.token })
console.log("INTO middleware")
const path = request.nextUrl.pathname
console.log({ path })
const zammadPaths = ['/zammad', '/assets', '/api/v1', '/auth/sso', '/ws'];
if (zammadPaths.some((p) => path.startsWith(p))) {
console.log("MATCHED ZAMMAD PATH")
const finalURL = new URL(path.replace("/zammad", ""), process.env.ZAMMAD_URL)
console.log(finalURL.toString())
const requestHeaders = new Headers(request.headers)
// @ts-expect-error
requestHeaders.set('X-Forwarded-User', request.nextauth.token?.email)
requestHeaders.set('Host', 'zammad.example.com')
console.log(requestHeaders)
return NextResponse.rewrite(finalURL, {
request: {
headers: requestHeaders
}
})
} else {
console.log("DID NOT MATCH ZAMMAD PATH")
return NextResponse.next()
}
}, {
pages: {
signIn: '/login',
}
})

View file

@ -13,18 +13,13 @@ module.exports = {
},
];
},
async rewrites() {
return {
beforeFiles: [
{
source: "/assets/:path*",
destination: `/zammad/assets/:path*`,
},
{
source: "/api/v1/:path*",
destination: `/zammad/api/v1/:path*`,
},
],
};
}, */
*/
rewrites: async () => ({
fallback: [
{
source: "/:path*",
destination: "/api/proxy/:path*",
},
],
}),
};

View file

@ -0,0 +1,39 @@
import { NextApiRequest, NextApiResponse } from 'next';
import { createProxyMiddleware } from 'http-proxy-middleware';
import { getToken } from "next-auth/jwt";
const withAuthInfo =
(handler) => async (req: NextApiRequest, res: NextApiResponse) => {
const session = await getToken({
req,
secret: process.env.NEXTAUTH_SECRET,
});
if (!session) {
return res.redirect("/login");
}
req.headers['X-Forwarded-User'] = session.email.toLowerCase();
req.headers['Host'] = 'zammad.example.com';
console.log({ headers: req.headers })
return handler(req, res);
};
const proxy = createProxyMiddleware({
target: process.env.ZAMMAD_URL,
changeOrigin: true,
xfwd: true,
ws: true,
pathRewrite: { "^/zammad": "" },
});
export default withAuthInfo(proxy);
export const config = {
api: {
bodyParser: false,
externalResolver: true,
},
};

View file

@ -4,6 +4,9 @@ import { Apple as AppleIcon, Google as GoogleIcon } from "@mui/icons-material";
import { signIn, getSession } from "next-auth/react";
const Login = ({ session }) => {
const origin = typeof window !== 'undefined' && window.location.origin
? window.location.origin
: '';
const buttonStyles = {
borderRadius: 500,
width: "100%",
@ -40,7 +43,7 @@ const Login = ({ session }) => {
sx={buttonStyles}
onClick={() =>
signIn("google", {
callbackUrl: `https://redaranj-bookish-tribble-56jwjx5wh4j4w-8003.preview.app.github.dev/auth/sso`,
callbackUrl: `${origin}/auth/sso`,
})
}
>

View file

@ -12,18 +12,21 @@ type TicketProps = {
};
const Ticket: NextPage<TicketProps> = ({ id }) => {
const origin = typeof window !== 'undefined' && window.location.origin
? window.location.origin
: '';
const fetcher = async (url: string) => {
const res = await fetch(url);
return res.json();
}
const { data: ticketData, error: ticketError } = useSWR(
`https://redaranj-bookish-tribble-56jwjx5wh4j4w-8003.preview.app.github.dev/api/v1/tickets/${id}`,
`${origin}/api/v1/tickets/${id}`,
fetcher
);
const { data: articlesData, error: articlesError } = useSWR(
`https://redaranj-bookish-tribble-56jwjx5wh4j4w-8003.preview.app.github.dev/api/v1/ticket_articles/by_ticket/${id}`,
`${origin}/api/v1/ticket_articles/by_ticket/${id}`,
fetcher
);