Hotfix: withoutAuth + ajustements UserContext

This commit is contained in:
Divlo 2020-04-08 15:26:18 +02:00
parent 5d048f3010
commit ca0c77a522
7 changed files with 75 additions and 37 deletions

View File

@ -56,7 +56,7 @@ exports.putUser = (req, res, next) => {
logo.mimetype !== 'image/jpeg' || logo.mimetype !== 'image/jpeg' ||
logo.mimetype !== 'image/gif' logo.mimetype !== 'image/gif'
)) { )) {
return errorHandling(next, { message:"Le profil doit avoir une image valide.", statusCode: 400 }); return errorHandling(next, { message:"Le profil doit avoir une image valide (PNG, JPG, GIF) et moins de 5mo.", statusCode: 400 });
} }
const logoName = name + req.userId + uuid.v4() + logo.name; const logoName = name + req.userId + uuid.v4() + logo.name;
// Supprime les anciens logo // Supprime les anciens logo

View File

@ -22,6 +22,7 @@ module.exports = sequelize.define('user', {
}, },
biography: { biography: {
type: Sequelize.TEXT, type: Sequelize.TEXT,
defaultValue: ""
}, },
logo: { logo: {
type: Sequelize.STRING, type: Sequelize.STRING,

View File

@ -14,45 +14,56 @@ function UserContextProvider(props) {
const [messageLogin, setMessageLogin] = useState(""); const [messageLogin, setMessageLogin] = useState("");
useEffect(() => { useEffect(() => {
const user = cookies.get('user'); const newUser = cookies.get('user');
setUser(user); if (newUser != undefined) {
if (user != undefined) {
setIsAuth(true); setIsAuth(true);
setUser(newUser);
} }
}, []); }, []);
const loginUser = ({ email, password }) => { useEffect(() => {
setLoginLoading(true); if (isAuth) {
api.post('/users/login', { email, password }) setMessageLogin('<p class="form-error"><b>Erreur:</b> Vous devez être déconnecter avant de vous connecter.</p>');
.then((response) => { } else {
const user = response.data; setMessageLogin("");
changeUserValue(user); }
setIsAuth(true); }, [isAuth]);
setMessageLogin('<p class="form-success"><b>Succès:</b> Connexion réussi!</p>');
setLoginLoading(false);
})
.catch((error) => {
setMessageLogin(`<p class="form-error"><b>Erreur:</b> ${error.response.data.message}</p>`);
setLoginLoading(false);
setIsAuth(false);
setUser(null);
});
}
const logoutUser = () => { const logoutUser = () => {
cookies.remove('user'); cookies.remove('user', { path: '/' });
setUser(null); setUser(null);
setIsAuth(false); setIsAuth(false);
} }
const changeUserValue = (user) => { const changeUserValue = (newUser) => {
cookies.remove('user'); cookies.remove('user', { path: '/' });
cookies.set('user', user); cookies.set('user', newUser, { path: '/' });
setUser(user); setUser(newUser);
}
const loginUser = ({ email, password }) => {
setLoginLoading(true);
return new Promise(async (next) => {
try {
const response = await api.post('/users/login', { email, password });
const newUser = response.data;
changeUserValue(newUser);
setIsAuth(true);
setMessageLogin('<p class="form-success"><b>Succès:</b> Connexion réussi!</p>');
setLoginLoading(false);
return next({ isSuccess: true, newUser });
} catch (error) {
setMessageLogin(`<p class="form-error"><b>Erreur:</b> ${error.response.data.message}</p>`);
setLoginLoading(false);
setIsAuth(false);
setUser(null);
return next({ isSuccess: false });
}
});
} }
return ( return (
<UserContext.Provider value={{ user, loginUser, logoutUser, loginLoading, messageLogin, isAuth, changeUserValue }}> <UserContext.Provider value={{ user, loginUser, logoutUser, loginLoading, messageLogin, isAuth, changeUserValue, setMessageLogin }}>
{props.children} {props.children}
</UserContext.Provider> </UserContext.Provider>
); );

View File

@ -0,0 +1,19 @@
import { useContext } from 'react';
import { UserContext } from '../contexts/UserContext';
import redirect from '../utils/redirect';
const withoutAuth = (WrappedComponent) => {
const Component = (props) => {
const { isAuth, user } = useContext(UserContext);
if (isAuth) return redirect({}, `/profile/${user.name}`);
return <WrappedComponent { ...props } />;
}
return Component;
}
export default withoutAuth;

View File

@ -5,13 +5,14 @@ import htmlParser from 'html-react-parser';
import Loader from '../components/Loader'; import Loader from '../components/Loader';
import HeadTag from '../components/HeadTag'; import HeadTag from '../components/HeadTag';
import { UserContext } from '../contexts/UserContext'; import { UserContext } from '../contexts/UserContext';
import redirect from '../utils/redirect';
import '../public/css/pages/register-login.css'; import '../public/css/pages/register-login.css';
const Login = () => { const Login = () => {
const router = useRouter(); const router = useRouter();
const [inputState, setInputState] = useState({}); const [inputState, setInputState] = useState({});
const { loginUser, messageLogin, loginLoading } = useContext(UserContext); const { loginUser, messageLogin, loginLoading, isAuth } = useContext(UserContext);
const handleChange = (event) => { const handleChange = (event) => {
const inputStateNew = { ...inputState }; const inputStateNew = { ...inputState };
@ -19,9 +20,14 @@ const Login = () => {
setInputState(inputStateNew); setInputState(inputStateNew);
} }
const handleSubmit = (event) => { const handleSubmit = async (event) => {
event.preventDefault(); event.preventDefault();
loginUser(inputState); if (!isAuth) {
const loginObject = await loginUser(inputState);
if (loginObject.isSuccess) {
redirect({}, `/profile/${loginObject.newUser.name}`);
}
}
} }
return ( return (

View File

@ -21,7 +21,7 @@ const Profile = (props) => {
const publicationDate = `${('0'+createdAt.getDate()).slice(-2)}/${('0'+(createdAt.getMonth()+1)).slice(-2)}/${createdAt.getFullYear()}`; const publicationDate = `${('0'+createdAt.getDate()).slice(-2)}/${('0'+(createdAt.getMonth()+1)).slice(-2)}/${createdAt.getFullYear()}`;
const { isAuth, user, logoutUser } = useContext(UserContext); const { isAuth, user, logoutUser } = useContext(UserContext);
const [isOpen, setIsOpen] = useState(false); const [isOpen, setIsOpen] = useState(false);
let defaultInputState = {}; let defaultInputState = {};
if (isAuth) { if (isAuth) {
@ -81,7 +81,7 @@ const Profile = (props) => {
<FontAwesomeIcon icon={faTimes} style={{ width: '1.5rem', color: 'red' }} /> <FontAwesomeIcon icon={faTimes} style={{ width: '1.5rem', color: 'red' }} />
</span> </span>
<h2 className="text-center">Éditer le profil</h2> <h2 className="text-center">Éditer le profil</h2>
<p className="text-center"><em>(Vous devrez vous reconnecter après la sauvegarde) <br/> Si vous changez votre adresse email, vous devrez la confirmer (vérifier vos emails).</em></p> <p className="text-center"><em>(Vous devrez vous reconnecter après la sauvegarde) <br/> Si vous changez votre adresse email, vous devrez la confirmer comme à l'inscription (vérifier vos emails).</em></p>
</div> </div>
</div> </div>
</div> </div>
@ -110,7 +110,7 @@ const Profile = (props) => {
<div className="form-group"> <div className="form-group">
<label className="form-label" htmlFor="logo">Logo <em>(400x400 recommandé)</em> :</label> <label className="form-label" htmlFor="logo">Logo <em>(400x400 recommandé)</em> :</label>
<br/> <p style={{ margin: 0 }}><em>Si aucun fichier est choisi, le logo ne sera pas modifié.</em></p>
<input onChange={handleChange} accept="image/jpeg,image/jpg,image/png,image/gif" type="file" name="logo" id="logo" /> <input onChange={handleChange} accept="image/jpeg,image/jpg,image/png,image/gif" type="file" name="logo" id="logo" />
</div> </div>

View File

@ -2,8 +2,9 @@ import { Fragment, useState } from 'react';
import htmlParser from 'html-react-parser'; import htmlParser from 'html-react-parser';
import Loader from '../components/Loader'; import Loader from '../components/Loader';
import HeadTag from '../components/HeadTag'; import HeadTag from '../components/HeadTag';
import '../public/css/pages/register-login.css';
import api from '../utils/api'; import api from '../utils/api';
import withoutAuth from '../hoc/withoutAuth';
import '../public/css/pages/register-login.css';
const Register = () => { const Register = () => {
@ -76,4 +77,4 @@ const Register = () => {
</Fragment> </Fragment>
); );
} }
export default Register; export default withoutAuth(Register);