Merge pull request #229 from jedmund/fix-login-editable

Fix issues with auth and editable state
This commit is contained in:
Justin Edmund 2023-02-03 19:44:30 -08:00 committed by GitHub
commit 260b92107b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 96 additions and 29 deletions

View file

@ -10,6 +10,7 @@ import Link from 'next/link'
import api from '~utils/api'
import { accountState, initialAccountState } from '~utils/accountState'
import { appState, initialAppState } from '~utils/appState'
import { getLocalId } from '~utils/localId'
import { retrieveLocaleCookies } from '~utils/retrieveCookies'
import {
@ -189,12 +190,16 @@ const Header = () => {
function remixTeam() {
setOriginalName(partySnapshot.name ? partySnapshot.name : t('no_title'))
if (partySnapshot.shortcode)
api.remix(partySnapshot.shortcode).then((response) => {
const remix = response.data.party
router.push(`/p/${remix.shortcode}`)
setRemixToastOpen(true)
})
if (partySnapshot.shortcode) {
const body = getLocalId()
api
.remix({ shortcode: partySnapshot.shortcode, body: body })
.then((response) => {
const remix = response.data.party
router.push(`/p/${remix.shortcode}`)
setRemixToastOpen(true)
})
}
}
function toggleFavorite() {

View file

@ -1,7 +1,7 @@
import React, { useEffect, useState } from 'react'
import { getCookie } from 'cookies-next'
import { useRouter } from 'next/router'
import { useSnapshot } from 'valtio'
import { subscribe, useSnapshot } from 'valtio'
import clonedeep from 'lodash.clonedeep'
import ls from 'local-storage'
@ -12,10 +12,12 @@ import SummonGrid from '~components/SummonGrid'
import CharacterGrid from '~components/CharacterGrid'
import api from '~utils/api'
import { accountState } from '~utils/accountState'
import { appState, initialAppState } from '~utils/appState'
import { getLocalId } from '~utils/localId'
import { GridType } from '~utils/enums'
import { retrieveCookies } from '~utils/retrieveCookies'
import { accountCookie, setEditKey, unsetEditKey } from '~utils/userToken'
import { setEditKey, unsetEditKey } from '~utils/userToken'
import type { DetailsObject } from '~types'
@ -42,6 +44,7 @@ const Party = (props: Props) => {
const { party } = useSnapshot(appState)
const [editable, setEditable] = useState(false)
const [currentTab, setCurrentTab] = useState<GridType>(GridType.Weapon)
const [refresh, setRefresh] = useState(false)
// Retrieve cookies
const cookies = retrieveCookies()
@ -53,6 +56,14 @@ const Party = (props: Props) => {
if (props.team) storeParty(props.team)
}, [])
// Subscribe to app state to listen for account changes and
// unsubscribe when component is unmounted
const unsubscribe = subscribe(accountState, () => {
setRefresh(true)
})
useEffect(() => () => unsubscribe(), [])
// Set editable on first load
useEffect(() => {
// Get cookie
@ -86,7 +97,7 @@ const Party = (props: Props) => {
appState.party.editable = editable
setEditable(editable)
})
}, [refresh])
// Set selected tab from props
useEffect(() => {
@ -99,7 +110,7 @@ const Party = (props: Props) => {
if (details) payload = formatDetailsObject(details)
return await api.endpoints.parties
.create({ ...payload, ...localId() })
.create({ ...payload, ...getLocalId() })
.then((response) => storeParty(response.data.party))
}
@ -290,15 +301,6 @@ 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 = (
<PartySegmentedControl

View file

@ -1,19 +1,34 @@
import { useEffect } from 'react'
import { getCookie } from 'cookies-next'
import { appWithTranslation } from 'next-i18next'
import { get } from 'local-storage'
import { getCookie, setCookie } from 'cookies-next'
import { subscribe } from 'valtio'
import { useEffect, useState } from 'react'
import { ThemeProvider } from 'next-themes'
import type { AppProps } from 'next/app'
import Layout from '~components/Layout'
import { accountState } from '~utils/accountState'
import { retrieveCookies } from '~utils/retrieveCookies'
import { setHeaders } from '~utils/userToken'
import '../styles/globals.scss'
import { ToastProvider, Viewport } from '@radix-ui/react-toast'
import { TooltipProvider } from '@radix-ui/react-tooltip'
import Layout from '~components/Layout'
import type { AppProps } from 'next/app'
import '../styles/globals.scss'
function MyApp({ Component, pageProps }: AppProps) {
const [refresh, setRefresh] = useState(false)
// Subscribe to app state to listen for account changes and
// unsubscribe when component is unmounted
const unsubscribe = subscribe(accountState, () => {
setRefresh(true)
})
useEffect(() => () => unsubscribe(), [])
const accountCookie = getCookie('account')
const userCookie = getCookie('user')
@ -42,9 +57,37 @@ function MyApp({ Component, pageProps }: AppProps) {
}
} else {
console.log(`You are not currently logged in.`)
setCookieFromLocalStorage()
}
}, [])
useEffect(() => {
setCookieFromLocalStorage()
}, [refresh])
function setCookieFromLocalStorage() {
const localUserId: string | null = get('userId')
const cookies = retrieveCookies()
if (
localUserId &&
(!cookies || (cookies && cookies.account && !cookies.account.token))
) {
const expiresAt = new Date()
expiresAt.setDate(expiresAt.getDate() + 60)
const cookieObj = {
userId: localUserId,
username: undefined,
token: undefined,
}
setCookie('account', cookieObj, {
path: '/',
expires: expiresAt,
})
}
}
return (
<ThemeProvider>
<ToastProvider swipeDirection="right">

View file

@ -1,6 +1,8 @@
import React, { useEffect, useState } from 'react'
import { useRouter } from 'next/router'
import { getCookie, setCookie } from 'cookies-next'
import { get, set } from 'local-storage'
import { serverSideTranslations } from 'next-i18next/serverSideTranslations'
import { useRouter } from 'next/router'
import { v4 as uuidv4 } from 'uuid'
import clonedeep from 'lodash.clonedeep'
@ -19,7 +21,6 @@ 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
@ -59,6 +60,13 @@ const NewRoute: React.FC<Props> = ({
}
}, [router.asPath])
// Persist generated userId in storage
useEffect(() => {
const cookie = getCookie('account')
const data: AccountCookie = JSON.parse(cookie as string)
if (!get('userId') && data && !data.token) set('userId', data.userId)
}, [])
useEffect(() => {
if (context && context.jobs && context.jobSkills) {
appState.raids = context.raids

View file

@ -120,9 +120,9 @@ class Api {
return axios.get(resourceUrl, params)
}
remix(shortcode: string, params?: {}) {
remix({ shortcode, body, params}: { shortcode: string, body?: {}, params?: {} }) {
const resourceUrl = `${this.url}/parties/${shortcode}/remix`
return axios.post(resourceUrl, params)
return axios.post(resourceUrl, body, params)
}
savedTeams(params: {}) {

9
utils/localId.tsx Normal file
View file

@ -0,0 +1,9 @@
import { accountCookie } from './userToken'
export function getLocalId() {
const cookie = accountCookie()
const parsed = JSON.parse(cookie as string)
if (parsed && !parsed.token) {
return { local_id: parsed.userId }
} else return {}
}