Skip to content

Commit

Permalink
Merge pull request #734 from basedosdados/feat/active-account-email
Browse files Browse the repository at this point in the history
Feat/active account email
  • Loading branch information
AldemirLucas authored Dec 21, 2023
2 parents 3de382f + 1a58f4f commit ac36765
Show file tree
Hide file tree
Showing 7 changed files with 167 additions and 65 deletions.
15 changes: 15 additions & 0 deletions next/pages/api/user/activeAccount.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import axios from "axios";

const API_URL= `${process.env.NEXT_PUBLIC_API_URL}/account/activate`

export default async function activeAccount(
id,
token
) {
try {
const res = await axios.post(`${API_URL}/${id}/${token}/`)
return res
} catch (error) {
console.error(error)
}
}
4 changes: 3 additions & 1 deletion next/pages/api/user/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import getFullUser from "./getFullUser";
import updateProfile from "./updateProfile";
import updateUser from "./updateUser";
import updatePassword from "./updatePassword";
import activeAccount from "./activeAccount";

export {
getToken,
Expand All @@ -21,5 +22,6 @@ export {
getFullUser,
updateProfile,
updateUser,
updatePassword
updatePassword,
activeAccount
}
8 changes: 4 additions & 4 deletions next/pages/api/user/updateUser.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ const API_URL= `${process.env.NEXT_PUBLIC_API_URL}/api/v1/graphql`

export default async function updateUser({
id,
email,
username,
email = "",
username = "",
}) {
let token = cookies.get("token") || ""

Expand All @@ -23,8 +23,8 @@ export default async function updateUser({
CreateUpdateAccount (input:
{
id: "${id}"
email: "${email}"
username: "${username}"
${email === "" ? "" : `email: "${email}"`}
${username === "" ? "" : `username: "${username}"`}
}
)
{
Expand Down
122 changes: 74 additions & 48 deletions next/pages/user/[username].js
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,8 @@ import {
getFullUser,
updateProfile,
refreshToken,
updatePassword
updatePassword,
updateUser
} from "../api/user";

import Exclamation from "../../public/img/icons/exclamationIcon";
Expand Down Expand Up @@ -505,32 +506,36 @@ const ProfileConfiguration = ({ userInfo }) => {

const Account = ({ userInfo }) => {
const emailModal = useDisclosure()
const usernameModal = useDisclosure()
const eraseModalAccount = useDisclosure()
const [emailSent, setEmailSent] = useState(false)
const [showPassword, setShowPassword] = useState(true)

const [formData, setFormData] = useState({})
const [errors, setErrors] = useState({})
const [isLoading, setIsLoading] = useState(true)

useEffect(() => {
if(Object.keys(userInfo).length === 0) return null

setFormData({
username: userInfo?.username,
})

setTimeout(() => {
setIsLoading(false)
}, [1000])
}, [userInfo])

const handleInputChange = (e) => {
setFormData((prevState) => ({
...prevState,
[e.target.name]: e.target.value,
}))
}

async function submitUpdate() {
const reg = new RegExp("(?<=:).*")
const [ id ] = reg.exec(userInfo?.id)
const form = {id: id, username: formData.username}

const result = await updateUser(form)

if(result?.errors?.length === 0) return location.reload(true)

if(result?.errors?.length > 0) {
setErrors({username: "Nome de usuário inválido ou já existe uma conta com este nome de usuário."})
}
}

return (
<Stack spacing="24px">
<ModalGeneral
Expand Down Expand Up @@ -703,6 +708,50 @@ instruções enviadas no e-mail para completar a alteração.</ExtraInfoTextForm
}
</ModalGeneral>

<ModalGeneral
isOpen={usernameModal.isOpen}
onClose={usernameModal.onClose}
>
<Stack spacing={0} marginBottom="16px">
<SectionTitle
lineHeight="40px"
>Alterar nome de usuário</SectionTitle>
<ModalCloseButton
fontSize="14px"
top="34px"
right="26px"
_hover={{backgroundColor: "transparent", color:"#42B0FF"}}
/>
</Stack>

<FormControl isInvalid={!!errors.username}>
<LabelTextForm text="Novo nome de usuário"/>
<InputForm
id="username"
name="username"
value={formData.username}
onChange={handleInputChange}
fontFamily="ubuntu"
height="40px"
fontSize="14px"
borderRadius="16px"
_invalid={{boxShadow:"0 0 0 2px #D93B3B"}}
/>
<FormErrorMessage fontSize="12px" color="#D93B3B" display="flex" flexDirection="row" gap="4px" alignItems="flex-start">
<Exclamation marginTop="3px" fill="#D93B3B"/>{errors.username}
</FormErrorMessage>
</FormControl>

<RoundedButton
marginTop="16px"
borderRadius="30px"
_hover={{transform: "none", opacity: 0.8}}
onClick={() => submitUpdate(formData)}
>
Atualizar nome de usuário
</RoundedButton>
</ModalGeneral>

<ModalGeneral
isOpen={eraseModalAccount.isOpen}
onClose={eraseModalAccount.onClose}
Expand Down Expand Up @@ -778,7 +827,7 @@ instruções enviadas no e-mail para completar a alteração.</ExtraInfoTextForm
>Alterar e-mail</Link>
</Box> */}

{/* <Box>
<Box>
<TitleTextForm>Nome de usuário</TitleTextForm>
<Text
color="#6F6F6F"
Expand All @@ -787,39 +836,17 @@ instruções enviadas no e-mail para completar a alteração.</ExtraInfoTextForm
fontWeight="400"
lineHeight="27px"
letterSpacing="0.3px"
>dadinho</Text>
>{userInfo.username}</Text>
<Link
color="#42B0FF"
fontFamily="ubuntu"
fontWeight="500"
fontSize="16px"
lineHeight="30px"
letterSpacing="0.2px"
onClick={() => emailModal.onOpen()}
>Alterar nome de usuário</Link>
</Box> */}

{/* <FormControl isInvalid={!!errors.firstName}>
<LabelTextForm text="Nome de usuário"/>
<SkStack isLoaded={!isLoading} maxWidth="400px">
<InputForm
id="username"
name="username"
value={formData.username}
onChange={handleInputChange}
fontFamily="ubuntu"
height="40px"
fontSize="14px"
borderRadius="16px"
maxWidth="400px"
_placeholder={{color: "#A3A3A3"}}
_invalid={{boxShadow:"0 0 0 2px #D93B3B"}}
/>
</SkStack>
<FormErrorMessage fontSize="12px" color="#D93B3B" display="flex" flexDirection="row" gap="4px" alignItems="flex-start">
<Exclamation marginTop="3px" fill="#D93B3B"/>{errors.firstName}
</FormErrorMessage>
</FormControl> */}
onClick={() => usernameModal.onOpen()}
>Alterar Nome de usuário</Link>
</Box>

<Box>
<TitleTextForm>Exportar dados da conta</TitleTextForm>
Expand Down Expand Up @@ -901,14 +928,14 @@ const NewPassword = ({ userInfo }) => {
if(Object.keys(regexPassword).length > 0) validationErrors.regexPassword = regexPassword

if(formData.password === "") {
validationErrors.password = "Confirmar a senha atual é necessário"
validationErrors.password = "Por favor, insira a senha."
}

let getTokenPassword
if(formData.password !== "") {
getTokenPassword = await getSimpleToken({email: userInfo.email, password: formData.password})
if(getTokenPassword?.tokenAuth === null || result?.errors?.length > 0) {
validationErrors.password = "Senha incorreta"
validationErrors.password = "A senha está incorreta. Por favor, tente novamente."
}
}
setErrors(validationErrors)
Expand Down Expand Up @@ -1606,8 +1633,7 @@ const PlansAndPayment = ({ userData }) => {
)
}

const Accesses = () => {

const Accesses = ({ userInfo }) => {
return (
<Stack spacing="24px">
<Stack alignItems="end">
Expand Down Expand Up @@ -1691,7 +1717,7 @@ const Accesses = () => {
overflow="hidden"
top="9px"
>
<Image width="100%" height="100%" src="https://storage.googleapis.com/basedosdados-website/equipe/sem_foto.png"/>
<Image width="100%" height="100%" src={userInfo?.picture ? userInfo?.picture :"https://storage.googleapis.com/basedosdados-website/equipe/sem_foto.png"}/>
</Box>
<Text
marginLeft={isMobileMod() ? "44px !important" : "60px !important"}
Expand All @@ -1703,7 +1729,7 @@ const Accesses = () => {
letterSpacing="0.3px"
height="27px"
isTruncated
>Dadinho</Text>
>{userInfo?.username}</Text>
<Text
marginLeft={isMobileMod() ? "44px !important" : "60px !important"}
color="#6F6F6F"
Expand All @@ -1714,7 +1740,7 @@ const Accesses = () => {
letterSpacing="0.3px"
height="27px"
isTruncated
>[email protected]</Text>
>{userInfo?.email}</Text>
</Stack>
</GridItem>

Expand Down Expand Up @@ -1851,7 +1877,7 @@ export default function UserPage({ fullUser }) {
{sectionSelected === 1 && <Account userInfo={userInfo}/>}
{sectionSelected === 2 && <NewPassword userInfo={userInfo}/>}
{sectionSelected === 3 && <PlansAndPayment userData={userData}/>}
{sectionSelected === 4 && <Accesses/>}
{sectionSelected === 4 && <Accesses userInfo={userInfo}/>}
</Stack>
</Stack>
</Stack>
Expand Down
65 changes: 65 additions & 0 deletions next/pages/user/activate-account.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import {
Stack,
} from "@chakra-ui/react";
import { useState, useEffect } from "react";
import { activeAccount } from "../api/user";

import Display from "../../components/atoms/Display";
import { isMobileMod } from "../../hooks/useCheckMobile.hook"
import { MainPageTemplate } from "../../components/templates/main";

import { EmailConfirmImage, EmailRecoveryImage } from "../../public/img/emailImage";

export async function getServerSideProps(context) {
const { query } = context

const result = await activeAccount(query.q, query.p)
const data = result?.status || ""

return {
props: {
data
}
}
}

export default function ActiveAccount({ data }) {
return (
<MainPageTemplate display="flex" justifyContent="center" cleanTemplate>
<Stack
display="flex"
justifyContent="center"
width="510px"
height="100%"
marginTop={isMobileMod() ? "150px" : "50px"}
marginX="27px"
spacing="40px"
alignItems="center"
>
{data === 200 ?
<EmailConfirmImage justifyContent="center" marginBottom="8px"/>
:
<EmailRecoveryImage justifyContent="center" marginBottom="8px"/>
}

{data === 200 ?
<Display
fontSize={isMobileMod() ? "28px" : "34px"}
lineHeight={isMobileMod() ? "36px" : "44px"}
letterSpacing={isMobileMod() ? "0" : "-0.4px"}
fontWeith="500"
textAlign="center"
>Conta ativa</Display>
:
<Display
fontSize={isMobileMod() ? "28px" : "34px"}
lineHeight={isMobileMod() ? "36px" : "44px"}
letterSpacing={isMobileMod() ? "0" : "-0.4px"}
fontWeith="500"
textAlign="center"
>Algo deu errado</Display>
}
</Stack>
</MainPageTemplate>
)
}
6 changes: 3 additions & 3 deletions next/pages/user/check-email.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,11 @@ export default function CheckEmail() {
const [email, setEmail] = useState("")

useEffect(() => {

setEmail(localStorage.getItem("registration_email_bd") || "")
}, [])

return (
<MainPageTemplate display="flex" justifyContent="center">
<MainPageTemplate display="flex" justifyContent="center" cleanTemplate>
<Stack
display="flex"
justifyContent="center"
Expand Down Expand Up @@ -61,7 +61,7 @@ export default function CheckEmail() {
lineHeight= "16px"
letterSpacing= "0.2px"
>
[email protected]
{email}
</Text>
</Stack>

Expand Down
12 changes: 3 additions & 9 deletions next/pages/user/register.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,7 @@ import {
Text
} from "@chakra-ui/react";
import { useState } from "react";
import cookies from "js-cookie";

import { registerAccount, getToken } from "../api/user";
import { registerAccount } from "../api/user";

import Input from "../../components/atoms/SimpleInput";
import Button from "../../components/atoms/RoundedButton";
Expand Down Expand Up @@ -110,12 +108,8 @@ export default function Register() {
setErrors(arrayErrors)

if(result?.errors?.length === 0) {
const acess = await getToken({email, password})
cookies.remove('token', { path: '/' })

if(acess?.errors?.length > 0) return

window.open("/", "_self")
localStorage.setItem('registration_email_bd', `${email}`)
window.open("/user/check-email", "_self")
}
}

Expand Down

0 comments on commit ac36765

Please sign in to comment.