Skip to content

Commit

Permalink
Fix auth
Browse files Browse the repository at this point in the history
  • Loading branch information
maryanchuk04 committed Aug 6, 2023
1 parent 28ec78c commit 0c103bc
Show file tree
Hide file tree
Showing 9 changed files with 113 additions and 88 deletions.
14 changes: 14 additions & 0 deletions YeProfspilka.Frontend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions YeProfspilka.Frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
"axios": "^1.3.4",
"date-fns": "^2.29.3",
"i": "^0.3.7",
"js-cookie": "^3.0.5",
"npm": "^9.6.2",
"react": "^18.2.0",
"react-barcode": "^1.4.6",
Expand Down
8 changes: 7 additions & 1 deletion YeProfspilka.Frontend/src/components/Header/MobileHeader.jsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useState } from 'react';
import React, { useEffect, useState } from 'react';
import Hamburger from './Hamburger';
import Container from '../Container';
import MobileMenuContent from './MobileMenuContent';
Expand All @@ -13,6 +13,12 @@ const MobileHeader = () => {
const user = useSelector(selectUserData);
const navigate = useNavigate();

useEffect(() => {
if (user) {
setHeaderState(0);
}
}, [user]);

const handleClick = () => {
setMenuOpen(!menuOpen);
setHeaderState(0);
Expand Down
9 changes: 3 additions & 6 deletions YeProfspilka.Frontend/src/features/userSlice.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
import { AuthenticateService } from '../services/AuthenticateService';
import { googleDataProvider } from '../services/GoogleAuth';
import { UserService } from '../services/UserService';
import { getUser } from '../services/UserService';
import { MemberStatus } from '../types/memberStatus';
import { showAlert, showDefaultAlert } from './alertSlice';
import { HttpStatusCode } from 'axios';
Expand Down Expand Up @@ -30,7 +30,6 @@ const alert = {
type: AlertType.SUCCESS,
duration: 4000,
};
const service = new UserService();

export const googleAuthenticateThunk = createAsyncThunk(
'user/authenticate',
Expand All @@ -56,9 +55,7 @@ export const googleAuthenticateThunk = createAsyncThunk(
dispatch(showAlert(alert));
}

setTimeout(() => {
dispatch(fetchUserThunk(data.token));
}, 1000);
dispatch(fetchUserThunk(data.token));

dispatch(handleOpen());
return fulfillWithValue();
Expand All @@ -75,7 +72,7 @@ export const fetchUserThunk = createAsyncThunk(
'user/fetchUser',
async (token, { fulfillWithValue, rejectWithValue, dispatch }) => {
try {
const userResponse = await service.get(token ?? null);
const userResponse = await getUser(token);

return fulfillWithValue(userResponse.data);
} catch (error) {
Expand Down
118 changes: 65 additions & 53 deletions YeProfspilka.Frontend/src/pages/VerifyDiscount/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,62 +6,74 @@ import Loader from '../../components/Loader';
import PrimaryButton from '../../ui/Buttons/PrimaryButton';

const VerifyDiscount = () => {
const { discountId, discountCodeId } = useParams();
const { discountId, discountCodeId } = useParams();

// DATA: {"fullName":null,"email":null,"image":null,"discount":null,"isSuccess":false}
// if isSuccess == true then all data must be not null
const [state, setState] = useState({ loading: false, data: null, error: null });
// DATA: {"fullName":null,"email":null,"image":null,"discount":null,"isSuccess":false}
// if isSuccess == true then all data must be not null
const [state, setState] = useState({ loading: false, data: null, error: null });

useEffect(() => {
(async () => {
setState({ ...state, loading: true });
try {
const data = await verifyDiscount(discountId, discountCodeId);
console.log(data);
setState({ ...state, loading: false, data });
} catch (error) {
setState({ ...state, loading: false, error: error.response.data.message });
}
})();
}, [discountId, discountCodeId]);
useEffect(() => {
(async () => {
setState({ ...state, loading: true });
try {
const data = await verifyDiscount(discountId, discountCodeId);

return (
<Container className='min-h-[30rem]'>
<div className=''>
<h1>#Верифікація знижки</h1>
{state.loading ? (
<div className='h-80'>
<Loader />
</div>
) : state.data || !state.error ? (
<React.Fragment>
{state.data?.isSuccess ? (
<div className='mt-4 grid place-items-center'>
<h2>QR-код успішно підтверджено!</h2>
<p className='text-black/60 mt-2'>
Знижка<span className='font-bold mx-1'>{state.data?.discount?.name}</span> доступна для
<span className='font-bold ml-1'>{state.data?.fullName}</span>
</p>
<img src='/images/success.png' alt='success' className='w-32 h-32 my-10' />
<PrimaryButton className='!w-56'>На головну</PrimaryButton>
</div>
) : (
<div className='mt-4 grid place-items-center'>
<h2>Цей QR-код вже не дійсний!</h2>
<p className='text-black/60 mt-2'>Не потрібно нас обманювати:)</p>
<img src='/images/warning.png' alt='warning' className='w-32 h-32 my-10' />
<PrimaryButton className='!w-56'>На головну</PrimaryButton>
</div>
)}
</React.Fragment>
) : (
<React.Fragment>
<h1>Щось пішло не так!</h1>
</React.Fragment>
)}
</div>
</Container>
);
setState({ ...state, loading: false, data });
} catch (error) {
setState({ ...state, loading: false, error: error.response.data.message });
}
})();
}, [discountId, discountCodeId]);

return (
<Container className='min-h-[30rem]'>
<div className=''>
<h1>#Верифікація знижки</h1>
{state.loading ? (
<div className='h-80'>
<Loader />
</div>
) : state.data || !state.error ? (
<React.Fragment>
{state.data?.isSuccess ? (
<div className='mt-4 grid place-items-center'>
<h2>QR-код успішно підтверджено!</h2>
<p className='text-black/60 mt-2'>
Знижка
<span className='font-bold mx-1'>
{state.data?.discount?.name}
</span>{' '}
доступна для
<span className='font-bold ml-1'>{state.data?.fullName}</span>
</p>
<img
src='/images/success.png'
alt='success'
className='w-32 h-32 my-10'
/>
<PrimaryButton className='!w-56'>На головну</PrimaryButton>
</div>
) : (
<div className='mt-4 grid place-items-center'>
<h2>Цей QR-код вже не дійсний!</h2>
<p className='text-black/60 mt-2'>Не потрібно нас обманювати:)</p>
<img
src='/images/warning.png'
alt='warning'
className='w-32 h-32 my-10'
/>
<PrimaryButton className='!w-56'>На головну</PrimaryButton>
</div>
)}
</React.Fragment>
) : (
<React.Fragment>
<h1>Щось пішло не так!</h1>
</React.Fragment>
)}
</div>
</Container>
);
};

export default VerifyDiscount;
7 changes: 4 additions & 3 deletions YeProfspilka.Frontend/src/services/AuthenticateService.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import { ApiService } from './config/ApiService';
import { Token } from './TokenService';

const api = new ApiService();

export class AuthenticateService {
#url = '/authenticate';
api = new ApiService();

async authenticateGoogle({ name, picture, email, hd }) {
try {
const response = await this.api.post(`${this.#url}/google`, {
const response = await api.post(`${this.#url}/google`, {
fullName: name,
avatar: picture,
email,
Expand All @@ -24,6 +25,6 @@ export class AuthenticateService {
}

logout() {
return this.api.post(`${this.#url}/logout`);
return api.post(`${this.#url}/logout`);
}
}
19 changes: 13 additions & 6 deletions YeProfspilka.Frontend/src/services/UserService.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,23 @@
import { ApiService } from './config/ApiService';
import axiosInstance from './config/axios.config';
import { Token } from './TokenService';
const api = new ApiService();

export class UserService {
#url = '/user';

constructor() {
this.api = new ApiService();
}
constructor() {}

async get(token = null) {
return await this.api.get(this.#url, {
Authorization: `Bearer ${token ?? Token.get() ?? ''}`,
});
return await api.get('/user', token);
}
}

export const getUser = async (token = null) => {
return axiosInstance.get('/user', {
headers: {
Authorization: `Bearer ${token ?? Token.get()}`,
},
withCredentials: true,
});
};
11 changes: 6 additions & 5 deletions YeProfspilka.Frontend/src/services/config/ApiService.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,12 @@ export class ApiService {
return res;
}

async get(url) {
const call = async () => {
return await api.get(url, {
Authorization: `Bearer ${Token.get() || ''}`,
withCredentials: true,
async get(url, token = null) {
const call = () => {
return api.get(url, {
headers: {
Authorization: `Bearer ${token ?? Token.get() ?? ''}`,
},
});
};

Expand Down
14 changes: 0 additions & 14 deletions YeProfspilka.Frontend/src/services/config/axios.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,4 @@ const axiosInstance = axios.create({
},
});

// axiosInstance.interceptors.response.use(
// (response) => {
// // Any status code that lie within the range of 2xx cause this function to trigger
// // Do something with response data
// return response;
// },
// (error) => {
// if (error.response?.data?.message === USER_NOT_FOUND) {
// Token.remove();
// }
// return Promise.reject(error);
// }
// );

export default axiosInstance;

0 comments on commit 0c103bc

Please sign in to comment.