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', label: 'Inicio',
items: [ items: [
{ label: 'Dashboard', icon: 'pi pi-fw pi-home', to: '/' }, { 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: 'Administradores de comunidad', icon: PrimeIcons.USERS, to: '/administradoresComunidad' },
{ label: 'Comunidades', icon: PrimeIcons.BUILDING, to: '/comunidadesViviendas' }, { 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() { function menu4() {
if (cookies.type == '1') { if (cookies.type == '1') {
return menu2; return menu2;
} else if (cookies.type == '2') { } else if (cookies.type == '2') {
return menu3; return menu3;
} else {
return menuLogin;
} }
} }
@ -210,39 +225,39 @@ const App = () => {
{ {
label: 'Inicio', label: 'Inicio',
items: items:
[ [
{ {
label: 'Administradores del sistema', label: 'Administradores del sistema',
icon: PrimeIcons.USERS, icon: PrimeIcons.USERS,
to: '/administradoresSistema', to: '/administradoresSistema',
}, },
{ {
label: 'Administradores de comunidad', label: 'Administradores de comunidad',
icon: PrimeIcons.USERS, icon: PrimeIcons.USERS,
to: '/administradoresComunidad', to: '/administradoresComunidad',
}, },
{ {
label: 'Guardas de seguridad', label: 'Guardas de seguridad',
icon: PrimeIcons.LOCK, icon: PrimeIcons.LOCK,
to: '/guardasSeguridad', to: '/guardasSeguridad',
}, },
{ {
label: 'Comunidades', label: 'Comunidades',
icon: PrimeIcons.BUILDING, icon: PrimeIcons.BUILDING,
to: '/comunidadesViviendas', to: '/comunidadesViviendas',
}, },
{ {
label: 'Inquilinos', label: 'Inquilinos',
icon: PrimeIcons.USER, icon: PrimeIcons.USER,
to: '/inquilinos' to: '/inquilinos'
}, },
{ {
label: 'Áreas Comunes de Comunidad', label: 'Áreas Comunes de Comunidad',
icon: PrimeIcons.BUILDING, icon: PrimeIcons.BUILDING,
to: '/areasComunes', to: '/areasComunes',
}, },
{ label: 'Log in', icon: 'pi pi-fw pi-id-card', to: '/logIn' }, { label: 'Log in', icon: 'pi pi-fw pi-id-card', to: '/logIn' },
], ],
}, },
{ {
label: 'UI Components', label: 'UI Components',
@ -395,9 +410,10 @@ const App = () => {
<BrowserRouter> <BrowserRouter>
<Switch> <Switch>
<Route exact path="/login" component={LoginLocalStorage} />
<div className={wrapperClass} onClick={onWrapperClick}> <div className={wrapperClass} onClick={onWrapperClick}>
<Tooltip ref={copyTooltipRef} target=".block-action-copy" position="bottom" content="Copied to clipboard" event="focus" /> <Tooltip ref={copyTooltipRef} target=".block-action-copy" position="bottom" content="Copied to clipboard" event="focus" />
<AppTopbar onToggleMenuClick={onToggleMenuClick} layoutColorMode={layoutColorMode} <AppTopbar onToggleMenuClick={onToggleMenuClick} layoutColorMode={layoutColorMode}
@ -409,8 +425,9 @@ const App = () => {
<div className="layout-main-container"> <div className="layout-main-container">
<div className="layout-main"> <div className="layout-main">
<Route path="/login" exact component={LoginLocalStorage} />
<Route path="/" exact render={() => <Dashboard colorMode={layoutColorMode} location={location} />} /> <Route path="/" exact render={() => <Dashboard colorMode={layoutColorMode} location={location} />} />
<Route path="/formlayout" component={FormLayoutDemo} /> <Route path="/formlayout" component={FormLayoutDemo} />
<Route path="/input" component={InputDemo} /> <Route path="/input" component={InputDemo} />
<Route path="/floatlabel" component={FloatLabelDemo} /> <Route path="/floatlabel" component={FloatLabelDemo} />
@ -439,15 +456,12 @@ const App = () => {
<Route path="/comunidadesViviendas" component={Communities} /> <Route path="/comunidadesViviendas" component={Communities} />
<Route path="/inquilinos" component={Inquilinos} /> <Route path="/inquilinos" component={Inquilinos} />
<Route path="/areasComunes" component={AreasComunes} /> <Route path="/areasComunes" component={AreasComunes} />
<Route path="/login" component={LoginLocalStorage} />
</div> </div>
<AppFooter layoutColorMode={layoutColorMode} /> <AppFooter layoutColorMode={layoutColorMode} />
</div> </div>
<AppConfig rippleEffect={ripple} onRippleEffect={onRipple} inputStyle={inputStyle} onInputStyleChange={onInputStyleChange} <AppConfig />
layoutMode={layoutMode} onLayoutModeChange={onLayoutModeChange} layoutColorMode={layoutColorMode} onColorModeChange={onColorModeChange} />
<CSSTransition classNames="layout-mask" timeout={{ enter: 200, exit: 200 }} in={mobileMenuActive} unmountOnExit> <CSSTransition classNames="layout-mask" timeout={{ enter: 200, exit: 200 }} in={mobileMenuActive} unmountOnExit>
<div className="layout-mask p-component-overlay"></div> <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 { Link } from 'react-router-dom';
import classNames from 'classnames'; import classNames from 'classnames';
import Cookies from 'universal-cookie'; import Cookies from 'universal-cookie';
import { Button } from 'primereact/button';
import { Menubar } from 'primereact/menubar';
const cookies = new Cookies(); const cookies = new Cookies();
export const AppTopbar = (props) => { export const AppTopbar = (props) => {
const [logged, setLogged] = useState(null);
function cerrarSesion() {
function cerrarSesion() {
cookies.remove('id', { path: "/" }); cookies.remove('id', { path: "/" });
cookies.remove('email', { path: "/" }); cookies.remove('email', { path: "/" });
cookies.remove('name', { path: "/" }); cookies.remove('name', { path: "/" });
@ -17,10 +20,46 @@ export const AppTopbar = (props) => {
window.location.href = '/login'; 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 ( return (
<div className="layout-topbar"> <div className="layout-topbar">
<Link to="/" className="layout-topbar-logo"> <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> <span>KATOIKIA</span>
</Link> </Link>
@ -28,33 +67,51 @@ export const AppTopbar = (props) => {
<i className="pi pi-bars"/> <i className="pi pi-bars"/>
</button> */} </button> */}
<button <button
type="button" type="button"
className="p-link layout-topbar-menu-button layout-topbar-button" className="p-link layout-topbar-menu-button layout-topbar-button"
> >
<i className="pi pi-ellipsis-v" /> <i className="pi pi-ellipsis-v" />
</button> </button>
<ul className="layout-topbar-menu lg:flex origin-top"> <ul className="layout-topbar-menu lg:flex origin-top">
{/* <li> {/* <li>
<button className="p-link layout-topbar-button" onClick={props.onMobileSubTopbarMenuClick}> <button className="p-link layout-topbar-button" onClick={props.onMobileSubTopbarMenuClick}>
<i className="pi pi-calendar"/> <i className="pi pi-calendar"/>
<span>Events</span> <span>Events</span>
</button> </button>
</li> */} </li> */}
{/* <li> {/* <li>
<button className="p-link layout-topbar-button" onClick={props.onMobileSubTopbarMenuClick}> <button className="p-link layout-topbar-button" onClick={props.onMobileSubTopbarMenuClick}>
<i className="pi pi-cog"/> <i className="pi pi-cog"/>
<span>Settings</span> <span>Settings</span>
</button> </button>
</li> */} </li> */}
<li> <li className='mx-2' hidden={!logged}>
<button className="p-link layout-topbar-button" > <button className="p-link layout-topbar-button" >
<i className="pi pi-user" /> <i className="pi pi-user" />
<span>Profile</span> <span>Perfil</span>
</button> </button>
<button type="button" onClick={() => cerrarSesion()}>Logout</button>
</li> </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> </ul>
</div> </div>
); );

View File

@ -1,20 +1,25 @@
import DashboardAdmin from "./DashboardAdmin"; import DashboardAdmin from "./DashboardAdmin";
import React, { Component, Fragment } from 'react'; import React, { Component, Fragment, useRef } from 'react';
import Cookies from 'universal-cookie'; import Cookies from 'universal-cookie';
import { InputText } from 'primereact/inputtext'; import { InputText } from 'primereact/inputtext';
import { Button } from 'primereact/button'; import { Button } from 'primereact/button';
import { Toast } from 'primereact/toast';
const baseUrl = "http://localhost:4000/user/loginUser"; const baseUrl = "http://localhost:4000/user/loginUser";
const cookies = new Cookies(); const cookies = new Cookies();
class LoginLocalStorage extends Component { class LoginLocalStorage extends Component {
state = { constructor(props) {
form: { super(props);
email: '', this.state = {
password: '' form: {
}, email: '',
errorMessages:{} password: ''
},
errorEmail: false,
errorPassword: false,
logged: null
}
} }
handleChange = async e => { 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 () => { iniciarSesion = async () => {
const data = { const data = {
email: this.state.form.email, email: this.state.form.email,
@ -34,40 +66,65 @@ class LoginLocalStorage extends Component {
console.log(data); console.log(data);
await fetch(baseUrl, { if (!this.validaciones(data)) {
cache: 'no-cache', this.setState({
method: 'POST', email: true,
body: JSON.stringify(data), password: true
headers: {
'Content-Type': 'application/json'
}
})
.then(response => {
return response.json();
}) })
.then(response => { await fetch(baseUrl, {
console.log(response.message); cache: 'no-cache',
if (response.message) { method: 'POST',
const user = response.message; body: JSON.stringify(data),
cookies.set('id', user._id, { path: "/" }); headers: {
cookies.set('name', user.name, { path: "/" }); 'Content-Type': 'application/json'
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');
} }
}) })
.catch(error => { .then(response => {
console.log(error); 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() { componentDidMount() {
@ -77,49 +134,88 @@ class LoginLocalStorage extends Component {
} }
renderErrorMessage = (name) => renderErrorMessage = (name) =>
name === this.state.errorMessages.name && ( name === this.state.errorMessages.name && (
<div className="error">{this.state.errorMessages.message}</div> <div className="error">{this.state.errorMessages.message}</div>
); );
errors = { errors = {
email: "Correo requerido", email: "Correo requerido",
pass: "Contraseña requerida" pass: "Contraseña requerida"
}; };
render() { render() {
return ( return (
<Fragment> <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"> <div className="card">
<h5>Iniciar Sesión</h5> <h5 className='card-header' id="message">
<div className="p-fluid formgrid grid"> </h5>
<div className="field col-12"> </div>
<label htmlFor="email">Correo electrónico</label> </div>
<InputText id="email" <div id="notification2" className="p-message p-message-success" hidden={true} >
type="email" <div className="card">
name="email" <h5 className='card-header' id="message2">
onChange={this.handleChange} </h5>
placeholder='Correo electrónico' /> </div>
{this.renderErrorMessage("email")} </div>
</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>
<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>
<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> </div>
</div> </div>