diff --git a/components/CharacterGrid/index.tsx b/components/CharacterGrid/index.tsx index b97218da..bed247ca 100644 --- a/components/CharacterGrid/index.tsx +++ b/components/CharacterGrid/index.tsx @@ -23,6 +23,7 @@ import './index.scss' // Props interface Props { new: boolean + editable: boolean characters?: GridCharacter[] createParty: (details?: DetailsObject) => Promise pushHistory?: (path: string) => void @@ -75,17 +76,6 @@ const CharacterGrid = (props: Props) => { [key: number]: number | undefined }>({}) - // Set the editable flag only on first load - useEffect(() => { - // If user is logged in and matches - if ( - (accountData && party.user && accountData.userId === party.user.id) || - props.new - ) - appState.party.editable = true - else appState.party.editable = false - }, [props.new, accountData, party]) - useEffect(() => { setJob(appState.party.job) setJobSkills(appState.party.jobSkills) @@ -115,7 +105,7 @@ const CharacterGrid = (props: Props) => { .catch((error) => console.error(error)) }) } else { - if (party.editable) + if (props.editable) saveCharacter(party.id, character, position) .then((response) => handleCharacterResponse(response.data)) .catch((error) => { @@ -232,7 +222,7 @@ const CharacterGrid = (props: Props) => { } function saveJobSkill(skill: JobSkill, position: number) { - if (party.id && appState.party.editable) { + if (party.id && props.editable) { const positionedKey = `skill${position}_id` let skillObject: { @@ -522,7 +512,7 @@ const CharacterGrid = (props: Props) => { job={job} jobSkills={jobSkills} jobAccessory={jobAccessory} - editable={party.editable} + editable={props.editable} saveJob={saveJob} saveSkill={saveJobSkill} saveAccessory={saveAccessory} @@ -541,7 +531,7 @@ const CharacterGrid = (props: Props) => {
  • { setCookie('account', cookieObj, { path: '/', expires: expiresAt }) // Set Axios default headers - setUserToken() + setHeaders() } function storeUserInfo(response: AxiosResponse) { diff --git a/components/Party/index.tsx b/components/Party/index.tsx index e935947c..347bc49e 100644 --- a/components/Party/index.tsx +++ b/components/Party/index.tsx @@ -1,7 +1,9 @@ import React, { useEffect, useState } from 'react' +import { getCookie } from 'cookies-next' import { useRouter } from 'next/router' import { useSnapshot } from 'valtio' import clonedeep from 'lodash.clonedeep' +import ls from 'local-storage' import PartySegmentedControl from '~components/PartySegmentedControl' import PartyDetails from '~components/PartyDetails' @@ -13,6 +15,8 @@ import api from '~utils/api' import { appState, initialAppState } from '~utils/appState' import { GridType } from '~utils/enums' import { retrieveCookies } from '~utils/retrieveCookies' +import { accountCookie, setEditKey, unsetEditKey } from '~utils/userToken' + import type { DetailsObject } from '~types' import './index.scss' @@ -36,6 +40,7 @@ const Party = (props: Props) => { // Set up states const { party } = useSnapshot(appState) + const [editable, setEditable] = useState(false) const [currentTab, setCurrentTab] = useState(GridType.Weapon) // Retrieve cookies @@ -48,6 +53,41 @@ const Party = (props: Props) => { if (props.team) storeParty(props.team) }, []) + // Set editable on first load + useEffect(() => { + // Get cookie + const cookie = getCookie('account') + const accountData: AccountCookie = cookie + ? JSON.parse(cookie as string) + : null + + let editable = false + unsetEditKey() + + if (props.new) editable = true + + if (accountData && props.team && !props.new) { + if (accountData.token) { + // Authenticated + if (props.team.user && accountData.userId === props.team.user.id) { + editable = true + } + } else { + // Not authenticated + if (!props.team.user && accountData.userId === props.team.local_id) { + // Set editable + editable = true + + // Also set edit key header + setEditKey(props.team.id, props.team.user) + } + } + } + + appState.party.editable = editable + setEditable(editable) + }) + // Set selected tab from props useEffect(() => { setCurrentTab(props.selectedTab) @@ -59,13 +99,13 @@ const Party = (props: Props) => { if (details) payload = formatDetailsObject(details) return await api.endpoints.parties - .create(payload) + .create({ ...payload, ...localId() }) .then((response) => storeParty(response.data.party)) } // Methods: Updating the party's details async function updateDetails(details: DetailsObject) { - if (!appState.party.id) return await createParty(details) + if (!props.team) return await createParty(details) else updateParty(details) } @@ -92,9 +132,9 @@ const Party = (props: Props) => { async function updateParty(details: DetailsObject) { const payload = formatDetailsObject(details) - if (appState.party.id) { + if (props.team && props.team.id) { return await api.endpoints.parties - .update(appState.party.id, payload) + .update(props.team.id, payload) .then((response) => storeParty(response.data.party)) } } @@ -103,8 +143,8 @@ const Party = (props: Props) => { appState.party.extra = event.target.checked // Only save if this is a saved party - if (appState.party.id) { - api.endpoints.parties.update(appState.party.id, { + if (props.team && props.team.id) { + api.endpoints.parties.update(props.team.id, { party: { extra: event.target.checked }, }) } @@ -112,9 +152,9 @@ const Party = (props: Props) => { // Deleting the party function deleteTeam() { - if (appState.party.editable && appState.party.id) { + if (props.team && editable) { api.endpoints.parties - .destroy({ id: appState.party.id }) + .destroy({ id: props.team.id }) .then(() => { // Push to route if (cookies && cookies.account.username) { @@ -139,7 +179,7 @@ const Party = (props: Props) => { } // Methods: Storing party data - const storeParty = function (team: Party) { + const storeParty = function (team: any) { // Store the important party and state-keeping values in global state appState.party.name = team.name appState.party.description = team.description @@ -162,6 +202,12 @@ const Party = (props: Props) => { appState.party.detailsVisible = false + // Store the edit key in local storage + if (team.edit_key) { + storeEditKey(team.id, team.edit_key) + setEditKey(team.id, team.user) + } + // Populate state storeCharacters(team.characters) storeWeapons(team.weapons) @@ -183,6 +229,10 @@ const Party = (props: Props) => { return team } + const storeEditKey = (id: string, key: string) => { + ls(id, key) + } + const storeCharacters = (list: Array) => { list.forEach((object: GridCharacter) => { if (object.position != null) @@ -240,6 +290,15 @@ const Party = (props: Props) => { } } + // Methods: Unauth validation + function localId() { + const cookie = accountCookie() + const parsed = JSON.parse(cookie as string) + if (parsed && !parsed.token) { + return { local_id: parsed.userId } + } else return {} + } + // Render: JSX components const navigation = ( { const weaponGrid = ( { const summonGrid = ( { const characterGrid = ( { setCookie('account', cookieObj, { path: '/', expires: expiresAt }) // Set Axios default headers - setUserToken() + setHeaders() } function fetchUserInfo(id: string) { diff --git a/components/SummonGrid/index.tsx b/components/SummonGrid/index.tsx index 1263658b..94139df2 100644 --- a/components/SummonGrid/index.tsx +++ b/components/SummonGrid/index.tsx @@ -21,6 +21,7 @@ import './index.scss' // Props interface Props { new: boolean + editable: boolean summons?: GridSummon[] createParty: (details?: DetailsObject) => Promise pushHistory?: (path: string) => void @@ -55,17 +56,6 @@ const SummonGrid = (props: Props) => { [key: number]: number }>({}) - // Set the editable flag only on first load - useEffect(() => { - // If user is logged in and matches - if ( - (accountData && party.user && accountData.userId === party.user.id) || - props.new - ) - appState.party.editable = true - else appState.party.editable = false - }, [props.new, accountData, party]) - // Initialize an array of current uncap values for each summon useEffect(() => { let initialPreviousUncapValues: { [key: number]: number } = {} @@ -100,7 +90,7 @@ const SummonGrid = (props: Props) => { ) }) } else { - if (party.editable) + if (props.editable) saveSummon(party.id, summon, position) .then((response) => handleSummonResponse(response.data)) .catch((error) => { @@ -401,7 +391,7 @@ const SummonGrid = (props: Props) => {
    {t('summons.main')}
    {
    {t('summons.friend')}
    {
  • { const subAuraSummonElement = ( Promise pushHistory?: (path: string) => void @@ -60,17 +61,6 @@ const WeaponGrid = (props: Props) => { [key: number]: number }>({}) - // Set the editable flag only on first load - useEffect(() => { - // If user is logged in and matches - if ( - (accountData && party.user && accountData.userId === party.user.id) || - props.new - ) - appState.party.editable = true - else appState.party.editable = false - }, [props.new, accountData, party]) - // Initialize an array of current uncap values for each weapon useEffect(() => { let initialPreviousUncapValues: { [key: number]: number } = {} @@ -99,7 +89,7 @@ const WeaponGrid = (props: Props) => { }) }) } else { - if (party.editable) + if (props.editable) saveWeapon(party.id, weapon, position) .then((response) => { if (response) handleWeaponResponse(response.data) @@ -337,7 +327,7 @@ const WeaponGrid = (props: Props) => { const mainhandElement = ( {
  • { const extraGridElement = ( { // prettier-ignore export const getServerSideProps = async ({ req, res, locale, query }: { req: NextApiRequest, res: NextApiResponse, locale: string, query: { [index: string]: string } }) => { // Set headers for server-side requests - setUserToken(req, res) + setHeaders(req, res) // Fetch latest version const version = await fetchLatestVersion() diff --git a/pages/_app.tsx b/pages/_app.tsx index cfc1806f..d3455586 100644 --- a/pages/_app.tsx +++ b/pages/_app.tsx @@ -7,7 +7,7 @@ import type { AppProps } from 'next/app' import Layout from '~components/Layout' import { accountState } from '~utils/accountState' -import setUserToken from '~utils/setUserToken' +import { setHeaders } from '~utils/userToken' import '../styles/globals.scss' import { ToastProvider, Viewport } from '@radix-ui/react-toast' @@ -23,9 +23,8 @@ function MyApp({ Component, pageProps }: AppProps) { } useEffect(() => { - setUserToken() - - if (accountCookie) { + setHeaders() + if (cookieData.account && cookieData.account.token) { console.log(`Logged in as user "${cookieData.account.username}"`) accountState.account.authorized = true diff --git a/pages/about.tsx b/pages/about.tsx index 179e1d53..06258b18 100644 --- a/pages/about.tsx +++ b/pages/about.tsx @@ -6,7 +6,7 @@ import { useTranslation } from 'next-i18next' import { serverSideTranslations } from 'next-i18next/serverSideTranslations' import { AboutTabs } from '~utils/enums' -import setUserToken from '~utils/setUserToken' +import { setHeaders } from '~utils/userToken' import AboutPage from '~components/AboutPage' import UpdatesPage from '~components/UpdatesPage' @@ -160,7 +160,7 @@ export const getServerSidePaths = async () => { // prettier-ignore export const getServerSideProps = async ({ req, res, locale, query }: { req: NextApiRequest, res: NextApiResponse, locale: string, query: { [index: string]: string } }) => { // Set headers for server-side requests - setUserToken(req, res) + setHeaders(req, res) // Fetch and organize raids return { diff --git a/pages/new/index.tsx b/pages/new/index.tsx index e03a3cfa..5f3bd215 100644 --- a/pages/new/index.tsx +++ b/pages/new/index.tsx @@ -1,6 +1,7 @@ import React, { useEffect, useState } from 'react' import { useRouter } from 'next/router' import { serverSideTranslations } from 'next-i18next/serverSideTranslations' +import { v4 as uuidv4 } from 'uuid' import clonedeep from 'lodash.clonedeep' import ErrorSection from '~components/ErrorSection' @@ -10,7 +11,7 @@ import NewHead from '~components/NewHead' import api from '~utils/api' import fetchLatestVersion from '~utils/fetchLatestVersion' import organizeRaids from '~utils/organizeRaids' -import setUserToken from '~utils/setUserToken' +import { accountCookie, setHeaders } from '~utils/userToken' import { appState, initialAppState } from '~utils/appState' import { groupWeaponKeys } from '~utils/groupWeaponKeys' @@ -18,6 +19,7 @@ import type { AxiosError } from 'axios' import type { NextApiRequest, NextApiResponse } from 'next' import type { PageContextObj, ResponseStatus } from '~types' import { GridType } from '~utils/enums' +import { setCookie } from 'cookies-next' interface Props { context?: PageContextObj @@ -119,8 +121,24 @@ export const getServerSidePaths = async () => { // prettier-ignore export const getServerSideProps = async ({ req, res, locale, query }: { req: NextApiRequest, res: NextApiResponse, locale: string, query: { [index: string]: string } }) => { - // Set headers for server-side requests - setUserToken(req, res) + // Set headers for API calls + setHeaders(req, res) + + // If there is no account entry in cookies, create a UUID and store it + if (!accountCookie(req, res)) { + const uuid = uuidv4() + const expiresAt = new Date() + expiresAt.setDate(expiresAt.getDate() + 60) + + const cookieObj = { + userId: uuid, + username: undefined, + token: undefined, + } + + const options = req && res ? { req, res } : {} + setCookie('account', cookieObj, { path: '/', expires: expiresAt, ...options }) + } // Fetch latest version const version = await fetchLatestVersion() diff --git a/pages/p/[party].tsx b/pages/p/[party].tsx index 3a85a1fc..1b22b046 100644 --- a/pages/p/[party].tsx +++ b/pages/p/[party].tsx @@ -10,7 +10,7 @@ import api from '~utils/api' import elementEmoji from '~utils/elementEmoji' import fetchLatestVersion from '~utils/fetchLatestVersion' import organizeRaids from '~utils/organizeRaids' -import setUserToken from '~utils/setUserToken' +import { setHeaders } from '~utils/userToken' import { appState } from '~utils/appState' import { groupWeaponKeys } from '~utils/groupWeaponKeys' @@ -108,7 +108,7 @@ export const getServerSidePaths = async () => { // prettier-ignore export const getServerSideProps = async ({ req, res, locale, query }: { req: NextApiRequest, res: NextApiResponse, locale: string, query: { [index: string]: string } }) => { // Set headers for server-side requests - setUserToken(req, res) + setHeaders(req, res) // Fetch latest version const version = await fetchLatestVersion() diff --git a/pages/saved.tsx b/pages/saved.tsx index 0328fb19..db375c10 100644 --- a/pages/saved.tsx +++ b/pages/saved.tsx @@ -7,7 +7,7 @@ import { serverSideTranslations } from 'next-i18next/serverSideTranslations' import clonedeep from 'lodash.clonedeep' import api from '~utils/api' -import setUserToken from '~utils/setUserToken' +import { setHeaders } from '~utils/userToken' import extractFilters from '~utils/extractFilters' import fetchLatestVersion from '~utils/fetchLatestVersion' import organizeRaids from '~utils/organizeRaids' @@ -363,7 +363,7 @@ export const getServerSidePaths = async () => { // prettier-ignore export const getServerSideProps = async ({ req, res, locale, query }: { req: NextApiRequest, res: NextApiResponse, locale: string, query: { [index: string]: string } }) => { // Set headers for server-side requests - setUserToken(req, res) + setHeaders(req, res) // Fetch latest version const version = await fetchLatestVersion() diff --git a/pages/teams.tsx b/pages/teams.tsx index 199cb1a3..6b875587 100644 --- a/pages/teams.tsx +++ b/pages/teams.tsx @@ -7,7 +7,7 @@ import { serverSideTranslations } from 'next-i18next/serverSideTranslations' import clonedeep from 'lodash.clonedeep' import api from '~utils/api' -import setUserToken from '~utils/setUserToken' +import { setHeaders } from '~utils/userToken' import extractFilters from '~utils/extractFilters' import fetchLatestVersion from '~utils/fetchLatestVersion' import organizeRaids from '~utils/organizeRaids' @@ -363,7 +363,7 @@ export const getServerSidePaths = async () => { // prettier-ignore export const getServerSideProps = async ({ req, res, locale, query }: { req: NextApiRequest, res: NextApiResponse, locale: string, query: { [index: string]: string } }) => { // Set headers for server-side requests - setUserToken(req, res) + setHeaders(req, res) // Fetch latest version const version = await fetchLatestVersion() diff --git a/types/Party.d.ts b/types/Party.d.ts index eebea134..3a41e705 100644 --- a/types/Party.d.ts +++ b/types/Party.d.ts @@ -29,6 +29,7 @@ interface Party { weapons: Array summons: Array user: User + local_id?: string remix: boolean remixes: Party[] created_at: string diff --git a/utils/setUserToken.tsx b/utils/setUserToken.tsx deleted file mode 100644 index 004a2bc6..00000000 --- a/utils/setUserToken.tsx +++ /dev/null @@ -1,19 +0,0 @@ -import axios from 'axios' -import { getCookie } from 'cookies-next' -import type { NextApiRequest, NextApiResponse } from 'next' - -export default ( - req: NextApiRequest | undefined = undefined, - res: NextApiResponse | undefined = undefined -) => { - // Set up cookies - const options = req && res ? { req, res } : {} - const cookie = getCookie('account', options) - if (cookie) { - axios.defaults.headers.common['Authorization'] = `Bearer ${ - JSON.parse(cookie as string).token - }` - } else { - delete axios.defaults.headers.common['Authorization'] - } -} diff --git a/utils/userToken.tsx b/utils/userToken.tsx new file mode 100644 index 00000000..08563bda --- /dev/null +++ b/utils/userToken.tsx @@ -0,0 +1,40 @@ +import axios from 'axios' +import ls, { get, set } from 'local-storage' +import { getCookie } from 'cookies-next' +import type { NextApiRequest, NextApiResponse } from 'next' + +export const accountCookie = ( + req: NextApiRequest | undefined = undefined, + res: NextApiResponse | undefined = undefined +) => { + const options = req && res ? { req, res } : {} + const cookie = getCookie('account', options) + return cookie ? cookie : undefined +} + +export const setHeaders = ( + req: NextApiRequest | undefined = undefined, + res: NextApiResponse | undefined = undefined +) => { + const cookie = accountCookie(req, res) + if (cookie) { + const parsed = JSON.parse(cookie as string) + if (parsed.token) + axios.defaults.headers.common['Authorization'] = `Bearer ${parsed.token}` + } else { + delete axios.defaults.headers.common['Authorization'] + } +} + +export const setEditKey = (id: string, user?: User) => { + if (!user) { + const edit_key = get(id) + axios.defaults.headers.common['X-Edit-Key'] = edit_key + } else { + unsetEditKey() + } +} + +export const unsetEditKey = () => { + delete axios.defaults.headers.common['X-Edit-Key'] +}