agregar funcionalidades de validaciones en login

This commit is contained in:
Mariela 2022-08-12 18:40:26 -06:00
parent 3fc01cc033
commit 59c0ced918
3 changed files with 292 additions and 125 deletions

View File

@ -174,7 +174,7 @@ const App = () => {
label: 'Inicio',
items: [
{ label: 'Dashboard', icon: 'pi pi-fw pi-home', to: '/' },
{ label: 'Administradores del sistema',icon: PrimeIcons.USERS, to: '/administradoresSistema' },
{ label: 'Administradores del sistema', icon: PrimeIcons.USERS, to: '/administradoresSistema' },
{ label: 'Administradores de comunidad', icon: PrimeIcons.USERS, to: '/administradoresComunidad' },
{ label: 'Comunidades', icon: PrimeIcons.BUILDING, to: '/comunidadesViviendas' },
]
@ -198,11 +198,26 @@ const App = () => {
},
]
const menuLogin = [
{
label: 'Inicio',
items: [
{
label: 'Inicio de sesion',
icon: PrimeIcons.BUILDING,
to: '/login'
},
]
},
]
function menu4() {
if (cookies.type == '1') {
return menu2;
} else if (cookies.type == '2') {
return menu3;
} else {
return menuLogin;
}
}
@ -210,39 +225,39 @@ const App = () => {
{
label: 'Inicio',
items:
[
{
label: 'Administradores del sistema',
icon: PrimeIcons.USERS,
to: '/administradoresSistema',
},
{
label: 'Administradores de comunidad',
icon: PrimeIcons.USERS,
to: '/administradoresComunidad',
},
{
label: 'Guardas de seguridad',
icon: PrimeIcons.LOCK,
to: '/guardasSeguridad',
},
{
label: 'Comunidades',
icon: PrimeIcons.BUILDING,
to: '/comunidadesViviendas',
},
{
label: 'Inquilinos',
icon: PrimeIcons.USER,
to: '/inquilinos'
},
{
label: 'Áreas Comunes de Comunidad',
icon: PrimeIcons.BUILDING,
to: '/areasComunes',
},
{ label: 'Log in', icon: 'pi pi-fw pi-id-card', to: '/logIn' },
],
[
{
label: 'Administradores del sistema',
icon: PrimeIcons.USERS,
to: '/administradoresSistema',
},
{
label: 'Administradores de comunidad',
icon: PrimeIcons.USERS,
to: '/administradoresComunidad',
},
{
label: 'Guardas de seguridad',
icon: PrimeIcons.LOCK,
to: '/guardasSeguridad',
},
{
label: 'Comunidades',
icon: PrimeIcons.BUILDING,
to: '/comunidadesViviendas',
},
{
label: 'Inquilinos',
icon: PrimeIcons.USER,
to: '/inquilinos'
},
{
label: 'Áreas Comunes de Comunidad',
icon: PrimeIcons.BUILDING,
to: '/areasComunes',
},
{ label: 'Log in', icon: 'pi pi-fw pi-id-card', to: '/logIn' },
],
},
{
label: 'UI Components',
@ -395,9 +410,10 @@ const App = () => {
<BrowserRouter>
<Switch>
<Route exact path="/login" component={LoginLocalStorage} />
<div className={wrapperClass} onClick={onWrapperClick}>
<Tooltip ref={copyTooltipRef} target=".block-action-copy" position="bottom" content="Copied to clipboard" event="focus" />
<AppTopbar onToggleMenuClick={onToggleMenuClick} layoutColorMode={layoutColorMode}
@ -409,8 +425,9 @@ const App = () => {
<div className="layout-main-container">
<div className="layout-main">
<Route path="/login" exact component={LoginLocalStorage} />
<Route path="/" exact render={() => <Dashboard colorMode={layoutColorMode} location={location} />} />
<Route path="/formlayout" component={FormLayoutDemo} />
<Route path="/input" component={InputDemo} />
<Route path="/floatlabel" component={FloatLabelDemo} />
@ -439,15 +456,12 @@ const App = () => {
<Route path="/comunidadesViviendas" component={Communities} />
<Route path="/inquilinos" component={Inquilinos} />
<Route path="/areasComunes" component={AreasComunes} />
<Route path="/login" component={LoginLocalStorage} />
</div>
<AppFooter layoutColorMode={layoutColorMode} />
</div>
<AppConfig rippleEffect={ripple} onRippleEffect={onRipple} inputStyle={inputStyle} onInputStyleChange={onInputStyleChange}
layoutMode={layoutMode} onLayoutModeChange={onLayoutModeChange} layoutColorMode={layoutColorMode} onColorModeChange={onColorModeChange} />
<AppConfig />
<CSSTransition classNames="layout-mask" timeout={{ enter: 200, exit: 200 }} in={mobileMenuActive} unmountOnExit>
<div className="layout-mask p-component-overlay"></div>

View File

@ -1,14 +1,17 @@
import React from 'react';
import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import classNames from 'classnames';
import Cookies from 'universal-cookie';
import { Button } from 'primereact/button';
import { Menubar } from 'primereact/menubar';
const cookies = new Cookies();
export const AppTopbar = (props) => {
const [logged, setLogged] = useState(null);
function cerrarSesion() {
function cerrarSesion() {
cookies.remove('id', { path: "/" });
cookies.remove('email', { path: "/" });
cookies.remove('name', { path: "/" });
@ -17,10 +20,46 @@ export const AppTopbar = (props) => {
window.location.href = '/login';
}
useEffect(() => {
if (cookies.get('email')) {
setLogged(true);
} else {
setLogged(false);
};
}, [])
const buttonLogout = () => {
return (
<>
<div className="my-2">
<Button label="Cerrar Sesión"
className="p-button-danger"
onClick={cerrarSesion}
disabled={logged} />
</div>
</>
)
}
const menuProfile = [
{
label: 'Perfil',
icon: 'pi pi-user',
items: [
{
label: 'Cerrar Sesion',
icon: 'pi pi-fw pi-lock',
}
],
},
]
return (
<div className="layout-topbar">
<Link to="/" className="layout-topbar-logo">
<img src={'assets/layout/images/logo-dark.svg' } alt="logo" />
<img src={'images/Logo_Katoikia.svg'} alt="logo" />
<span>KATOIKIA</span>
</Link>
@ -28,33 +67,51 @@ export const AppTopbar = (props) => {
<i className="pi pi-bars"/>
</button> */}
<button
type="button"
className="p-link layout-topbar-menu-button layout-topbar-button"
>
<i className="pi pi-ellipsis-v" />
</button>
<button
type="button"
className="p-link layout-topbar-menu-button layout-topbar-button"
>
<i className="pi pi-ellipsis-v" />
</button>
<ul className="layout-topbar-menu lg:flex origin-top">
{/* <li>
<ul className="layout-topbar-menu lg:flex origin-top">
{/* <li>
<button className="p-link layout-topbar-button" onClick={props.onMobileSubTopbarMenuClick}>
<i className="pi pi-calendar"/>
<span>Events</span>
</button>
</li> */}
{/* <li>
{/* <li>
<button className="p-link layout-topbar-button" onClick={props.onMobileSubTopbarMenuClick}>
<i className="pi pi-cog"/>
<span>Settings</span>
</button>
</li> */}
<li>
<li className='mx-2' hidden={!logged}>
<button className="p-link layout-topbar-button" >
<i className="pi pi-user" />
<span>Profile</span>
<span>Perfil</span>
</button>
<button type="button" onClick={() => cerrarSesion()}>Logout</button>
</li>
<li className='mx-2' hidden={!logged}>
<button className="p-link layout-topbar-button" onClick={cerrarSesion} >
<i className="pi pi-sign-out" />
<span>Cerrar Sesión</span>
</button>
</li>
{/*
<Menubar model={menuProfile} ></Menubar>
</li>
<li hidden={!logged}>
<div className="my-2" >
<Button label="Cerrar Sesión"
className="p-button-danger"
onClick={cerrarSesion}
/>
</div>
</li>*/}
</ul>
</div>
);

View File

@ -1,20 +1,25 @@
import DashboardAdmin from "./DashboardAdmin";
import React, { Component, Fragment } from 'react';
import React, { Component, Fragment, useRef } from 'react';
import Cookies from 'universal-cookie';
import { InputText } from 'primereact/inputtext';
import { Button } from 'primereact/button';
import { Toast } from 'primereact/toast';
const baseUrl = "http://localhost:4000/user/loginUser";
const cookies = new Cookies();
class LoginLocalStorage extends Component {
state = {
form: {
email: '',
password: ''
},
errorMessages:{}
constructor(props) {
super(props);
this.state = {
form: {
email: '',
password: ''
},
errorEmail: false,
errorPassword: false,
logged: null
}
}
handleChange = async e => {
@ -26,6 +31,33 @@ class LoginLocalStorage extends Component {
});
}
validaciones = (data) => {
let error = true;
if (data.email == '') {
this.setState({
errorEmail: true
})
error = true;
} else {
this.setState({
errorEmail: false
})
}
if (data.password == '') {
this.setState({
errorPassword: true
})
error = true;
} else {
this.setState({
errorPassword: false
})
}
return error;
}
iniciarSesion = async () => {
const data = {
email: this.state.form.email,
@ -34,40 +66,65 @@ class LoginLocalStorage extends Component {
console.log(data);
await fetch(baseUrl, {
cache: 'no-cache',
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json'
}
})
.then(response => {
return response.json();
if (!this.validaciones(data)) {
this.setState({
email: true,
password: true
})
.then(response => {
console.log(response.message);
if (response.message) {
const user = response.message;
cookies.set('id', user._id, { path: "/" });
cookies.set('name', user.name, { path: "/" });
cookies.set('email', user.email, { path: "/" });
cookies.set('type', user.user_type, { path: "/" });
if(user.user_type != '1') {
cookies.set('community_id', user.community_id, { path: "/" });
}
alert(`Bienvenido ${user.name}`);
window.location.href = "/";
} else {
alert('El usuario o la contraseña no son correctos');
await fetch(baseUrl, {
cache: 'no-cache',
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json'
}
})
.catch(error => {
console.log(error);
})
.then(response => {
if (response.status != 201)
console.log('Ocurrió un error con el servicio: ' + response.status);
else return response.json();
})
.then(response => {
console.log(response.message);
if (response.message) {
const user = response.message;
cookies.set('id', user._id, { path: "/" });
cookies.set('name', user.name, { path: "/" });
cookies.set('email', user.email, { path: "/" });
cookies.set('type', user.user_type, { path: "/" });
if (user.user_type != '1') {
cookies.set('community_id', user.community_id, { path: "/" });
}
// alert(`Bienvenido ${user.name}`);
document.getElementById('notification').hidden = true;
document.getElementById('notification2').hidden = false;
document.getElementById("message2").innerHTML = `Bienvenido ${user.name}`;
//document.getElementById("message").remove('p-message p-message-error')
// document.getElementById("message").append(`Bienvenido ${user.name}`);
// document.getElementById("message").classList('p-message p-message-success')
// window.location.href = "/";
} else {
document.getElementById('notification2').hidden = true;
document.getElementById('notification').hidden = false;
//alert('El usuario o la contraseña no son correctos');
document.getElementById("message").innerHTML = "El usuario o la contraseña son incorrectos";
// document.getElementById("message").remove('p-message p-message-success')
// document.getElementById("message").append('El usuario o la contraseña son incorrectos');
// document.getElementById("message").add.className('p-message p-message-error')
}
})
.catch(error => {
console.log(error);
})
}
}
componentDidMount() {
@ -77,49 +134,88 @@ class LoginLocalStorage extends Component {
}
renderErrorMessage = (name) =>
name === this.state.errorMessages.name && (
<div className="error">{this.state.errorMessages.message}</div>
);
name === this.state.errorMessages.name && (
<div className="error">{this.state.errorMessages.message}</div>
);
errors = {
email: "Correo requerido",
pass: "Contraseña requerida"
};
errors = {
email: "Correo requerido",
pass: "Contraseña requerida"
};
render() {
return (
<Fragment>
<div className="login-wrapper">
<div className="grid form justify-content-center my-5">
<div className="col-5">
<div className="grid ">
<div className="col-10 xl:col-8">
<div id="notification" className="p-message p-message-error" hidden={true} >
<div className="card">
<h5>Iniciar Sesión</h5>
<div className="p-fluid formgrid grid">
<div className="field col-12">
<label htmlFor="email">Correo electrónico</label>
<InputText id="email"
type="email"
name="email"
onChange={this.handleChange}
placeholder='Correo electrónico' />
{this.renderErrorMessage("email")}
</div>
<div className="field col-12 ">
<label htmlFor="password">Contraseña</label>
<InputText id="password"
type="password"
name="password"
onChange={this.handleChange}
placeholder='Contraseña'
/>
{this.renderErrorMessage("password")}
</div>
<h5 className='card-header' id="message">
</h5>
</div>
</div>
<div id="notification2" className="p-message p-message-success" hidden={true} >
<div className="card">
<h5 className='card-header' id="message2">
</h5>
</div>
</div>
<Button label="Iniciar sesión" type="button" onClick={() => this.iniciarSesion()}></Button>
</div>
<div className="col-10 xl:col-8">
<div className="card">
<h5 className='card-header'>Iniciar Sesión</h5>
<div className="p-fluid formgrid grid">
<div className="field col-12 md:col-12">
<label htmlFor="email">Correo electrónico</label>
<div className="p-0 col-12 md:col-12">
<div className="p-inputgroup">
<span className="p-inputgroup-addon p-button p-icon-input-khaki">
<i className="pi pi-user"></i>
</span>
<InputText id="email"
type="email"
name="email"
onChange={this.handleChange}
placeholder='Correo electrónico'
className={this.state.errorEmail ? 'p-invalid' : ''}
/>
</div>
{this.state.errorEmail && (
<small className="p-invalid">Correo electrónico es requerido</small>
)}
</div>
</div>
<div className="field col-12 md:col-12">
<label htmlFor="v">Contraseña</label>
<div className="p-0 col-12 md:col-12">
<div className="p-inputgroup">
<span className="p-inputgroup-addon p-button p-icon-input-khaki">
<i className="pi pi-lock"></i>
</span>
<InputText id="password"
type="password"
name="password"
onChange={this.handleChange}
placeholder='Contraseña'
className={this.state.errorPassword ? 'p-invalid' : ''}
/>
</div>
{this.state.errorPassword && (
<small className="p-invalid">Contraseña es requerida</small>
)}
</div>
</div>
<Button label="Iniciar sesión" type="button" onClick={() => this.iniciarSesion()}></Button>
</div>
</div>
</div>