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

Loading…
Cancel
Save