Skip to content

Commit

Permalink
Merge pull request #42 from Aar-if/main
Browse files Browse the repository at this point in the history
Issue #2195 feat: Use admin app authorisation token in workspace
  • Loading branch information
itsvick authored Oct 16, 2024
2 parents 69ab3d2 + 69b2483 commit 60d52c2
Show file tree
Hide file tree
Showing 2 changed files with 98 additions and 53 deletions.
79 changes: 47 additions & 32 deletions src/pages/api/proxy.ts
Original file line number Diff line number Diff line change
@@ -1,66 +1,81 @@
import { NextApiRequest, NextApiResponse } from 'next';
import { genericEditorSaveFormResponse, telemetryResponse,
creatLockResponse, genericEditorReviewFormResponse } from './mocked-response';
import { NextApiRequest, NextApiResponse } from "next";
import {
genericEditorSaveFormResponse,
telemetryResponse,
creatLockResponse,
genericEditorReviewFormResponse,
} from "./mocked-response";

let storedToken: string | null = null;

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const { method, query } = req;
const { method, body, query } = req;
const { path } = query;

let pathString = Array.isArray(path) ? path.join('/') : (path as string);

const BASE_URL = process.env.BASE_URL as string;
const API_KEY = process.env.AUTH_API_TOKEN as string;
const TENANT_ID = process.env.TENANT_ID as string;
const API_KEY = process.env.AUTH_API_TOKEN as string;

if (pathString === '/action/data/v3/telemetry') {
const token = body?.token || storedToken || API_KEY;

if (body?.token) {
console.log("Received new token:", body.token);
storedToken = body.token;
return res.status(200).json({ message: "Token received" });
}

if (!token) {
console.error("No valid token available");
return res.status(401).json({ message: "Unauthorized: Token is required" });
}

console.log("Using token:", token);

let pathString = Array.isArray(path) ? path.join("/") : (path as string);

// Handle mocked responses
if (pathString === "/action/data/v3/telemetry") {
return res.status(200).json(telemetryResponse);
}

if (pathString === '/action/data/v1/form/read') {
if (req.body.request.action === 'save' && req.body.request.subType === 'resource') {
if (pathString === "/action/data/v1/form/read") {
const { action, subType } = body.request;
if (action === "save" && subType === "resource") {
return res.status(200).json(genericEditorSaveFormResponse);
}
if (req.body.request.action === 'review' && req.body.request.subType === 'resource') {
if (action === "review" && subType === "resource") {
return res.status(200).json(genericEditorReviewFormResponse);
}
console.log('req body ====>', req.body);
}

if (pathString === '/action/lock/v1/create') {
if (pathString === "/action/lock/v1/create") {
return res.status(200).json(creatLockResponse);
}

if (pathString.startsWith('/action/framework/v3/read/')) {
pathString = pathString.replace('/action/framework/v3/read/', '/api/framework/v1/read/');
if (pathString.startsWith("/action/framework/v3/read/")) {
pathString = pathString.replace("/action/framework/v3/read/", "/api/framework/v1/read/");
}

const queryString = req.url?.includes('?') ? req.url.split('?')[1] : '';

// Build target URL
const targetUrl = `${BASE_URL}${pathString}${queryString ? `?${queryString}` : ''}`;
console.log('Target URL:', targetUrl);
const queryString = req.url?.includes("?") ? req.url.split("?")[1] : "";
const targetUrl = `${BASE_URL}${pathString}${queryString ? `?${queryString}` : ""}`;

try {
const options: RequestInit = {
method,
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${API_KEY}`,
'tenantId': TENANT_ID,
'X-Channel-Id': 'test-k12-channel'
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
tenantId: TENANT_ID,
"X-Channel-Id": "test-k12-channel",
},
...(method === "POST" || method === "PATCH" ? { body: JSON.stringify(body) } : {}),
};

if (method === 'POST' || method === 'PATCH') {
options.body = JSON.stringify(req.body);
}

const response = await fetch(targetUrl, options);

const data = await response.json();

res.status(response.status).json(data);
} catch (error: any) {
console.error('Error in proxy:', error.message);
res.status(500).json({ message: 'Error fetching data', error: error.message });
console.error("Error in proxy:", error.message);
res.status(500).json({ message: "Error fetching data", error: error.message });
}
}
72 changes: 51 additions & 21 deletions src/pages/workspace/content/create/index.tsx
Original file line number Diff line number Diff line change
@@ -1,50 +1,80 @@
import React, { useState } from "react";
import React, { useEffect, useState } from "react";
import Layout from "../../../../components/Layout";
import { Typography, Box, useTheme } from "@mui/material";
import ContentCard from "../../../../components/ContentCard";
import DescriptionOutlinedIcon from "@mui/icons-material/DescriptionOutlined";
import DescriptionIcon from "@mui/icons-material/Description";
import UploadIcon from "@mui/icons-material/Upload";
import { useRouter } from "next/router";
import { createQuestionSet } from "@/services/ContentService";
import axios from "axios";

const CreatePage = () => {
const theme = useTheme<any>();
const [selectedKey, setSelectedKey] = useState("create");
const router = useRouter();
const [token, setToken] = useState<string | null>(null);

const sendTokenToProxy = async (storedToken: string) => {
try {
const response = await axios.post(
"/api/proxy",
{ token: storedToken },
{ headers: { "Content-Type": "application/json" } }
);

const fetchData = async () => {
try {
const response = await createQuestionSet();
console.log('Question set created successfully:', response);
const identifier = response?.result?.identifier;

router.push({
pathname: `/editor`,
query: { identifier },
});

} catch (error) {
console.error('Error creating question set:', error);
if (response.status === 200) {
console.log("Token sent successfully to proxy:", storedToken);
return true;
} else {
console.error("Failed to send token to proxy");
return false;
}
};
} catch (error) {
console.error("Error sending token to proxy:", error);
return false;
}
};

const fetchData = async () => {
try {
const storedToken = localStorage.getItem("token");

if (storedToken) {
setToken(storedToken);
const proxySuccess = await sendTokenToProxy(storedToken);

if (!proxySuccess) {
console.error("Proxy request failed. Stopping execution.");
return;
}
} else {
console.warn("No token found. Proceeding without token.");
}

// Call createQuestionSet regardless of token presence
const response = await createQuestionSet();
console.log("Question set created successfully:", response);

const identifier = response?.result?.identifier;
router.push({
pathname: `/editor`,
query: { identifier },
});
} catch (error) {
console.error("Error creating question set:", error);
}
};

const openEditor = () => {
fetchData();
fetchData();
};

const cardData = [
{
title: "Upload Content",
description: "You can upload content here.",
icon: <UploadIcon fontSize="large" />,
onClick: () => {
console.log("Uploading content");
router.push("/upload-editor");
},
onClick: () => router.push("/upload-editor"),
},
{
title: "Question Set",
Expand Down

0 comments on commit 60d52c2

Please sign in to comment.