API bug fixed, register flow worksgit add .

This commit is contained in:
Mikayla Dobson
2023-02-12 11:33:33 -06:00
parent 1b73fa6b99
commit 532a713295
7 changed files with 64 additions and 33 deletions

View File

@@ -21,21 +21,27 @@ import GroceryList from './components/pages/GroceryList';
import GroceryListCollection from './components/pages/GroceryListCollection'; import GroceryListCollection from './components/pages/GroceryListCollection';
import { TokenType } from './util/types'; import { TokenType } from './util/types';
import './sass/App.scss'; import './sass/App.scss';
import handleToken from './util/handleToken';
function App() { function App() {
const { setUser, token, setToken } = useAuthContext(); const { setUser, token, setToken } = useAuthContext();
useEffect(() => { useEffect(() => {
if (document.cookie) { if (document.cookie) {
const extractedToken: Partial<TokenType> = jwtDecode(document.cookie.split("=")[1]); const response = handleToken();
setToken(document.cookie.split("=")[1]); if (response) {
setUser(extractedToken.user); setToken(response.token);
setUser(response.user);
}
} }
}, [document.cookie]); }, [document.cookie]);
useEffect(() => { useEffect(() => {
token && API.Settings.setToken(token); if (token) {
}, [token]) const response = handleToken();
response && setUser(response.user);
}
}, [setToken])
return ( return (
<BrowserRouter> <BrowserRouter>

View File

@@ -9,15 +9,16 @@ import TextField from "../../ui/TextField";
import { useAuthContext } from "../../../context/AuthContext"; import { useAuthContext } from "../../../context/AuthContext";
const InitialCollection: RegisterVariantType = ({ transitionDisplay, input }) => { const InitialCollection: RegisterVariantType = ({ transitionDisplay, input }) => {
const { user, setUser } = useAuthContext(); const { user, token } = useAuthContext();
const [collectionName, setCollectionName] = useState<string>(); const [collectionName, setCollectionName] = useState<string>();
const [view, setView] = useState<JSX.Element>(<Page><h1>Loading...</h1></Page>); const [view, setView] = useState<JSX.Element>(<Page><h1>Loading...</h1></Page>);
const now = useNow(); const now = useNow();
const collectionAPI = new API.Collection();
const handleClick = async () => { const handleClick = async () => {
if (!user) return; if (!user || !token) return;
const collectionAPI = new API.Collection(token);
const collection: ICollection = { const collection: ICollection = {
name: collectionName ?? (user.firstname + "'s Collection"), name: collectionName ?? (user.firstname + "'s Collection"),
active: true, active: true,
@@ -35,7 +36,7 @@ const InitialCollection: RegisterVariantType = ({ transitionDisplay, input }) =>
} }
useEffect(() => { useEffect(() => {
if (user) { if (user && token) {
setView( setView(
<Page> <Page>
<h1>Hi, {user.firstname}! Great to meet you.</h1> <h1>Hi, {user.firstname}! Great to meet you.</h1>

View File

@@ -4,14 +4,15 @@ import { TextField, UserCard } from "..";
import { v4 } from "uuid"; import { v4 } from "uuid";
import { getAllUsers } from "../../../util/apiUtils"; import { getAllUsers } from "../../../util/apiUtils";
import API from "../../../util/API"; import API from "../../../util/API";
import { useAuthContext } from "../../../context/AuthContext";
const FriendSearchWidget: FC<{}> = () => { const FriendSearchWidget: FC<{}> = () => {
const { token } = useAuthContext();
const [searchTerm, setSearchTerm] = useState<string>(); const [searchTerm, setSearchTerm] = useState<string>();
const [userPool, setUserPool] = useState<IUser[]>([]); const [userPool, setUserPool] = useState<IUser[]>([]);
const [friendResults, setFriendResults] = useState<IUser[]>([]); const [friendResults, setFriendResults] = useState<IUser[]>([]);
const users = new API.User();
// this isn't really working right now i don't think // this isn't really working right now i don't think
const handleRequestSent = useCallback((targetid: string | number) => { const handleRequestSent = useCallback((targetid: string | number) => {
setUserPool((prev: IUser[]) => { setUserPool((prev: IUser[]) => {
@@ -26,6 +27,9 @@ const FriendSearchWidget: FC<{}> = () => {
// load available user pool on mount // load available user pool on mount
useEffect(() => { useEffect(() => {
(async function() { (async function() {
if (!token) return;
const users = new API.User(token);
const result = await users.getAll(); const result = await users.getAll();
if (result) setUserPool(result); if (result) setUserPool(result);
})(); })();

View File

@@ -2,9 +2,9 @@ import { createContext, Dispatch, SetStateAction, useContext } from "react";
import { IUser } from "../schemas"; import { IUser } from "../schemas";
export interface IAuthContext { export interface IAuthContext {
user?: IUser user: IUser | undefined
setUser: Dispatch<SetStateAction<IUser | undefined>> | VoidFunction setUser: Dispatch<SetStateAction<IUser | undefined>> | VoidFunction
token?: string token: string | undefined
setToken: Dispatch<SetStateAction<string | undefined>> | VoidFunction setToken: Dispatch<SetStateAction<string | undefined>> | VoidFunction
} }

View File

@@ -25,15 +25,14 @@ module API {
protected endpoint: string; protected endpoint: string;
protected headers?: any protected headers?: any
constructor(endpoint: string) { constructor(endpoint: string, token: string) {
this.endpoint = endpoint; this.endpoint = endpoint;
this.headers = {
if (Settings.getToken()) { headers: {
this.headers = {
"Content-Type": "application/json", "Content-Type": "application/json",
"Authorization": ("Bearer " + Settings.getToken()) "Authorization": ("Bearer " + token)
}; }
} };
} }
async getAll() { async getAll() {
@@ -112,14 +111,14 @@ module API {
} }
export class User extends RestController<IUser> { export class User extends RestController<IUser> {
constructor() { constructor(token: string) {
super(Settings.getAPISTRING() + "/app/users"); super(Settings.getAPISTRING() + "/app/users", token);
} }
} }
export class Friendship extends RestController<IFriendship> { export class Friendship extends RestController<IFriendship> {
constructor() { constructor(token: string) {
super(Settings.getAPISTRING() + "/app/friends"); super(Settings.getAPISTRING() + "/app/friends", token);
} }
async getPendingFriendRequests() { async getPendingFriendRequests() {
@@ -129,26 +128,27 @@ module API {
} }
export class Recipe extends RestController<IRecipe> { export class Recipe extends RestController<IRecipe> {
constructor() { constructor(token: string) {
super(Settings.getAPISTRING() + "/app/recipes"); super(Settings.getAPISTRING() + "/app/recipes", token);
} }
} }
export class Ingredient extends RestController<IIngredient> { export class Ingredient extends RestController<IIngredient> {
constructor() { constructor(token: string) {
super(Settings.getAPISTRING() + "/app/ingredients"); if (!token) throw new Error("Missing required token");
super(Settings.getAPISTRING() + "/app/ingredients", token);
} }
} }
export class Collection extends RestController<ICollection> { export class Collection extends RestController<ICollection> {
constructor() { constructor(token: string) {
super(Settings.getAPISTRING() + "/app/collection"); super(Settings.getAPISTRING() + "/app/collection", token);
} }
} }
export class GroceryList extends RestController<IGroceryList> { export class GroceryList extends RestController<IGroceryList> {
constructor() { constructor(token: string) {
super(Settings.getAPISTRING() + "/app/grocery-list") super(Settings.getAPISTRING() + "/app/grocery-list", token)
} }
} }
} }

View File

@@ -0,0 +1,19 @@
import jwtDecode from "jwt-decode";
import { IUser } from "../schemas";
import { TokenType } from "./types";
export default function handleToken(): { token: string, user: IUser } | null {
try {
const extractedToken: Partial<TokenType> = jwtDecode(document.cookie.split("=")[1]);
if (extractedToken) {
return {
token: document.cookie.split("=")[1],
user: extractedToken.user as IUser
}
}
} catch(e: any) {
console.log(e.message);
}
return null;
}

View File

@@ -21,6 +21,7 @@ export const routes = async (app: Express) => {
// middleware to check for auth on cookies on each request in protected routes // middleware to check for auth on cookies on each request in protected routes
app.use('/app', async (req, res, next) => { app.use('/app', async (req, res, next) => {
// pull jwt from request headers // pull jwt from request headers
console.log(req.headers);
const token = req.headers['authorization']?.split(" ")[1]; const token = req.headers['authorization']?.split(" ")[1];
console.log(token); console.log(token);