Browse Source

Checking if username/nickname are already registered in the database before registering

master
GabrielTrettel 3 years ago
parent
commit
a212c0caef
  1. 11
      src/app/api/auth.js
  2. 96
      src/app/screens/RegisterScreen.js

11
src/app/api/auth.js

@ -71,4 +71,13 @@ async function userActivation(code) {
return localClient.post(`/activate?username=${username}&activationkey=0b7b37bb-0f6d-4c65-b1b4-d7cc816f52bd`);
}
export { login, signup, userPersonalData, userActivation };
async function existUsername(username) {
return authClient.post(`/existsByUsername?username=${username}`);
}
async function existNickname(nickname) {
return authClient.post(`/existsByNickname?nickname=${nickname}`);
}
export { login, signup, userPersonalData, userActivation, existNickname, existUsername };

96
src/app/screens/RegisterScreen.js

@ -5,7 +5,13 @@ import {
ErrorMessage,
} from "../components/forms";
import React, { useState, useEffect, useContext } from "react";
import { StyleSheet, View, Text, TouchableNativeFeedback } from "react-native";
import {
StyleSheet,
View,
Text,
TouchableNativeFeedback,
ScrollView,
} from "react-native";
import Screen from "../components/Screen";
import { dimensions } from "../config/dimensions";
import { MaterialCommunityIcons } from "@expo/vector-icons";
@ -19,10 +25,16 @@ import SearchablePicker from "../components/SearchablePicker";
import { states, statesToCities } from "../assets/cities_states";
import { useFormikContext } from "formik";
import Checkbox from "../components/forms/CheckBox";
import {signup, login, userPersonalData} from "../api/auth";
import {
signup,
login,
userPersonalData,
existUsername,
existNickname,
} from "../api/auth";
import { AuthContext } from "../auth/context";
import authStorage from "../auth/storage";
import jwdDecode from "jwt-decode";
import ConfirmationModal from "../components/ConfirmationModal";
const phoneRegex = RegExp(
/^\(?[\(]?([0-9]{2})?\)?[)\b]?([0-9]{4,5})[-. ]?([0-9]{4})$/
@ -236,7 +248,6 @@ function RolePicker({ name }) {
);
}
function MaterialCommunityIconsCustom({
name,
color = colors.primary,
@ -253,6 +264,8 @@ export default function RegisterScreen(props) {
const _moment = moment();
const [date, setDate] = useState(_moment);
const [singUpFailed, setSingUpFailed] = useState(false);
const [scroll, setScroll] = useState();
const [showLog, setShowLog] = useState(false);
const comparePassword = (password, confirmPassword) => {
if (password !== confirmPassword) {
@ -270,29 +283,50 @@ export default function RegisterScreen(props) {
authStorage.setToken(result.data);
const user = await userPersonalData();
user.ok && authContext.setUser(user.data);
}
};
const handleSubmit = async (form) => {
const formDate = date.format("DD/MM/yyyy") === moment().format("DD/MM/yyyy") ? "" : date;
console.log("apaaaaaaa");
const formDate =
date.format("DD/MM/yyyy") === moment().format("DD/MM/yyyy") ? "" : date;
const result = await signup({...form, dateofborn: formDate})
console.log(result)
const result = await signup({ ...form, dateofborn: formDate });
// console.log(result)
switch (result.status) {
case 200:
automaticLogin(form)
automaticLogin(form);
break;
case 422:
// setError()
// setError()
}
};
default:
const fieldsAreNotInUse = async (form, actions) => {
var inUse = true;
const ru = await existUsername(form.number);
if (ru.data) {
actions.setFieldError("number", "Este número de telefone já está em uso");
inUse = false;
}
const rn = await existNickname(form.name);
if (rn.data) {
actions.setFieldError("name", "Este apelido de usuário já está em uso");
inUse = false;
}
return inUse;
};
return (
<Screen style={styles.containter}>
<ConfirmationModal
show={showLog}
description="Apelido de usuário ou telefone em uso"
confirmationLabel="OK"
onConfirm={() => setShowLog(false)}
/>
<Form
initialValues={{
name: "",
@ -309,16 +343,33 @@ export default function RegisterScreen(props) {
role: "",
consent: false,
}}
onSubmit={(form) => {
onSubmit={(form, actions) => {
comparePassword(form.password, form.confirmPassword);
handleSubmit(form)
fieldsAreNotInUse(form, actions).then((isNotUsed) => {
isNotUsed
? handleSubmit(form)
: setShowLog(true)
// NOTE: this woud be nice, but does not work...
// : scroll.scrollTo({
// x: 0,
// y: 0,
// animated: true,
// });
});
}}
validationSchema={validationSchema}
>
<View
style={{ flexDirection: "column", justifyContent: "center", flex: 1 }}
>
<KeyboardAwareScrollView scrollEnabled={true}>
<ScrollView
scrollToOverflowEnabled={true}
ref={(ref) => {
setScroll(ref);
}}
scrollEnabled={true}
>
<Text
style={{
color: colors.primary,
@ -398,25 +449,21 @@ export default function RegisterScreen(props) {
<MaterialCommunityIconsCustom name="account" />
<GenderPicker name="gender" />
</View>
<Text style={styles.labelStyle}>Estado*:</Text>
<View style={[styles.iconField]}>
<MaterialCommunityIconsCustom name="map-marker" />
<StatePicker name="state" />
</View>
<Text style={styles.labelStyle}>Cidade*:</Text>
<View style={[styles.iconField]}>
<MaterialCommunityIconsCustom name="map-marker" />
<CityPicker name={"city"} />
</View>
<Text style={styles.labelStyle}>Tipo de instituição:</Text>
<View style={[styles.iconField]}>
<MaterialCommunityIconsCustom name="bank" />
<InstitutionPicker name="institution" />
</View>
<Text style={styles.labelStyle}>Nome da instituição</Text>
<View style={styles.iconField}>
<MaterialCommunityIconsCustom name="bank" />
@ -429,16 +476,11 @@ export default function RegisterScreen(props) {
paddingRight={2}
/>
</View>
<Text style={styles.labelStyle}>Vínculo institucional:</Text>
<View style={[styles.iconField]}>
<MaterialCommunityIconsCustom name="bank" />
<RolePicker name="role"/>
<RolePicker name="role" />
</View>
<Text style={styles.labelStyle}>Pergunta de segurança*:</Text>
<View
style={{
@ -461,7 +503,6 @@ export default function RegisterScreen(props) {
paddingLeft={2}
/>
</View>
<Text style={styles.labelStyle}>Termos de uso*</Text>
<View
flexDirection="column"
@ -474,7 +515,6 @@ export default function RegisterScreen(props) {
navigate={() => props.navigation.navigate("UserAgreement")}
/>
</View>
<SubmitButton
flex={1}
title="cadastrar"
@ -497,7 +537,7 @@ export default function RegisterScreen(props) {
<Text style={{ color: colors.lightBlue }}>Faça Login</Text>
</View>
</TouchableNativeFeedback>
</KeyboardAwareScrollView>
</ScrollView>
</View>
</Form>
</Screen>

Loading…
Cancel
Save