Skip to content

Commit

Permalink
Merge pull request #576 from hackforla/refactor-admin-login-component
Browse files Browse the repository at this point in the history
Refactor admin login component
  • Loading branch information
alex-anakin authored May 24, 2021
2 parents 1708197 + c40140e commit 16a3857
Show file tree
Hide file tree
Showing 6 changed files with 177 additions and 149 deletions.
76 changes: 38 additions & 38 deletions client/src/App.js
Original file line number Diff line number Diff line change
@@ -1,48 +1,48 @@
import React from "react";
import { AuthProvider } from "./context/authContext";
import { Route, Redirect, Switch } from "react-router-dom";
import React from 'react';
import { AuthProvider } from './context/authContext';
import { Route, Redirect, Switch } from 'react-router-dom';

import Home from "./pages/Home";
import Navbar from "./components/Navbar";
import Footer from "./components/Footer";
import AdminDashboard from "./components/admin/dashboard";
import UserDashboard from "./pages/UserDashboard";
import UserProfile from "./pages/UserProfile";
import Event from "./pages/Event";
import NewUser from "./pages/NewUser";
import ReturningUser from "./pages/ReturningUser";
import AdminLogin from "./pages/AdminLogin";
import CheckInForm from "./pages/CheckInForm";
import Success from "./pages/Success";
import HandleAuth from "./pages/HandleAuth";
import EmailSent from "./pages/EmailSent";
import Events from "./pages/Events";
import AddNew from "./pages/AddNew";
import ProjectLeaderDashboard from "./pages/ProjectLeaderDashboard";
import Home from './pages/Home';
import Navbar from './components/Navbar';
import Footer from './components/Footer';
import AdminDashboard from './components/admin/dashboard';
import UserDashboard from './pages/UserDashboard';
import UserProfile from './pages/UserProfile';
import Event from './pages/Event';
import NewUser from './pages/NewUser';
import ReturningUser from './pages/ReturningUser';
import Auth from './components/auth/Auth';
import CheckInForm from './pages/CheckInForm';
import Success from './pages/Success';
import HandleAuth from './components/auth/HandleAuth';
import EmailSent from './pages/EmailSent';
import Events from './pages/Events';
import AddNew from './pages/AddNew';
import ProjectLeaderDashboard from './pages/ProjectLeaderDashboard';

import "./App.scss";
import './App.scss';

const routes = [
{ path: "/", name: "home", Component: Home },
{ path: "/admin", name: "admindashboard", Component: AdminDashboard },
{ path: "/user", name: "userdashboard", Component: UserDashboard },
{ path: "/profile", name: "profile", Component: UserProfile },
{ path: "/event/:id", name: "event", Component: Event },
{ path: "/new", name: "new", Component: NewUser },
{ path: "/returning", name: "returning", Component: ReturningUser },
{ path: "/login", name: "login", Component: AdminLogin },
{ path: "/checkIn/:userType", name: "checkIn", Component: CheckInForm },
{ path: "/newProfile", name: "newProfile", Component: CheckInForm },
{ path: "/success", name: "success", Component: Success },
{ path: "/handleauth", name: "handleauth", Component: HandleAuth },
{ path: "/emailsent", name: "emailsent", Component: EmailSent },
{ path: "/events", name: "events", Component: Events },
{ path: '/', name: 'home', Component: Home },
{ path: '/admin', name: 'admindashboard', Component: AdminDashboard },
{ path: '/user', name: 'userdashboard', Component: UserDashboard },
{ path: '/profile', name: 'profile', Component: UserProfile },
{ path: '/event/:id', name: 'event', Component: Event },
{ path: '/new', name: 'new', Component: NewUser },
{ path: '/returning', name: 'returning', Component: ReturningUser },
{ path: '/login', name: 'login', Component: Auth },
{ path: '/checkIn/:userType', name: 'checkIn', Component: CheckInForm },
{ path: '/newProfile', name: 'newProfile', Component: CheckInForm },
{ path: '/success', name: 'success', Component: Success },
{ path: '/handleauth', name: 'handleauth', Component: HandleAuth },
{ path: '/emailsent', name: 'emailsent', Component: EmailSent },
{ path: '/events', name: 'events', Component: Events },
{
path: "/projectleader",
name: "pldashboard",
path: '/projectleader',
name: 'pldashboard',
Component: ProjectLeaderDashboard,
},
{ path: "/add/:item", name: "addnew", Component: AddNew },
{ path: '/add/:item', name: 'addnew', Component: AddNew },
];

const App = () => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,19 @@
import React, { useState } from 'react';
import { Redirect } from 'react-router-dom';
import { useHistory } from 'react-router-dom';
import { checkUser, checkAuth } from '../../services/user.service';

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

/** At the moment only users with the 'admin' accessLevel can login
* and see the dashboard
**/
const AdminLogin = () => {
const Auth = () => {
const LOG_IN = 'LOG_IN';
const ADMIN = 'admin';
const pattern = /\b[a-z0-9._]+@[a-z0-9.-]+\.[a-z]{2,4}\b/i;

const history = useHistory();
const auth = useAuth();

Expand All @@ -17,91 +22,58 @@ const AdminLogin = () => {
const [isError, setIsError] = useState(false);
const [errorMessage, setErrorMessage] = useState('');

const CHECK_USER = '/api/checkuser';
const HEADERS = {
'Content-Type': 'application/json',
'x-customrequired-header': process.env.REACT_APP_CUSTOM_REQUEST_HEADER,
const validateEmail = () => {
if (email.search(pattern) !== -1) {
setIsDisabled(false);
return true;
} else {
setIsDisabled(true);
showError('Please enter a valid email address');
return false;
}
};
const auth_origin = 'LOG_IN';
const SIGN_IN = '/api/auth/signin';
const ADMIN = 'admin';

const isValidEmail = (email) => {
const pattern = /\b[a-z0-9._]+@[a-z0-9.-]+\.[a-z]{2,4}\b/i;
return email.search(pattern) !== -1;
const showError = (message) => {
setIsError(true);
setErrorMessage(message);
};

async function checkUser(email) {
try {
const response = await fetch(CHECK_USER, {
method: 'POST',
headers: HEADERS,
body: JSON.stringify({ email: email, auth_origin: auth_origin }),
});
return await response.json();
} catch (error) {
console.log('User is not registered in the app');
console.log(error);
return null;
}
}
const handleLogin = async (e) => {
e.preventDefault();

async function checkAuth(email) {
try {
const response = await fetch(SIGN_IN, {
method: 'POST',
headers: HEADERS,
body: JSON.stringify({ email: email, auth_origin: auth_origin }),
});
return response.status === 200;
} catch (error) {
console.log('User is not authorized in app');
console.log(error);
return null;
}
}
const isEmailValid = validateEmail();

const handleLogin = async () => {
if (isValidEmail(email)) {
setIsDisabled(false);
const userData = await checkUser(email);
if (isEmailValid) {
const userData = await checkUser(email, LOG_IN);
if (userData) {
if (userData.user.accessLevel !== ADMIN) {
setIsError(true);
setErrorMessage(
showError(
"You don't have the correct access level to view the dashboard"
);
return;
}

const isAuth = await checkAuth(email);
const isAuth = await checkAuth(email, LOG_IN);
if (isAuth) {
history.push('/emailsent');
} else {
setIsError(true);
setErrorMessage(
showError(
'We don’t recognize your email address. Please, create an account.'
);
}
} else {
setIsError(true);
setErrorMessage(
showError(
'We don’t recognize your email address. Please, create an account.'
);
}
} else {
setIsDisabled(true);
setIsError(true);
setErrorMessage('Please enter a valid email address');
}
};

function handleInputChange(e) {
const inputValue = e.currentTarget.value.toString();
if (!inputValue) {
setIsDisabled(true);
setIsError(true);
setErrorMessage('Please enter a valid email address');
showError('Please enter a valid email address');
} else {
setIsDisabled(false);
setIsError(false);
Expand All @@ -117,11 +89,7 @@ const AdminLogin = () => {
<div className="adminlogin-headers">
<h3>Welcome Back!</h3>
</div>
<form
className="form-check-in"
autoComplete="off"
onSubmit={(e) => e.preventDefault()}
>
<form className="form-check-in" autoComplete="off">
<div className="form-row">
<div className="form-input-text">
<label htmlFor="email">Enter your email address:</label>
Expand Down Expand Up @@ -156,4 +124,4 @@ const AdminLogin = () => {
);
};

export default AdminLogin;
export default Auth;
29 changes: 29 additions & 0 deletions client/src/components/auth/HandleAuth.js
Original file line number Diff line number Diff line change
@@ -0,0 +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);

useEffect(() => {
const search = props.location.search;
const params = new URLSearchParams(search);
const api_token = params.get('token');
const isValid = isValidToken(api_token);
setMagicLink(isValid);
}, []);

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

export default HandleAuth;
47 changes: 0 additions & 47 deletions client/src/pages/HandleAuth.js

This file was deleted.

70 changes: 70 additions & 0 deletions client/src/services/user.service.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
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
* @returns user data otherwise null
* @param email user email
* @param auth_origin auth origin 'LOG_IN' or 'CREATE_ACCOUNT'
*/
export async function checkUser(email, auth_origin) {
try {
const response = await fetch(CHECK_USER, {
method: 'POST',
headers: HEADERS,
body: JSON.stringify({ email: email, auth_origin: auth_origin }),
});
return await response.json();
} catch (error) {
console.log('User is not registered in the app');
console.log(error);
return null;
}
}

/**
* Method sent request to the backend to check if user can login in app
* @returns true if user can login otherwise null
* @param email user email
* @param auth_origin auth origin 'LOG_IN' or "CREATE_ACCOUNT'
*/
export async function checkAuth(email, auth_origin) {
try {
const response = await fetch(SIGN_IN, {
method: 'POST',
headers: HEADERS,
body: JSON.stringify({ email: email, auth_origin: auth_origin }),
});
return response.status === 200;
} catch (error) {
console.log('User is not authorized in app');
console.log(error);
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;
}
}
Loading

0 comments on commit 16a3857

Please sign in to comment.