Skip to content

Commit

Permalink
[#87] authorization
Browse files Browse the repository at this point in the history
  • Loading branch information
asiaziola committed Apr 3, 2021
1 parent 33bfa04 commit e4fdcc2
Show file tree
Hide file tree
Showing 8 changed files with 76 additions and 35 deletions.
6 changes: 3 additions & 3 deletions client/package-lock.json

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

3 changes: 2 additions & 1 deletion client/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,10 @@
]
},
"devDependencies": {
"@types/history": "^4.7.3",
"@types/react-router-dom": "^5.1.7",
"customize-cra": "^1.0.0",
"react-app-rewired": "^2.1.8",
"@types/react-router-dom": "^5.1.7",
"react-router-dom": "^5.2.0"
},
"proxy": "http://localhost:3001"
Expand Down
40 changes: 40 additions & 0 deletions client/src/PrivateRoute.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import React, { useEffect, useState } from 'react';
import axios from 'axios';
import { Redirect, Route } from 'react-router-dom';

const PrivateRoute = ({ ...props }: any) => {
const [isAuthenticated, setIsAuthenticated] = useState(false);
const [isLoading, setIsLoading] = useState(true);

useEffect(() => {
const checkAuth = async () => {
const result = await axios
.get('/api/me')
.then((res) => {
if (res.status === 200) {
return true;
} else {
return false;
}
})
.catch((err) => {
return false;
});

setIsAuthenticated(result);
setIsLoading(false);
};
checkAuth();
}, []);

if (isLoading) {
return <div></div>;
} else {
if (isAuthenticated) {
return <Route {...props} />;
} else {
return <Redirect to={{ pathname: '/login', state: { from: props.location } }} />;
}
}
};
export default PrivateRoute;
27 changes: 2 additions & 25 deletions client/src/components/Form/Form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,30 +32,7 @@ interface IFormInput {
termsInput: string;
}

const handleGoogleRedirect = () => {
const requestOptions = {
method: 'GET',
headers: { 'Content-Type': 'application/json' },
mode: 'no-cors' as RequestMode
};

fetch(`/api/google`, requestOptions)
.then((response) => {
window.location.href = `/`;
})
.catch((err) => {
console.error(err);
});
};

const Form = ({
error,
isregister,
onUsernameChange,
onEmailChange,
onPasswordChange,
onSubmit
}: FormProps): ReactElement => {
const Form = ({ error, isregister, onUsernameChange, onEmailChange, onPasswordChange, onSubmit }: FormProps) => {
const { handleSubmit, control, errors, watch } = useForm<IFormInput>();
const emailWatch: string = watch(`emailInput`);
const usernameWatch: string = watch(`usernameInput`);
Expand Down Expand Up @@ -93,7 +70,7 @@ const Form = ({
spacing={1}
mt={4}
>
<StyledButtonGoogle onClick={() => handleGoogleRedirect()} variant="outlined">
<StyledButtonGoogle onClick={() => window.open('/api/google', '_self')} variant="outlined">
<Search
css={css`
margin-right: 10px;
Expand Down
11 changes: 6 additions & 5 deletions client/src/views/App/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import Register from '../Register/Register';
import SearchResultsComponent from '../../components/SearchResults/SearchResultsComponent';
import { css } from '@emotion/react';
import { CreateCollection } from '../../components/CreateCollection/CreateCollection';
import PrivateRoute from '../../PrivateRoute';

const App = (): ReactElement => {
return (
Expand All @@ -24,14 +25,14 @@ const App = (): ReactElement => {
`}
>
<Switch>
<Route exact path="/about" component={About} />
<PrivateRoute exact path="/about" component={About} />
<Route exact path="/" component={Home} />
<Route exact path="/create" component={CreateCollection} />
<Route exact path="/profil" component={ProfileComponent} />
<PrivateRoute exact path="/create" component={CreateCollection} />
<PrivateRoute exact path="/profile" component={ProfileComponent} />
<Route exact path="/register" component={Register} />
<Route exact path="/login" component={Login} />
<Route exact path="/flashcardCollections" component={HomeView} />
<Route path="/search/:search?" component={SearchResultsComponent} />
<PrivateRoute exact path="/flashcardCollections" component={HomeView} />
<PrivateRoute path="/search/:search?" component={SearchResultsComponent} />
<Route component={NotFound} />
</Switch>
</div>
Expand Down
9 changes: 8 additions & 1 deletion client/src/views/Login/Login.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,16 @@ import React, { useState } from 'react';
import Form from '../../components/Form/Form';
import axios from 'axios';
import { useForm } from 'react-hook-form';
import { useHistory, useLocation } from 'react-router-dom';

const Login = () => {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const { errors, setError } = useForm();
const history = useHistory();
const location = useLocation();
const { from } = location.state || { from: { pathname: '/' } };

const handleSubmit = () => {
const user = {
email: email,
Expand All @@ -20,7 +25,9 @@ const Login = () => {
},
data: user
})
.then((response) => (window.location.href = `/`))
.then((response) => {
history.replace(from);
})
.catch((error) => {
setError('server', {
type: 'server',
Expand Down
3 changes: 3 additions & 0 deletions server/src/routes/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import passport from 'passport';
import { runNotificationService } from '../services/NotificationService';
import search from './search';
import session from '../routes/Session';
import me from './me';
import * as path from 'path';

const isAuthenticated = passport.authenticate('jwt', { session: false });
Expand Down Expand Up @@ -44,6 +45,8 @@ router.use('/api/session', isAuthenticated, session);

router.use('/api/search', isAuthenticated, search);

router.use('/api/me', isAuthenticated, me);

// for any other requests, send `index.html` as a response
router.use(serveStatic(publicPath));
router.use('*', (req, res) => {
Expand Down
12 changes: 12 additions & 0 deletions server/src/routes/me.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import express, { Request, Response } from 'express';
const router = express.Router();

router.get('/', async (req: Request, res: Response, next) => {
try {
res.send(200);
} catch (error) {
next(error);
}
});

export default router;

0 comments on commit e4fdcc2

Please sign in to comment.