Skip to content
This repository has been archived by the owner on Oct 14, 2023. It is now read-only.

Commit

Permalink
Добавила OAuth авторизацию (#13)
Browse files Browse the repository at this point in the history
* Добавила OAuth авторизацию

* Fix marks

* Fix bugs
  • Loading branch information
KosilovaDaria authored Dec 21, 2022
1 parent 1388ecd commit 0d30f6a
Show file tree
Hide file tree
Showing 17 changed files with 187 additions and 76 deletions.
18 changes: 9 additions & 9 deletions packages/client/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,16 @@ import NotFound from './pages/not-found/NotFound'
import ServerError from './pages/server-error/ServerError'

function App() {
useEffect(() => {
const fetchServerData = async () => {
const url = `http://localhost:${__SERVER_PORT__}`
const response = await fetch(url)
const data = await response.json()
console.log(data)
}
// useEffect(() => {
// const fetchServerData = async () => {
// const url = `http://localhost:${__SERVER_PORT__}`
// const response = await fetch(url)
// const data = await response.json()
// console.log(data)
// }

fetchServerData()
}, [])
// fetchServerData()
// }, [])
return (
<Routes>
<Route path={'/'} element={<Intro />} />
Expand Down
4 changes: 4 additions & 0 deletions packages/client/src/assets/RU.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added packages/client/src/assets/ya-btn.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
5 changes: 5 additions & 0 deletions packages/client/src/components/YandexIcon/YandexIcon.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import icon from '@assets/RU.svg'
export const YandexIcon = () => {
return <img src={icon}/>

}
30 changes: 15 additions & 15 deletions packages/client/src/entry-client.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,21 +9,21 @@ import ErrorBoundary from './components/ErrorBoundary'

const store = setupStore()

window.addEventListener('load', () => {
if ('serviceWorker' in navigator) {
navigator.serviceWorker
.register('/sw.js')
.then(registration => {
console.log(
'ServiceWorker registration successful with scope: ',
registration.scope
)
})
.catch((error: string) => {
console.log('ServiceWorker registration failed: ', error)
})
}
})
// window.addEventListener('load', () => {
// if ('serviceWorker' in navigator) {
// navigator.serviceWorker
// .register('/sw.js')
// .then(registration => {
// console.log(
// 'ServiceWorker registration successful with scope: ',
// registration.scope
// )
// })
// .catch((error: string) => {
// console.log('ServiceWorker registration failed: ', error)
// })
// }
// })

ReactDOM.hydrateRoot(
document.getElementById('root') as HTMLElement,
Expand Down
8 changes: 4 additions & 4 deletions packages/client/src/hooks/useAuth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@ export const useAuth = () => {
user.id
? navigate('/game/start')
: dispatch(fetchUser()).then(res => {
if (res.type === 'auth/fetch/rejected') {
return navigate('/auth')
}
})
if (res.type === 'auth/fetch/rejected') {
return navigate('/auth')
}
})
}
}
23 changes: 23 additions & 0 deletions packages/client/src/hooks/useOAuth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { oauthYandex, fetchUser } from '@store/actions/AuthActionCreators'
import { useAppDispatch } from '@store/index'
import { OauthData } from '@store/types'

export const useOAuth = () => {
const REDIRECT_URI = 'http://localhost:3000'
const dispatch = useAppDispatch()
const url = document.location.href
const code = url.split('=').pop();
return () => {
if (/code/.test(url)) {
dispatch(oauthYandex({
code: code,
redirect_uri: REDIRECT_URI
} as OauthData))
.then(res => {
if (res.payload === 'OK') {
dispatch(fetchUser())
}
})
}
}
}
2 changes: 1 addition & 1 deletion packages/client/src/hooks/useRegister.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { fetchUser, register } from '../store/actions/AuthActionCreators'
import { register } from '../store/actions/AuthActionCreators'
import { useAppDispatch } from '../store/index'
import { UserData } from '../store/types'
import { useNavigate } from 'react-router-dom'
Expand Down
17 changes: 17 additions & 0 deletions packages/client/src/hooks/useServiceId.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { getServiceId } from "@store/actions/AuthActionCreators"
import { useAppDispatch } from "@store/index"

export const useServiceId = () => {
const dispatch = useAppDispatch()
const REDIRECT_URI = 'http://localhost:3000';
// const REDIRECT_URI =`http://localhost:${__CLIENT_PORT__}`

return () => {
dispatch(getServiceId())
.then(res => {
if (res.payload.service_id) {
document.location = `https://oauth.yandex.ru/authorize?response_type=code&client_id=${res.payload.service_id}&redirect_uri=${REDIRECT_URI}`
}
})
}
}
38 changes: 31 additions & 7 deletions packages/client/src/pages/LoginPage/Login.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import React, { useEffect } from 'react'
import {
Container,
Box,
Expand All @@ -8,25 +7,42 @@ import {
Stack,
} from '@mui/material'
import { Link, useNavigate } from 'react-router-dom'
import { createTheme, ThemeProvider } from '@mui/material/styles'
import { LoginData } from '../../store/types'
import { createTheme, styled, ThemeProvider } from '@mui/material/styles'
import { LoginData } from '@store/types'
import { useLogin } from '../../hooks/useLogin'
import { useUser } from '../../hooks/useUser'
import { fetchUser } from '../../store/actions/AuthActionCreators'
import { useAppDispatch } from '../../store/index'
import { useEffect } from 'react'
import { fetchUser } from '@store/actions/AuthActionCreators'
import { useAppDispatch } from '@store/index'
import { YandexIcon } from '@components/YandexIcon/YandexIcon'
import { useServiceId } from '../../hooks/useServiceId'

export default function Login() {
const user = useUser()
const dispatch = useAppDispatch()
const navigate = useNavigate()
const login = useLogin()
const location = useServiceId()

const YandexIdButton = styled(Button)({
color: ' white',
width: '100%',
height: '44px',
backgroundColor: 'black',
textTransform: 'none',
'&:hover': {
backgroundColor: 'black',
borderColor: '#0062cc',
boxShadow: 'none',
},
})

useEffect(() => {
dispatch(fetchUser())
if (user.id) {
navigate('/')
}
}, [navigate, user])
dispatch(fetchUser())
}, [user.id])

const theme = createTheme({
typography: {
Expand All @@ -42,6 +58,7 @@ export default function Login() {
} as LoginData
login(authData)
}


return (
<ThemeProvider theme={theme}>
Expand Down Expand Up @@ -89,6 +106,13 @@ export default function Login() {
{' '}
Войти
</Button>
<Typography component="p" sx={{ textAlign: 'center', fontSize: '12px' }}>
или
</Typography>
<YandexIdButton
onClick={()=>location()}
// startIcon={<YandexIcon/>}
>Войти c Яндекс ID</YandexIdButton>
<Stack spacing={2} sx={{ textAlign: 'center' }}>
<Typography>Еще не зарегистрированы?</Typography>
<Link
Expand Down
14 changes: 2 additions & 12 deletions packages/client/src/pages/game/GameStart/MenuList/MenuList.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,11 @@
import React from 'react'
import { Box, Button } from '@mui/material'
import { Box } from '@mui/material'

import userIcon from '../../../../assets/user-icon.svg'
import chatIcon from '../../../../assets/chat-icon.svg'
import ratingIcon from '../../../../assets/rating-icon.svg'
import questionIcon from '../../../../assets/question-icon.svg'
import exitIcon from '../../../../assets/exit-icon.svg'
import MenuItem from '../MenuItem'
import { logout } from '../../../../store/actions/AuthActionCreators'
import { useAppDispatch } from '../../../../store'
import { useNavigate } from 'react-router-dom'

const links = [
{ title: 'Профиль игрока', src: userIcon, alt: 'профиль', to: '/profile' },
Expand All @@ -19,13 +16,7 @@ const links = [
]

export default function MenuList() {
const dispatch = useAppDispatch()
const navigate = useNavigate()

const logOut = () => {
dispatch(logout())
navigate('/auth')
}
return (
<Box
component="ul"
Expand All @@ -43,7 +34,6 @@ export default function MenuList() {
{links.map(props => (
<MenuItem key={props.title} {...props} />
))}
<Button onClick={logOut}>Выйти</Button>
</Box>
)
}
39 changes: 16 additions & 23 deletions packages/client/src/pages/intro/Intro.tsx
Original file line number Diff line number Diff line change
@@ -1,20 +1,22 @@
import React, { useEffect } from 'react'
import { Link } from 'react-router-dom'
import { Button, Box, Container, Typography } from '@mui/material'
import { fetchUser } from '../../store/actions/AuthActionCreators'
import { useAppDispatch } from '../../store/index'
import { Box, Container, Button, Typography } from '@mui/material'
import { fetchUser } from '@store/actions/AuthActionCreators'
import { useAppDispatch } from '@store/index'
import { useOAuth } from '../../hooks/useOAuth'
import { useEffect } from 'react'

import { useAuth } from '../../hooks/useAuth'
import styles from './styles'
import React from 'react'

export default function Intro() {
const getOAuth = useOAuth()
const getAuth = useAuth()
const dispatch = useAppDispatch()

useEffect(() => {
getOAuth()
dispatch(fetchUser())
}, [])
const isAuth = useAuth()
const handleClick = () => {
isAuth()
}

return (
<React.Fragment>
Expand All @@ -31,21 +33,12 @@ export default function Intro() {
alignItems: 'flex-start',
}}>
<Button
onClick={() => getAuth()}
sx={{ marginBottom: '1rem' }}
variant="contained"
sx={{
background: '#000',
marginBottom: '1rem',
':hover': {
backgroundColor: '#000',
color: '#fff',
},
}}>
<Link
to="/auth"
onClick={handleClick}
style={{ textDecoration: 'none', color: '#fff' }}>
Начать игру
</Link>
size="large"
color="primary">
Начать игру
</Button>
<Typography>Для игры требуется регистрация</Typography>
</Box>
Expand Down
4 changes: 2 additions & 2 deletions packages/client/src/pages/profile/Profile.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -206,8 +206,8 @@ const Profile = () => {
marginTop: 1,
}}
onClick={() => {
dispatch(logout())
navigate('/auth')
dispatch(logout()).then(()=>navigate('/auth'))

}}>
Выйти из профиля
</RB.Button>
Expand Down
27 changes: 26 additions & 1 deletion packages/client/src/store/actions/AuthActionCreators.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { createAsyncThunk } from '@reduxjs/toolkit'
import { LoginData, UserData } from '../types'
import { LoginData, OauthData, UserData } from '@store/types'

import axiosInstance from '../../services/BaseApi'

export const register = createAsyncThunk(
Expand Down Expand Up @@ -45,3 +46,27 @@ export const logout = createAsyncThunk('auth/logout', async (_, thunkApi) => {
return thunkApi.rejectWithValue('Не удалось выйти из приложения')
}
})

export const getServiceId = createAsyncThunk(
'auth/serviceid',
async (_, thunkApi) => {
try {
const response = await axiosInstance.get('oauth/yandex/service-id')
return response.data
} catch (e) {
return thunkApi.rejectWithValue('No such redirect_uri refistered')
}
}
)

export const oauthYandex = createAsyncThunk(
'auth/yandex',
async (data: OauthData, thunkApi) => {
try {
const response = await axiosInstance.post('oauth/yandex', data)
return response.data
} catch (e) {
return thunkApi.rejectWithValue('Пользователь не авторизован в системе')
}
}
)
Loading

0 comments on commit 0d30f6a

Please sign in to comment.