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/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;
// Supprime les anciens logo

View File

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

View File

@ -14,45 +14,56 @@ function UserContextProvider(props) {
const [messageLogin, setMessageLogin] = useState("");
useEffect(() => {
const user = cookies.get('user');
setUser(user);
if (user != undefined) {
const newUser = cookies.get('user');
if (newUser != undefined) {
setIsAuth(true);
setUser(newUser);
}
}, []);
const loginUser = ({ email, password }) => {
setLoginLoading(true);
api.post('/users/login', { email, password })
.then((response) => {
const user = response.data;
changeUserValue(user);
setIsAuth(true);
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);
});
}
useEffect(() => {
if (isAuth) {
setMessageLogin('<p class="form-error"><b>Erreur:</b> Vous devez être déconnecter avant de vous connecter.</p>');
} else {
setMessageLogin("");
}
}, [isAuth]);
const logoutUser = () => {
cookies.remove('user');
cookies.remove('user', { path: '/' });
setUser(null);
setIsAuth(false);
}
const changeUserValue = (user) => {
cookies.remove('user');
cookies.set('user', user);
setUser(user);
const changeUserValue = (newUser) => {
cookies.remove('user', { path: '/' });
cookies.set('user', newUser, { path: '/' });
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 (
<UserContext.Provider value={{ user, loginUser, logoutUser, loginLoading, messageLogin, isAuth, changeUserValue }}>
<UserContext.Provider value={{ user, loginUser, logoutUser, loginLoading, messageLogin, isAuth, changeUserValue, setMessageLogin }}>
{props.children}
</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 HeadTag from '../components/HeadTag';
import { UserContext } from '../contexts/UserContext';
import redirect from '../utils/redirect';
import '../public/css/pages/register-login.css';
const Login = () => {
const router = useRouter();
const [inputState, setInputState] = useState({});
const { loginUser, messageLogin, loginLoading } = useContext(UserContext);
const router = useRouter();
const [inputState, setInputState] = useState({});
const { loginUser, messageLogin, loginLoading, isAuth } = useContext(UserContext);
const handleChange = (event) => {
const inputStateNew = { ...inputState };
@ -19,9 +20,14 @@ const Login = () => {
setInputState(inputStateNew);
}
const handleSubmit = (event) => {
const handleSubmit = async (event) => {
event.preventDefault();
loginUser(inputState);
if (!isAuth) {
const loginObject = await loginUser(inputState);
if (loginObject.isSuccess) {
redirect({}, `/profile/${loginObject.newUser.name}`);
}
}
}
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 { isAuth, user, logoutUser } = useContext(UserContext);
const [isOpen, setIsOpen] = useState(false);
const [isOpen, setIsOpen] = useState(false);
let defaultInputState = {};
if (isAuth) {
@ -81,7 +81,7 @@ const Profile = (props) => {
<FontAwesomeIcon icon={faTimes} style={{ width: '1.5rem', color: 'red' }} />
</span>
<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>
@ -110,7 +110,7 @@ const Profile = (props) => {
<div className="form-group">
<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" />
</div>

View File

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