Skip to content

Commit

Permalink
Refactor HandleAuth component
Browse files Browse the repository at this point in the history
  • Loading branch information
OlgaBilogurova committed May 24, 2021
1 parent 790628d commit c40140e
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 32 deletions.
44 changes: 13 additions & 31 deletions client/src/components/auth/HandleAuth.js
Original file line number Diff line number Diff line change
@@ -1,47 +1,29 @@
import React, { useState, useEffect } from 'react';
import { Redirect } from 'react-router-dom';
import { isValidToken } from '../../services/user.service';

import '../../sass/MagicLink.scss';
import useAuth from '../../hooks/useAuth';

const HandleAuth = (props) => {
const auth = useAuth();
const [isMagicLinkValid, setMagicLink] = useState(null);
const headerToSend = process.env.REACT_APP_CUSTOM_REQUEST_HEADER;

async function isValidToken() {
useEffect(() => {
const search = props.location.search;
const params = new URLSearchParams(search);
const api_token = params.get('token');

try {
const response = await fetch('/api/auth/verify-signin', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-access-token': api_token,
'x-customrequired-header': headerToSend,
},
});
// eslint-disable-next-line no-unused-vars
const body = await response;
setMagicLink(response.status === 200);
} catch (error) {
console.log(error);
}
}

useEffect(() => {
isValidToken();
const isValid = isValidToken(api_token);
setMagicLink(isValid);
}, []);

if (isMagicLinkValid) {
return <Redirect to="/admin" />;
} else {
return (
<div className="flex-container">
<div>Sorry, the link is not valid.</div>
</div>
);
}
return auth.user && isMagicLinkValid ? (
<Redirect to="/admin" />
) : (
<div className="flex-container">
<div>Sorry, the link is not valid anymore.</div>
</div>
);
};

export default HandleAuth;
29 changes: 28 additions & 1 deletion client/src/services/user.service.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import { HEADERS, CHECK_USER, SIGN_IN } from '../utils/endpoints';
import {
HEADERS,
CHECK_USER,
SIGN_IN,
AUTH_VERIFY_SIGN_IN,
} from '../utils/endpoints';

/**
* Method sent request to the backend to check if user exist in the DB
Expand Down Expand Up @@ -41,3 +46,25 @@ export async function checkAuth(email, auth_origin) {
return null;
}
}

/**
* Method sent request to the backend to check if token is valid
* @returns true if is valid otherwise false
* @param api_token token
*/
export async function isValidToken(api_token) {
try {
const response = await fetch(AUTH_VERIFY_SIGN_IN, {
method: 'POST',
headers: {
...HEADERS,
'x-access-token': api_token,
},
});
return response.status === 200;
} catch (error) {
console.log('Token is not valid');
console.log(error);
return false;
}
}

0 comments on commit c40140e

Please sign in to comment.