feat: make edit course page private

This commit is contained in:
swve 2023-04-09 00:07:59 +02:00
parent 46f13fac87
commit 8f8257b9e7
4 changed files with 28 additions and 32 deletions

View file

@ -13,6 +13,7 @@ import NewActivityModal from "@components/Pages/CourseEdit/NewActivity";
import { createActivity, createFileActivity } from "@services/courses/activities"; import { createActivity, createFileActivity } from "@services/courses/activities";
import { getOrganizationContextInfo } from "@services/organizations/orgs"; import { getOrganizationContextInfo } from "@services/organizations/orgs";
import Modal from "@components/UI/Modal/Modal"; import Modal from "@components/UI/Modal/Modal";
import AuthProvider from "@components/Security/AuthProvider";
function CourseEdit(params: any) { function CourseEdit(params: any) {
// Initial Course State // Initial Course State
@ -117,7 +118,7 @@ function CourseEdit(params: any) {
const closeNewActivityModal = () => { const closeNewActivityModal = () => {
console.log("closeNewActivityModal"); console.log("closeNewActivityModal");
setNewActivityModal(false); setNewActivityModal(false);
}; };
@ -225,6 +226,7 @@ function CourseEdit(params: any) {
return ( return (
<> <>
<AuthProvider />
<Page> <Page>
<Title> <Title>
Edit Course {" "} Edit Course {" "}
@ -252,8 +254,8 @@ function CourseEdit(params: any) {
Save Save
</button> </button>
</Title>- </Title>-
<Modal <Modal
isDialogOpen={newActivityModal} isDialogOpen={newActivityModal}
onOpenChange={setNewActivityModal} onOpenChange={setNewActivityModal}
minHeight="no-min" minHeight="no-min"
@ -266,7 +268,7 @@ function CourseEdit(params: any) {
></NewActivityModal>} ></NewActivityModal>}
dialogTitle="Create Activity" dialogTitle="Create Activity"
dialogDescription="Choose between types of activities to add to the course" dialogDescription="Choose between types of activities to add to the course"
/> />
<br /> <br />

View file

@ -1,12 +1,12 @@
"use client"; //todo: use server components "use client"; //todo: use server components
import Link from "next/link"; import Link from "next/link";
import React from "react"; import React from "react";
import Layout from "../../components/UI/Layout";
import { Title } from "../../components/UI/Elements/Styles/Title"; import { Title } from "../../components/UI/Elements/Styles/Title";
import { deleteOrganizationFromBackend } from "@services/organizations/orgs"; import { deleteOrganizationFromBackend } from "@services/organizations/orgs";
import useSWR, { mutate } from "swr"; import useSWR, { mutate } from "swr";
import { swrFetcher } from "@services/utils/requests"; import { swrFetcher } from "@services/utils/requests";
import { getAPIUrl, getUriWithOrg } from "@services/config/config"; import { getAPIUrl, getUriWithOrg } from "@services/config/config";
import AuthProvider from "@components/Security/AuthProvider";
const Organizations = () => { const Organizations = () => {
const { data : organizations , error } = useSWR(`${getAPIUrl()}orgs/user/page/1/limit/10`, swrFetcher) const { data : organizations , error } = useSWR(`${getAPIUrl()}orgs/user/page/1/limit/10`, swrFetcher)
@ -18,6 +18,7 @@ const Organizations = () => {
return ( return (
<> <>
<AuthProvider/>
<Title> <Title>
Your Organizations{" "} Your Organizations{" "}
<Link href={"/organizations/new"}> <Link href={"/organizations/new"}>

View file

@ -5,7 +5,9 @@ import { useRouter, usePathname } from "next/navigation";
export const AuthContext: any = React.createContext({}); export const AuthContext: any = React.createContext({});
const NON_AUTHENTICATED_ROUTES = ["/login", "/signup"]; const PRIVATE_ROUTES = ["/course/*/edit",];
const NON_AUTHENTICATED_ROUTES = ["/login", "/register"];
export interface Auth { export interface Auth {
access_token: string; access_token: string;
isAuthenticated: boolean; isAuthenticated: boolean;
@ -15,6 +17,8 @@ export interface Auth {
const AuthProvider = ({ children }: any) => { const AuthProvider = ({ children }: any) => {
const router = useRouter(); const router = useRouter();
const pathname = usePathname();
const [auth, setAuth] = React.useState<Auth>({ access_token: "", isAuthenticated: false, userInfo: {}, isLoading: true }); const [auth, setAuth] = React.useState<Auth>({ access_token: "", isAuthenticated: false, userInfo: {}, isLoading: true });
async function checkRefreshToken() { async function checkRefreshToken() {
@ -24,6 +28,7 @@ const AuthProvider = ({ children }: any) => {
} }
} }
async function checkAuth() { async function checkAuth() {
try { try {
let access_token = await checkRefreshToken(); let access_token = await checkRefreshToken();
@ -34,13 +39,24 @@ const AuthProvider = ({ children }: any) => {
userInfo = await getUserInfo(access_token); userInfo = await getUserInfo(access_token);
setAuth({ access_token, isAuthenticated: true, userInfo, isLoading }); setAuth({ access_token, isAuthenticated: true, userInfo, isLoading });
// Redirect to home if user is trying to access a NON_AUTHENTICATED_ROUTES route
if (NON_AUTHENTICATED_ROUTES.some((route) => new RegExp(`^${route.replace("*", ".*")}$`).test(pathname))) {
router.push("/");
}
} else { } else {
setAuth({ access_token, isAuthenticated: false, userInfo, isLoading }); setAuth({ access_token, isAuthenticated: false, userInfo, isLoading });
//router.push("/login");
// Redirect to login if user is trying to access a private route
if (PRIVATE_ROUTES.some((route) => new RegExp(`^${route.replace("*", ".*")}$`).test(pathname))) {
router.push("/login");
}
} }
} catch (error) { } catch (error) {
router.push("/");
} }
} }

View file

@ -9,29 +9,6 @@ from fastapi.responses import JSONResponse
router = APIRouter() router = APIRouter()
# DEPRECATED
@router.post("/token", response_model=Token)
async def login_for_access_token(request: Request, form_data: OAuth2PasswordRequestForm = Depends()):
"""
OAuth2 compatible token login, get access token for future requests
"""
user = await authenticate_user(request, form_data.username, form_data.password)
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect Email or password",
headers={"WWW-Authenticate": "Bearer"},
)
access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
access_token = create_access_token(
data={"sub": user.username}, expires_delta=access_token_expires
)
response = JSONResponse(content={"access_token" : access_token ,"token_type": "bearer"})
response.set_cookie(key="user_token", value=access_token, httponly=True, expires=3600,secure=True)
return response
@router.post('/refresh') @router.post('/refresh')
def refresh(Authorize: AuthJWT = Depends()): def refresh(Authorize: AuthJWT = Depends()):
""" """