diff --git a/api/__debug_bin2117125024 b/api/__debug_bin2117125024 deleted file mode 100755 index 62baac2..0000000 Binary files a/api/__debug_bin2117125024 and /dev/null differ diff --git a/api/auth/middleware/authentication_middleware.go b/api/auth/middleware/authentication_middleware.go index 2b1544f..ae16613 100644 --- a/api/auth/middleware/authentication_middleware.go +++ b/api/auth/middleware/authentication_middleware.go @@ -3,7 +3,6 @@ package middleware import ( "bytes" "encoding/json" - "io" "log" "net/http" "net/url" @@ -44,7 +43,7 @@ func TokenIsNotExpired(access_token string) bool { func GetUserProfile(context *gin.Context) { session := sessions.Default(context) - access_token := session.Get("access_token") + /* access_token := session.Get("access_token") user_profile_client := http.Client{} user_profile_url, err := url.Parse("https://" + os.Getenv("AUTH0_DOMAIN") + os.Getenv("AUTH0_USER_INFO_ENDPOINT")) @@ -71,10 +70,15 @@ func GetUserProfile(context *gin.Context) { } defer user_profile_response.Body.Close() - user_profile_bytes, _ := io.ReadAll(user_profile_response.Body) - + user_profile_bytes, _ := io.ReadAll(user_profile_response.Body) */ var user_profile dto.UserProfileResponse - json.Unmarshal(user_profile_bytes, &user_profile) + profile_session := session.Get("profile").(map[string]interface{}) + user_profile.Sub = profile_session["sub"].(string) + user_profile.Email = profile_session["email"].(string) + user_profile.Verified = profile_session["email_verified"].(bool) + user_profile.PictureUrl = profile_session["picture"].(string) + user_profile.Nickname = profile_session["nickname"].(string) + user_profile.Updated_at = profile_session["updated_at"].(string) context.Set("user_profile", user_profile) context.Next() } diff --git a/api/controllers/userController.go b/api/controllers/userController.go index 0843375..c3d4291 100644 --- a/api/controllers/userController.go +++ b/api/controllers/userController.go @@ -181,6 +181,8 @@ func GetCurrentAuthenticatedUser(pool *pgxpool.Pool) gin.HandlerFunc { user_profile, _ := ctx.Get("user_profile") + log.Printf("%s", user_profile.(dto.UserProfileResponse).Sub) + sub_id := user_profile.(dto.UserProfileResponse).Sub var user dto.UserResponse diff --git a/api/dto/user_response.go b/api/dto/user_response.go index 86b2227..10562d9 100644 --- a/api/dto/user_response.go +++ b/api/dto/user_response.go @@ -3,9 +3,9 @@ package dto // User response for exposing to the front-end // :3 type UserResponse struct { - Id int `json: "id"` - Name string `json: "name"` - JobPosition string `json: "job_position"` - Active bool `json: "active"` - Admin bool `json: "admin"` + Id int + Name string + JobPosition string + Active bool + Admin bool } diff --git a/api/go.mod b/api/go.mod index 72d9cb6..533a776 100644 --- a/api/go.mod +++ b/api/go.mod @@ -64,6 +64,7 @@ require ( github.com/mattn/go-colorable v0.1.13 // indirect github.com/mattn/go-isatty v0.0.20 // indirect github.com/mattn/go-runewidth v0.0.13 // indirect + github.com/mitchellh/mapstructure v1.5.0 github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect github.com/pelletier/go-toml/v2 v2.2.4 // indirect diff --git a/api/go.sum b/api/go.sum index b6974e2..b738932 100644 --- a/api/go.sum +++ b/api/go.sum @@ -135,6 +135,8 @@ github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D github.com/mattn/go-runewidth v0.0.3/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= github.com/mattn/go-runewidth v0.0.13 h1:lTGmDsbAYt5DmK6OnoV7EuIF1wEIFAcxld6ypU4OSgU= github.com/mattn/go-runewidth v0.0.13/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= +github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= +github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= diff --git a/api/main.go b/api/main.go index d8f3649..2492874 100644 --- a/api/main.go +++ b/api/main.go @@ -99,6 +99,7 @@ func main() { router.GET("/item/history", corsmiddleware.CORSMiddleware, user_authenticated, middleware.GetUserProfile, user_in_db, user_active, user_is_admin, controllers.GetItemHistory(pool)) router.POST("/position/create", corsmiddleware.CORSMiddleware, user_authenticated, middleware.GetUserProfile, user_in_db, user_active, user_is_admin, controllers.CreatePosition(pool)) router.POST("/item/create", corsmiddleware.CORSMiddleware, user_authenticated, middleware.GetUserProfile, user_in_db, user_active, user_is_admin, controllers.CreateItem(pool)) + router.OPTIONS("/item/create", corsmiddleware.CORSMiddleware) router.POST("/order/create", corsmiddleware.CORSMiddleware, user_authenticated, middleware.GetUserProfile, user_in_db, user_active, controllers.CreateOrder(pool)) router.OPTIONS("/order/create", corsmiddleware.CORSMiddleware) diff --git a/api/queries/UserQueries.go b/api/queries/UserQueries.go index 60e5470..841c512 100644 --- a/api/queries/UserQueries.go +++ b/api/queries/UserQueries.go @@ -54,7 +54,8 @@ FROM ordr_user LEFT JOIN ordr_position ON job_position = ordr_position.id - AND ordr_user.sub_id = $1; +WHERE + ordr_user.sub_id = $1; ` const USER_SET_POSITION string = ` diff --git a/ordr-ui/app/client/controllers/ItemController.ts b/ordr-ui/app/client/controllers/ItemController.ts index fd271b1..5083ec7 100644 --- a/ordr-ui/app/client/controllers/ItemController.ts +++ b/ordr-ui/app/client/controllers/ItemController.ts @@ -20,10 +20,7 @@ export const CreateItem = async (query: CreateItemQuery): Promise { return response; }, async error => { - if (error.response.status === 401) { + if (error.response?.status === 401) { const resp = await axios.get(process.env.NEXT_PUBLIC_API_URL + "/auth/login", {withCredentials: true}) window.location.href = resp.data.Location } diff --git a/ordr-ui/app/client/controllers/UserController.ts b/ordr-ui/app/client/controllers/UserController.ts index c2ba30f..9768680 100644 --- a/ordr-ui/app/client/controllers/UserController.ts +++ b/ordr-ui/app/client/controllers/UserController.ts @@ -9,12 +9,10 @@ export const GetCurrentUser = async (): Promise => { console.log(process.env.NEXT_PUBLIC_API_URL + "/user/current") const res = await axios.get(process.env.NEXT_PUBLIC_API_URL + "/user/current", { maxRedirects: 0, + withCredentials: true, validateStatus: (status) => { return status >= 200 && status < 400 }}); - if(res.data.Location) { - window.location.href = res.data.Location - } return res.data; }; diff --git a/ordr-ui/app/components/ItemTableListRow.tsx b/ordr-ui/app/components/ItemTableListRow.tsx index 85296d9..c8142e4 100644 --- a/ordr-ui/app/components/ItemTableListRow.tsx +++ b/ordr-ui/app/components/ItemTableListRow.tsx @@ -5,6 +5,8 @@ import { ItemHistoryTable } from "./ItemHistoryTable" import useAsyncEffect from "use-async-effect" import { useItemStore } from "../providers/ItemsProvider" import { Mutex } from "async-mutex" +import { useCurrentAuthenticatedUserStore } from "../providers" +import { useShallow } from "zustand/shallow" type ItemTableListRowProps = { item: ItemPriceResponse @@ -56,15 +58,25 @@ export const ItemTableListRow = ({item}: ItemTableListRowProps) => { const [shouldPushNewItemPrice, setShouldPushNewItemPrice] = useState(false) + const authUserStore = useCurrentAuthenticatedUserStore(useShallow((state) => state)) + useAsyncEffect(async () => { - if(shouldPushNewItemPrice) + if(shouldPushNewItemPrice && authUserStore.Admin) { const release = await itemTableListRowMutex.acquire() setShouldPushNewItemPrice(false) await itemStore.setItemPrice(item.ItemId, newItemPrice) await release() } - }, [shouldPushNewItemPrice]) + }, [shouldPushNewItemPrice, authUserStore]) + + useAsyncEffect(async () => { + if (authUserStore.Id === -1) { + const release = await itemTableListRowMutex.acquire() + await authUserStore.sync() + await release() + } + }, [authUserStore]) return (
  • @@ -79,7 +91,7 @@ export const ItemTableListRow = ({item}: ItemTableListRowProps) => { price: {Math.trunc(item.ItemPrice * 100) / 100} - {shouldShowDetails && ( + {shouldShowDetails && authUserStore.Admin && ( <>

    Set Item Price

    diff --git a/ordr-ui/app/components/NavBar.tsx b/ordr-ui/app/components/NavBar.tsx index 3ce7c53..2383013 100644 --- a/ordr-ui/app/components/NavBar.tsx +++ b/ordr-ui/app/components/NavBar.tsx @@ -1,11 +1,29 @@ +'use client' import Link from "next/link" +import { useCurrentAuthenticatedUserStore } from "../providers" +import useAsyncEffect from "use-async-effect" +import { Mutex } from "async-mutex" +import { useShallow } from "zustand/shallow" + +const navBarMutex = new Mutex() export const NavBar = () => { + + const authUserStore = useCurrentAuthenticatedUserStore(useShallow((state) => state)) + + useAsyncEffect(async () => { + if(authUserStore.Id === -1) { + const release = await navBarMutex.acquire() + await authUserStore.sync() + await release() + } + }, [authUserStore]) + return ( diff --git a/ordr-ui/app/components/OrderItemTable.tsx b/ordr-ui/app/components/OrderItemTable.tsx index f4a6eb4..c80df0d 100644 --- a/ordr-ui/app/components/OrderItemTable.tsx +++ b/ordr-ui/app/components/OrderItemTable.tsx @@ -1,3 +1,4 @@ +'for client' import { useItemStore } from "../providers/ItemsProvider" import { useState } from "react" import useAsyncEffect from "use-async-effect" diff --git a/ordr-ui/app/components/OrderTableList.tsx b/ordr-ui/app/components/OrderTableList.tsx index b003ea7..6158910 100644 --- a/ordr-ui/app/components/OrderTableList.tsx +++ b/ordr-ui/app/components/OrderTableList.tsx @@ -2,9 +2,9 @@ import { useOrderStore } from "../providers/OrderProvider" import { useShallow } from "zustand/shallow" import useAsyncEffect from "use-async-effect" -import { OrderTableRow } from "./OrderTableRow" import { Mutex } from "async-mutex" import styled from "styled-components" +import { OrderTableRow } from "./OrderTableRow" type OrderTableProps = { page: number, diff --git a/ordr-ui/app/components/OrderTableRow.tsx b/ordr-ui/app/components/OrderTableRow.tsx index 3845d52..160a5e3 100644 --- a/ordr-ui/app/components/OrderTableRow.tsx +++ b/ordr-ui/app/components/OrderTableRow.tsx @@ -1,3 +1,4 @@ +'for client' import { useState } from "react" import styled from "styled-components" import { OrderItemTable } from "./OrderItemTable" diff --git a/ordr-ui/app/components/UserTable.tsx b/ordr-ui/app/components/UserTable.tsx index fa51f6d..cf65e23 100644 --- a/ordr-ui/app/components/UserTable.tsx +++ b/ordr-ui/app/components/UserTable.tsx @@ -4,6 +4,8 @@ import { useUserStore } from "../providers/UsersProvider" import useAsyncEffect from "use-async-effect" import styled from "styled-components" import { useRef, useState } from "react" +import { useCurrentAuthenticatedUserStore } from "../providers" +import { Mutex } from "async-mutex" type UserTableProps = { page: number @@ -35,6 +37,8 @@ const UserTableRow = styled.tr` ` +const userTableMutex = new Mutex() + export const UserTable = ({page}: UserTableProps) => { const userStore = useUserStore(useShallow((state) => ({ @@ -43,47 +47,59 @@ export const UserTable = ({page}: UserTableProps) => { console.log(page) const [callLock, setCallLock] = useState(false) - + const authUserStore = useCurrentAuthenticatedUserStore(useShallow((state) => state)) + console.log(authUserStore) const callLockRef = useRef(callLock) useAsyncEffect(async () => { - if(!callLockRef.current) { + if(!callLockRef.current && authUserStore.Admin) { callLockRef.current = true setCallLock(true) await userStore.sync(page) callLockRef.current = false setCallLock(false) } - }, [page]) + }, [page, authUserStore.Id, authUserStore.Name]) + + useAsyncEffect(async () => { + if(authUserStore.Id === -1) { + const release = await userTableMutex.acquire() + await authUserStore.sync() + console.log(authUserStore) + await release() + } + }, [authUserStore.Id]) console.log(userStore.tableUsers) - return ( - - - id - name - position - active - admin - - - {userStore.tableUsers.map((u) => ( - - {u.Id} - {u.Name} - {u.JobPosition} - { - if(u.Active) - await userStore.deactivateUser(u.Id) - else - await userStore.activateUser(u.Id) - }}/> - { - if(u.Admin) - await userStore.demoteUser(u.Id) - else - await userStore.promoteUser(u.Id) - }}/> - ))} - - + return authUserStore.Admin && ( + + + + id + name + position + active + admin + + + + {userStore.tableUsers.map((u) => ( + + {u.Id} + {u.Name} + {u.JobPosition} + { + if(u.Active) + await userStore.deactivateUser(u.Id) + else + await userStore.activateUser(u.Id) + }} checked={u.Active}/> + { + if(u.Admin) + await userStore.demoteUser(u.Id) + else + await userStore.promoteUser(u.Id) + }} checked={u.Admin}/> + ))} + + ) } \ No newline at end of file diff --git a/ordr-ui/app/items/page.tsx b/ordr-ui/app/items/page.tsx index 6585d52..45456b9 100644 --- a/ordr-ui/app/items/page.tsx +++ b/ordr-ui/app/items/page.tsx @@ -1,10 +1,71 @@ 'use client' +import { useState } from "react" import { ItemTableList } from "../components/ItemTableList" +import useAsyncEffect from "use-async-effect" +import { Mutex } from "async-mutex" +import { useItemStore } from "../providers/ItemsProvider" +import { useCurrentAuthenticatedUserStore } from "../providers" +import { useShallow } from "zustand/shallow" + +const itemPageApiMutex = new Mutex() const Items = () => { + const [itemName, setItemName] = useState("") + const [itemPrice, setItemPrice] = useState(0) + const [inSeason, setInSeason] = useState(false) + const [shouldSubmitDetails, setShouldSubmitDetails] = useState(false) + + const itemStore = useItemStore((state) => state) + + const authUserStore = useCurrentAuthenticatedUserStore(useShallow((state) => state)) + + useAsyncEffect(async () => { + if(shouldSubmitDetails && authUserStore.Admin) + { + setShouldSubmitDetails(false) + const release = await itemPageApiMutex.acquire() + await itemStore.createItem(itemName, inSeason, itemPrice) + + await release() + } + }, [shouldSubmitDetails]) + + useAsyncEffect(async () => { + if(authUserStore.Id === -1) { + const release = await itemPageApiMutex.acquire() + await authUserStore.sync() + await release() + } + }, [authUserStore]) + + return ( - + <> + + {authUserStore.Admin && + <> +

    Create Item

    + { + setItemName(e.currentTarget.value) + }}/> + { + const int_value = parseInt(e.currentTarget.value) + if(!Number.isNaN(int_value)) + setItemPrice(int_value) + }}/> + In Season + { + setInSeason(e.target.checked) + }} /> +
    + + + } + + ) } diff --git a/ordr-ui/app/providers/AuthenticationProvider.ts b/ordr-ui/app/providers/AuthenticationProvider.ts index 99b3089..3861b93 100644 --- a/ordr-ui/app/providers/AuthenticationProvider.ts +++ b/ordr-ui/app/providers/AuthenticationProvider.ts @@ -16,8 +16,8 @@ export const useCurrentAuthenticatedUserStore = create { const authUser = await GetCurrentUser() set((state) => ({ - ...authUser, - ...state + ...state, + ...authUser })) return authUser },