Skip to content

Commit

Permalink
Merge pull request #85 from OlhaD/77-fix-login-without-remember-me
Browse files Browse the repository at this point in the history
77 fix login without remember me
  • Loading branch information
OlhaD authored Aug 21, 2023
2 parents 01ee9ed + 6c9b11a commit 0748756
Show file tree
Hide file tree
Showing 13 changed files with 74 additions and 51 deletions.
6 changes: 4 additions & 2 deletions src/api/transfers.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import apiClient from '../utils/apiClient';
import { makeQueryString } from '../utils/formatting';

export const getTransfers = async ({ pagination, filter }) => {
export const getTransfers = async (token, { pagination, filter }) => {
try {
const where = filter.getWhereObj();
// pagination: limit, offset
Expand All @@ -13,7 +13,9 @@ export const getTransfers = async ({ pagination, filter }) => {

const queryString = makeQueryString(transferFilter);

const response = await apiClient.get(`/transfers?${queryString}`);
const response = await apiClient
.setAuthHeader(token)
.get(`/transfers?${queryString}`);
return response.data;
} catch (error) {
console.error(error);
Expand Down
6 changes: 4 additions & 2 deletions src/api/wallets.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ const mapWallet = (walletData, nameProp) => {
};
};

export const getWallets = async (name = '', pageNumber = 1) => {
export const getWallets = async (token, name = '', pageNumber = 1) => {
const params = {
offset: pageNumber - 1,
};
Expand All @@ -20,6 +20,7 @@ export const getWallets = async (name = '', pageNumber = 1) => {
}

const { total, wallets } = await apiClient
.setAuthHeader(token)
.get('/wallets', {
params: {
name: name || undefined, // Pass 'name' if it exists, or pass 'undefined' to exclude it
Expand All @@ -46,8 +47,9 @@ export const getWallets = async (name = '', pageNumber = 1) => {
};
};

export const getWalletById = async (id) => {
export const getWalletById = async (token, id) => {
const walletData = await apiClient
.setAuthHeader(token)
.get('/wallets/' + id)
.then((response) => {
return mapWallet(response.data, 'wallet');
Expand Down
10 changes: 8 additions & 2 deletions src/pages/MyTransfers/MyTransfers.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import React, { useEffect, useState } from 'react';
import React, { useContext, useEffect, useState } from 'react';
import { Grid } from '@mui/material';
import TransfersTable from './TransfersTable';
import Message from '../../components/UI/components/Message/Message';
import { getTransfers } from '../../api/transfers';
import { useTransfersContext } from '../../store/TransfersContext';
import AuthContext from '../../store/auth-context';

/**@function
* @name MyTransfers
Expand All @@ -22,12 +23,17 @@ const MyTransfers = () => {
// total rows count for pagination
const [totalRowCount, setTotalRowCount] = useState(null);

const authContext = useContext(AuthContext);

// load data
useEffect(() => {
const loadData = async () => {
try {
setIsLoading(true);
const data = await getTransfers({ pagination, filter });
const data = await getTransfers(authContext.token, {
pagination,
filter,
});
const preparedRows = prepareRows(await data.transfers);

setTableRows(preparedRows);
Expand Down
11 changes: 4 additions & 7 deletions src/pages/MyTransfers/MyTransfers.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@ import AuthProvider from '../../store/AuthProvider';
import { BrowserRouter as Router } from 'react-router-dom';
import { TransfersProvider } from '../../store/TransfersContext';
import MyTransfers from './MyTransfers';
import apiClient from '../../utils/apiClient';
import { getTransfers } from '../../api/transfers';

jest.mock('../../utils/apiClient', () => ({
get: jest.fn(),
jest.mock('../../api/transfers', () => ({
getTransfers: jest.fn(),
}));

const mockTransfersData = {
Expand Down Expand Up @@ -98,21 +98,18 @@ describe('My Transfers page', function () {
});

it('renders table pagination correctly', async () => {
apiClient.get.mockResolvedValueOnce({ data: mockTransfersData });

getTransfers.mockResolvedValueOnce(mockTransfersData);
render(
<TestWrapper>
<MyTransfers />
</TestWrapper>
);

expect(await screen.findByTestId('table-pagination')).toBeInTheDocument();
expect(await screen.findByTestId('transfers-table')).toBeInTheDocument();
expect(await screen.findByTestId('date-range-filter')).toBeInTheDocument();
expect(
await screen.findByTestId('transfer-status-filter')
).toBeInTheDocument();

await waitFor(() => {
expect(screen.getAllByRole('row')).toHaveLength(3 + 1);
});
Expand Down
8 changes: 6 additions & 2 deletions src/pages/SendTokens/SendTokens.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useState } from 'react';
import React, { useContext, useState } from 'react';
import { Paper } from '@mui/material';
import {
ContentContainer,
Expand All @@ -14,7 +14,7 @@ import apiClient from '../../utils/apiClient';
import { Loader } from '../../components/UI/components/Loader/Loader';
import TokenInfoBlock from './TokenInfoBlock/TokenInfoBlock';
import { formatWithCommas } from '../../utils/formatting';
// import AuthContext from '../../store/auth-context';
import AuthContext from '../../store/auth-context';

const SendTokens = () => {
const [createdWalletName, setCreatedWalletName] = useState();
Expand All @@ -25,6 +25,8 @@ const SendTokens = () => {
const [senderWalletName, setSenderWalletName] = useState();
const [senderWalletTokens, setSenderWalletTokens] = useState(0);

const authContext = useContext(AuthContext);

// TODO: uncomment when API is ready: is should have a totalTokens value
// const [totalTokensAmount, setTotalTokensAmount] = useState();

Expand Down Expand Up @@ -62,6 +64,7 @@ const SendTokens = () => {
setIsLoading(true);

apiClient
.setAuthHeader(authContext.token)
.post('/transfers', {
bundle: { bundle_size: data.tokensAmount },
sender_wallet: data.senderWallet,
Expand Down Expand Up @@ -104,6 +107,7 @@ const SendTokens = () => {
setIsLoading(true);

apiClient
.setAuthHeader(authContext.token)
.post('/wallets', {
wallet: name,
})
Expand Down
13 changes: 10 additions & 3 deletions src/pages/SendTokens/SendTokensForm/SelectWallet.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import React, { useEffect, useState } from 'react';
import React, { useContext, useEffect, useState } from 'react';
import { Autocomplete, Button, TextField } from '@mui/material';
import { getWallets } from '../../../api/wallets';
import AuthContext from '../../../store/auth-context';

function SelectWallet({ wallet, onChangeWallet, label, createdWalletName }) {
const filterLoadMore = 'LOAD_MORE';
Expand All @@ -11,12 +12,14 @@ function SelectWallet({ wallet, onChangeWallet, label, createdWalletName }) {
const [walletsFullLoadedData, setWalletsFullLoadedData] = useState([]);
const [walletSearchString, setWalletSearchString] = useState('');

const authContext = useContext(AuthContext);

// Is called when page loads and when user starts to type in a 'Wallet' filter
useEffect(() => {
const getWalletsData = async () => {
setWalletPage(0);
try {
let response = await getWallets(walletSearchString);
let response = await getWallets(authContext.token, walletSearchString);

if (!response) {
console.log('No response from getWallets');
Expand Down Expand Up @@ -69,7 +72,11 @@ function SelectWallet({ wallet, onChangeWallet, label, createdWalletName }) {
}

try {
const response = await getWallets(walletSearchString, walletPage);
const response = await getWallets(
authContext.token,
walletSearchString,
walletPage
);

const total = response.total;
setWalletsFullLoadedData(response.wallets);
Expand Down
9 changes: 6 additions & 3 deletions src/pages/Wallet/Wallet.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,12 +41,15 @@ const Wallet = () => {
const fetchData = async () => {
try {
// get wallet data
const returnedWalletData = await getWalletById(wallet.id);
const returnedWalletData = await getWalletById(
authContext.token,
wallet.id
);
setWallet(returnedWalletData);

// get pending transfers data
const pendingTransferFilter = new TransferFilter({ state: 'pending' });
const returnedTransferData = await getTransfers({
const returnedTransferData = await getTransfers(authContext.token, {
filter: pendingTransferFilter,
});
setPendingTransfers(returnedTransferData.transfers);
Expand All @@ -59,7 +62,7 @@ const Wallet = () => {
};

fetchData();
}, []);
}, [authContext.token]);

if (isLoading) {
return <Loader />;
Expand Down
26 changes: 12 additions & 14 deletions src/pages/Wallet/Wallet.test.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { render, screen } from '@testing-library/react';
import React from 'react';
import apiClient from '../../utils/apiClient';
import { getTransfers } from '../../api/transfers';
import Wallet from './Wallet';
import { getWalletById } from '../../api/wallets';

jest.mock('../../utils/apiClient', () => ({
get: jest.fn(),
jest.mock('../../api/wallets', () => ({
getWalletById: jest.fn(),
}));

jest.mock('../../api/transfers', () => ({
Expand Down Expand Up @@ -76,6 +76,13 @@ const mockPendingTransfers = {
total: 3,
};

const mockWallet = {
id: '9d6c674f-ae62-4fab-8d14-ae5de9f14ab8',
logoUrl: 'https://example.com/logo.png',
tokensInWallet: 100,
name: 'test wallet',
};

describe('<Wallet />', () => {
beforeEach(() => {
localStorage.setItem(
Expand All @@ -92,14 +99,7 @@ describe('<Wallet />', () => {
});

it('fetches and displays wallet data', async () => {
apiClient.get.mockResolvedValueOnce({
data: {
id: '9d6c674f-ae62-4fab-8d14-ae5de9f14ab8',
logo_url: 'https://example.com/logo.png',
tokens_in_wallet: 100,
wallet: 'test wallet',
},
});
getWalletById.mockResolvedValueOnce(mockWallet);

getTransfers.mockResolvedValueOnce(mockPendingTransfers);

Expand All @@ -115,11 +115,9 @@ describe('<Wallet />', () => {
});

it('displays error message on fetch failure', async () => {
apiClient.get.mockImplementationOnce(() => Promise.reject('API error'));
getWalletById.mockImplementationOnce(() => Promise.reject('API error'));
getTransfers.mockImplementation(() => Promise.reject('API error'));

render(<Wallet />);

expect(screen.getByRole('progressbar')).toBeInTheDocument();

// TODO: fix and uncomment
Expand Down
2 changes: 1 addition & 1 deletion src/pages/Wallet/WalletHeader/WalletHeader.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ const WalletHeader = ({ pendingTransfers, walletName, walletLogoURL }) => {
sx={{ display: 'flex', flexDirection: 'column' }}
>
<WalletTitle>{walletName}</WalletTitle>
<WalletPendingTransfers pendingTransfers={pendingTransfers}>
<WalletPendingTransfers pendingtransfers={pendingTransfers}>
Pending transfers - {pendingTransfers}
</WalletPendingTransfers>
</Grid>
Expand Down
4 changes: 2 additions & 2 deletions src/pages/Wallet/WalletHeader/WalletHeaderStyled.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ export const WalletTitle = styled(Typography)({
lineHeight: '40px',
});

export const WalletPendingTransfers = styled(Typography)(({ pendingTransfers }) => ({
color: pendingTransfers === 0 ? '#000000' : '#FF2B2B',
export const WalletPendingTransfers = styled(Typography)(({ pendingtransfers }) => ({
color: pendingtransfers === 0 ? '#000000' : '#FF2B2B',
fontSize: '16px',
fontStyle: 'normal',
fontWeight: '400',
Expand Down
5 changes: 3 additions & 2 deletions src/store/AuthProvider.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable no-debugger */
import React, { useState } from 'react';
import jwt_decode from 'jwt-decode';
import AuthContext from './auth-context';
Expand All @@ -23,12 +24,12 @@ const AuthProvider = (props) => {
const wallet = newWallet ? newWallet : parseToken(newToken);
setWallet(wallet);

localStorage.setItem(walletKey, JSON.stringify(wallet));

if (rememberDetails) {
localStorage.setItem(tokenKey, newToken);
localStorage.setItem(walletKey, JSON.stringify(wallet));
} else {
localStorage.removeItem(tokenKey);
localStorage.removeItem(walletKey);
}

setIsLoggedIn(true);
Expand Down
2 changes: 2 additions & 0 deletions src/store/auth-context.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import { createContext } from "react";

const AuthContext = createContext({
isLoggedIn: false,
token: "",
wallet: {},
login: () => {},
logout: () => {},
});
Expand Down
23 changes: 12 additions & 11 deletions src/utils/apiClient.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,19 @@ const apiClient = axios.create({
},
});

apiClient.interceptors.request.use(
(config) => {
const token = localStorage.getItem('token');

if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
apiClient.setAuthToken = (token) => {
if (token) {
apiClient.defaults.headers.common['Authorization'] = `Bearer ${token}`;
} else {
delete apiClient.defaults.headers.common['Authorization'];
}
};

return config;
},
(error) => Promise.reject(error)
);
// Custom method to set auth header and make API call
apiClient.setAuthHeader = (token) => {
apiClient.setAuthToken(token);
return apiClient;
};

// all unauthorized responses will be redirected to login
apiClient.interceptors.response.use(
Expand Down

0 comments on commit 0748756

Please sign in to comment.