Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/add auth0 #195

Open
wants to merge 10 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions components/DatasourceFooter.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,12 @@ const DatasourceFooter: FC = () => {
データソースについて
</Box>{' '}
| © {year} Code for Japan
{/* <Box pt={2}> */}
{/* eslint-disable-next-line @next/next/no-html-link-for-pages */}
{/* <a href="/api/auth/logout" style={{ textDecoration: 'underline' }}>
ログアウトする
</a>
</Box> */}
</Box>
<ModalBase isOpen={isOpen} onClose={onClose} maxWidth="800px">
<Box pt={10} pb={20} fontSize="14px">
Expand Down
20 changes: 18 additions & 2 deletions components/molecules/questions/Form.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import { FC, useCallback, useEffect, useMemo, useState } from 'react'
import { useRouter } from 'next/router'
import { useUser } from '@auth0/nextjs-auth0/client'
import { Box, Heading, Text } from '@chakra-ui/react'
import { Controller, FieldErrors, useForm } from 'react-hook-form'
import DatasourceFooter from 'components/DatasourceFooter'
import { API } from 'constants/api'
import { useProfile } from 'hooks/profile'
import { useAnswerController } from 'hooks/questions'
import { toBoolean } from 'utils/datatype'
import { setDynamicUrl } from 'utils/setUrl'
import api from '../../../utils/api'
import BasicButton from '../../atoms/buttons/Basic'
import RadioGroups from '../../atoms/inputs/RadioGroup'
Expand All @@ -22,6 +25,7 @@ interface SendParams extends Profile.Profile {
}

const QuestionForm: FC<Props> = ({ questionPage }) => {
const { user } = useUser()
const { profile, setProfile, userInfoDone } = useProfile()
const [isTransitioning, setIsTransitioning] = useState(false)

Expand Down Expand Up @@ -93,20 +97,32 @@ const QuestionForm: FC<Props> = ({ questionPage }) => {
const sendData = useCallback(
async (data: any) => {
let nextPageUid = nextQuestionUid(data)
console.log(profile, 'profile')
if (!profile) return
const params: SendParams = {
...profile,
[sendDataParamsKey]: data,
estimate: questionPage.isLast || nextPageUid === 'result' ? true : false
}
try {
const { data } = await api.put(`/profiles/${profile?.id}`, params)
let data: Profile.Profile | null = null
if (user?.sub) {
const authUrl = setDynamicUrl(API.PROFILE.AUTH_PUT, { id: user.sub })
const res = await api.put(authUrl, params)
console.log(res, 'res')
data = res.data
} else {
const url = setDynamicUrl(API.PROFILE.PUT, { id: profile.id })
const res = await api.put(url, params)
console.log(res, 'res2')
data = res.data
}
setProfile(data)
} catch (error) {
console.log(error)
}
},
[profile, questionPage]
[profile, questionPage, user]
)

const nextQuestionUid = (data: { [key: string]: string | number }) => {
Expand Down
16 changes: 14 additions & 2 deletions components/molecules/questions/UserinfoForm.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
import { FC, useCallback } from 'react'
import { useRouter } from 'next/router'
import { useUser } from '@auth0/nextjs-auth0/client'
import { Box, Heading } from '@chakra-ui/react'
import { Controller, useForm } from 'react-hook-form'
import BasicButton from 'components/atoms/buttons/Basic'
import SelectBox from 'components/atoms/inputs/Select'
import DatasourceFooter from 'components/DatasourceFooter'
import { API } from 'constants/api'
import { USERINFO_SKIP } from 'constants/localstorageKeys'
import { useProfile } from 'hooks/profile'
import api from 'utils/api'
import { setDynamicUrl } from 'utils/setUrl'

type FormData = {
gender?: string
Expand All @@ -16,6 +19,7 @@ type FormData = {
}

const UserinfoForm: FC = () => {
const { user } = useUser()
const router = useRouter()
const { category } = router.query

Expand All @@ -36,11 +40,19 @@ const UserinfoForm: FC = () => {
if (!formData.age) delete formData.age
if (!formData.region) delete formData.region
try {
const { data } = await api.put(`/profiles/${profile?.id}`, {
const params = {
...profile,
...formData,
estimate: true
})
}
let data = []
if (user?.sub) {
const authUrl = setDynamicUrl(API.PROFILE.AUTH_PUT, { id: user.sub })
data = await api.put(authUrl, params)
} else {
const url = setDynamicUrl(API.PROFILE.PUT, { id: profile.id })
data = await api.put(url, params)
}
setProfile(data)
router.push(`/category/${category}/result`)
} catch (error) {
Expand Down
10 changes: 6 additions & 4 deletions components/organisms/homes/HomeFooter/HomeFooter.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@ import { Box, Text } from '@chakra-ui/react'
import classNames from 'classnames'
import BasicButton from 'components/atoms/buttons/Basic'
import HomeContentCatchPhrase from 'components/molecules/homes/HomeContentCatchPhrase/HomeContentCatchPhrase'
import { API } from 'constants/api'
import styles from 'styles/Home.module.scss'

type Props = {
className?: string
onClick: { (): void }
}

const HomeFooter: FC<Props> = (props) => {
Expand All @@ -29,9 +29,11 @@ const HomeFooter: FC<Props> = (props) => {
<br className={styles['br-sp']} />
知る
</HomeContentCatchPhrase>
<BasicButton width={300} textAlign={'center'} onClick={props.onClick}>
はじめる
</BasicButton>
<a href={API.AUTH.LOGIN}>
<BasicButton width={300} textAlign={'center'}>
はじめる
</BasicButton>
</a>
<Text fontSize={14} mt={'auto'} pb={{ base: 0, md: 5 }}>
© 2022 Code for Japan
</Text>
Expand Down
14 changes: 6 additions & 8 deletions components/organisms/homes/HomeKnowSection/HomeKnowSection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@ import HomeContentBody from 'components/molecules/homes/HomeContentBody/HomeCont
import HomeContentCatchPhrase from 'components/molecules/homes/HomeContentCatchPhrase/HomeContentCatchPhrase'
import HomeContentTitle from 'components/molecules/homes/HomeContentTitle/HomeContentTitle'
import HomeSectionContainer from 'components/molecules/homes/HomeSectionContainer/HomeSectionContainer'
import { API } from 'constants/api'
import styles from 'styles/Home.module.scss'

type Props = {
className?: string
sp: boolean
onClick: { (): void }
}

const HomeKnowSection: FC<Props> = (props) => {
Expand Down Expand Up @@ -55,13 +55,11 @@ const HomeKnowSection: FC<Props> = (props) => {
<Text pb={3} fontSize={'18px'} fontWeight={'bold'}>
あなたのカーボンフットプリント量を知る
</Text>
<BasicButton
width={'full'}
textAlign={'center'}
onClick={props.onClick}
>
はじめる
</BasicButton>
<a href={API.AUTH.LOGIN}>
<BasicButton width={'full'} textAlign={'center'}>
はじめる
</BasicButton>
</a>
</Box>
</Box>
</HomeSectionContainer>
Expand Down
2 changes: 1 addition & 1 deletion components/organisms/result/MyResult.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export const MyResult: FC<Props> = ({ category }) => {
.filter((v) => v.key !== 'total' && v.value !== 0)
.sort((a, b) => b.value - a.value)
: []
}, [result])
}, [category, result])

const total = useMemo(() => {
const r = result[category]
Expand Down
14 changes: 14 additions & 0 deletions constants/api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
export const API = {
AUTH: {
LOGIN: '/api/auth/login',
LOGOUT: '/api/auth/logout'
},
PROFILE: {
INDEX: '/profiles',
AUTH_INDEX: '/auth/profiles',
AUTH_SHOW: '/auth/profiles/:id',
SHOW: '/profiles/:id',
AUTH_PUT: '/auth/profiles/:id',
PUT: '/profiles/:id'
}
}
44 changes: 38 additions & 6 deletions hooks/profile.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
import { useEffect, useState } from 'react'
import { useUser } from '@auth0/nextjs-auth0/client'
import { useRecoilState } from 'recoil'
import { API } from 'constants/api'
import { PROFILE_ID, USERINFO_SKIP } from 'constants/localstorageKeys'
import { profileAtom, sharedProfileAtom } from 'store/profile'
import { setDynamicUrl } from 'utils/setUrl'
import api from '../utils/api'

export const useProfile = () => {
const { user } = useUser()
const [profile, setProfile] = useRecoilState(profileAtom)
const [userInfoDone, setUserInfoDone] = useState(false)

Expand All @@ -13,21 +17,49 @@ export const useProfile = () => {
if (profile) return
try {
const profileId = localStorage.getItem(PROFILE_ID)
if (!profileId) {
const { data } = await api.post('/profiles', { estimate: true })
if (!profileId || profileId === 'undefined') {
let data: Profile.Profile | null = null
if (user?.sub) {
const res = await api.post(API.PROFILE.AUTH_INDEX, {
estimate: true,
user_id: user?.sub
})
data = res.data
} else {
const res = await api.post(API.PROFILE.INDEX, {
estimate: true
})
data = res.data
if (data?.id) {
localStorage.setItem(PROFILE_ID, data.id)
}
}
setProfile(data)
localStorage.setItem(PROFILE_ID, data.id)
} else {
const data = await api.get(`/profiles/${profileId}`)
let data: Profile.Profile | null = null
if (user?.sub) {
const authShowUrl = setDynamicUrl(API.PROFILE.AUTH_SHOW, {
id: user.sub
})
const res = await api.get(authShowUrl)
data = res.data
} else {
const showUrl = setDynamicUrl(API.PROFILE.SHOW, { id: profileId })
const res = await api.get(showUrl)
data = res.data
}

setProfile(data)
}
} catch (error) {
setProfile(null)
return
}
}
fetchProfile()
}, [])
return () => {
fetchProfile()
}
}, [profile, setProfile, user])

useEffect(() => {
if (
Expand Down
Loading