Skip to content

Commit

Permalink
ajustes login
Browse files Browse the repository at this point in the history
  • Loading branch information
fell-lucas committed May 5, 2021
1 parent 8056ee2 commit 1f2c868
Show file tree
Hide file tree
Showing 3 changed files with 142 additions and 135 deletions.
103 changes: 52 additions & 51 deletions src/pages/Login/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { Label } from '../../components/Label';
import { apiAuth } from '../../services/api';
import { schema } from './schema';

export default function Login () {
export default function Login() {
const [generalErrors, setGeneralErrors] = useState<string[]>([])
const msgTimeout = 4000

Expand All @@ -26,32 +26,33 @@ export default function Login () {
async function handleLogin(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault()

if(await validate())
if (await validate())
try {
const response = await apiAuth.post('/signin', null, {
params: {
email: data['Email'],
password: data['Senha']
}
})
const response = await apiAuth.post('/signin', null, {
params: {
email: data['Email'],
password: data['Senha']
}
})

localStorage.setItem('token', response.data)
toast('Login efetuado com sucesso.', {autoClose: msgTimeout, type:'success'})
setTimeout(() => {
history.push('/')
}, msgTimeout)
localStorage.setItem('token', response.data)
localStorage.setItem('email', data['Email'])
toast('Login efetuado com sucesso.', { autoClose: msgTimeout, type: 'success' })
setTimeout(() => {
history.push('/')
}, msgTimeout)
} catch (error) {
if(error.response) {
toast(error.response.data, {autoClose: msgTimeout, type: 'error'})
if (error.response) {
toast(error.response.data, { autoClose: msgTimeout, type: 'error' })
} else {
toast('Erro ao conectar com a API.', {autoClose: msgTimeout, 'type': 'error'})
toast('Erro ao conectar com a API.', { autoClose: msgTimeout, 'type': 'error' })
}
}
}

async function validate() {
try {
await schema.validate(data, {abortEarly: false})
await schema.validate(data, { abortEarly: false })
setGeneralErrors([])
return true
} catch (error) {
Expand Down Expand Up @@ -86,10 +87,10 @@ export default function Login () {
<div className="flex flex-col items-end flex-initial h-full bg-red-200 dark:bg-gray-800 justify-end">
<div className="flex-auto m-16">
<h1 className="text-5xl mb-8 text-left font-bold text-red-700 dark:text-red-300">
<Link to="/">Imobiliária</Link>
<Link to="/">Imobiliária</Link>
</h1>
<h1 className="text-2xl text-left font-bold text-red-700 dark:text-red-300">
Descubra imóveis para compra e aluguel na sua área
Descubra imóveis para compra e aluguel na sua área
</h1>
</div>
<div className="flex items-end p-2">
Expand Down Expand Up @@ -119,40 +120,40 @@ export default function Login () {
<div className="flex flex-col w-2/5">
<ToastContainer />
<h1 className="text-3xl font-bold mb-8 dark:text-white">Acesse sua conta</h1>
{ generalErrors[0] &&
(<>
<div className="bg-red-100 dark:bg-gray-900 p-3 rounded-lg mb-3">
<h3 className="text-red-800 dark:text-red-500 font-bold">Campos inválidos:</h3>
{generalErrors.map((e) => (
<FormError key={Math.random()}>{e}</FormError>
))}
</div>
</>)}
{generalErrors[0] &&
(<>
<div className="bg-red-100 dark:bg-gray-900 p-3 rounded-lg mb-3">
<h3 className="text-red-800 dark:text-red-500 font-bold">Campos inválidos:</h3>
{generalErrors.map((e) => (
<FormError key={Math.random()}>{e}</FormError>
))}
</div>
</>)}
<form onSubmit={handleLogin}>
<fieldset>
<Label for="userEmail">Endereço de Email</Label>
<Input
name="userEmail"
type="email"
value={data['Email']}
onChange={e => setData({...data, 'Email': e.target.value})}
/>
</fieldset>
<fieldset className="my-6">
<div className="flex justify-between">
<Label for="userPassword">Senha</Label>
<Link
<fieldset>
<Label for="userEmail">Endereço de Email</Label>
<Input
name="userEmail"
type="email"
value={data['Email']}
onChange={e => setData({ ...data, 'Email': e.target.value })}
/>
</fieldset>
<fieldset className="my-6">
<div className="flex justify-between">
<Label for="userPassword">Senha</Label>
<Link
className="text-red-700 dark:text-red-500"
to="/passwords_reset/new">Esqueceu a senha?</Link>
</div>
<Input
name="userPassword"
type="password"
value={data['Senha']}
onChange={e => setData({...data, 'Senha': e.target.value})}
/>
</fieldset>
<Button type="submit">Enviar</Button>
to="/passwords_reset/new">Esqueceu a senha?</Link>
</div>
<Input
name="userPassword"
type="password"
value={data['Senha']}
onChange={e => setData({ ...data, 'Senha': e.target.value })}
/>
</fieldset>
<Button type="submit">Enviar</Button>
</form>
</div>
</div>
Expand Down
117 changes: 61 additions & 56 deletions src/pages/Profile/index.tsx
Original file line number Diff line number Diff line change
@@ -1,21 +1,22 @@
import React, { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { toast, ToastContainer } from "react-toastify";
import { Button } from "../../components/Button";
import { Input } from "../../components/Input";
import { Label } from "../../components/Label";
import Navbar from "../../components/Navbar";
import { apiUser } from "../../services/api";
import { apiAuth, apiUser } from "../../services/api";

export function Profile() {
// atualmente nao esta funcionando pois os dados nao estao mais sendo salvos
// no localstorage.
const [userName, setUserName] = useState(localStorage.getItem('userName') ?? '')
const [userEmail, setUserEmail] = useState(localStorage.getItem('userEmail') ?? '')
const [userCpf, setUserCpf] = useState(localStorage.getItem('userCpf') ?? '')
const [userPhone, setUserPhone] = useState(localStorage.getItem('userPhone') ?? '')
const [userAddress, setUserAddress] = useState(localStorage.getItem('userAddress') ?? '')

const userId = localStorage.getItem('userId')
const [userName, setUserName] = useState('')
const [userPassword, setUserPassword] = useState('')
const [userEmail, setUserEmail] = useState('')
const [userCpf, setUserCpf] = useState('')
const [userPhone, setUserPhone] = useState('')
const [userAddress, setUserAddress] = useState('')
let userId = ''

async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault()
Expand All @@ -30,41 +31,38 @@ export function Profile() {
"address": userAddress
}

// issues a new request to retrieve user password because
// we're using put instead of patch in the back-end, so I have to
// rebuild an entire user here then send it over for them to update it

// could've saved the user password locally, but not the best idea
try {
const response = await apiUser.get(`/user/customer/find/${userId}`)
data.password = response.data.password
} catch (error) {
alert('Erro ao recuperar dados vitais do usuário.')
}

try {
const response = await apiUser.put('/customer/update', data)

localStorage.setItem('userId', response.data.id)
localStorage.setItem('userName', response.data.name)
localStorage.setItem('userEmail', response.data.email)
localStorage.setItem('userCpf', response.data.cpf)
localStorage.setItem('userPhone', response.data.phone)
localStorage.setItem('userAddress', response.data.address)

alert('Usuário atualizado com sucesso.')
await apiUser.put('/customer/update', data)
toast('Usuário atualizado com sucesso.', { autoClose: 4000, 'type': 'success' })
} catch (error) {
alert('Erro ao atualizar informações do usuário.')
toast('Erro ao atualizar informações do usuário.', { autoClose: 4000, 'type': 'error' })
}
}

useEffect(() => {
Inputmask("999.999.999-99", {autoUnmask: true}).mask('input[name*=cpf i]');
Inputmask("(99) 9999-9999", {autoUnmask: true}).mask('input[name*=phone i]');
async function fetch() {
try {
const response = await apiUser.get(`/customer/find/${localStorage.getItem('email')}`)
console.log(response)
userId = response.data.id
setUserAddress(response.data.address)
setUserEmail(response.data.email)
setUserName(response.data.name)
setUserCpf(response.data.cpf)
setUserPhone(response.data.phone)
setUserPassword(response.data.password)
} catch (error) {
toast('Erro ao recuperar dados vitais do usuário.', { autoClose: 4000, 'type': 'error' })
}
}
fetch()
Inputmask("999.999.999-99", { autoUnmask: true }).mask('input[name*=cpf i]');
Inputmask("(99) 9999-9999", { autoUnmask: true }).mask('input[name*=phone i]');
}, [])

return (
<>
<ToastContainer />
<div className="max-w-7xl m-auto h-screen">
<div className="flex flex-col gap-12 items-center">
<Navbar />
Expand Down Expand Up @@ -117,8 +115,8 @@ export function Profile() {
value={userPhone}
onChange={e => {
e.target.value.length > 10 ?
Inputmask("(99) 9999[9]-9999", {autoUnmask: true}).mask('input[name*=phone i]') :
Inputmask("(99) 9999-9999[9]", {autoUnmask: true, greedy: false}).mask('input[name*=phone i]')
Inputmask("(99) 9999[9]-9999", { autoUnmask: true }).mask('input[name*=phone i]') :
Inputmask("(99) 9999-9999[9]", { autoUnmask: true, greedy: false }).mask('input[name*=phone i]')
setUserPhone(e.target.value)
}}
name="userPhone"
Expand Down Expand Up @@ -158,50 +156,57 @@ export function ChangePw() {
e.preventDefault()
let actualPassword = ''

const data = {
"id": '',
"email": '',
"name": '',
"password": newPassword,
"cpf": '',
"phone": '',
"address": '',
}

try {
const response = await apiUser.get(`/user/customer/find/${userId}`)
const response = await apiUser.get(`/customer/find/${localStorage.getItem('email')}`)
actualPassword = response.data.password
data['id'] = response.data.id
data['email'] = response.data.email
data['name'] = response.data.name
data['cpf'] = response.data.cpf
data['phone'] = response.data.phone
data['address'] = response.data.address
} catch (error) {
alert('Erro ao recuperar dados vitais do usuário.')
toast('Erro ao recuperar dados vitais do usuário.', { autoClose: 4000, 'type': 'error' })
return
}

if(!newPassword || !newPasswordRepeat || !password) {
alert('Preencha os campos vazios.')
if (!newPassword || !newPasswordRepeat || !password) {
toast('Preencha os campos vazios.', { autoClose: 4000, 'type': 'error' })
return
}

if(password !== actualPassword) {
alert('A senha atual está incorreta.')
if (password !== actualPassword) {
toast('A senha atual está incorreta.', { autoClose: 4000, 'type': 'error' })
return
}


if(newPassword !== newPasswordRepeat) {
alert('As senhas não são iguais.')
if (newPassword !== newPasswordRepeat) {
toast('As senhas não são iguais.', { autoClose: 4000, 'type': 'error' })
return
}

const data = {
"id": userId,
"email": localStorage.getItem('userEmail'),
"name": localStorage.getItem('userName'),
"password": newPassword,
"cpf": localStorage.getItem('userCpf'),
"phone": localStorage.getItem('userPhone'),
"address": localStorage.getItem('userAddress')
}


try {
await apiUser.put('/customer/update', data)
alert('Senha atualizada com sucesso.')
toast('Senha atualizada com sucesso.', { autoClose: 4000, 'type': 'success' })
} catch (error) {
alert('Erro ao atualizar a senha.')
toast('Erro ao atualizar a senha.', { autoClose: 4000, 'type': 'success' })
}
}

return (
<>
<ToastContainer />
<div className="max-w-7xl m-auto h-screen">
<div className="flex flex-col gap-12 items-center">
<Navbar />
Expand Down
Loading

0 comments on commit 1f2c868

Please sign in to comment.