Browse Source

Merge branch 'main' of https://github.com/IGSD-UoW/WPD-MobileApp into main

master
analuizaff 3 years ago
parent
commit
8db503e1d4
  1. 35
      src/app/api/auth.js
  2. 33
      src/app/screens/AccountScreen.js
  3. 73
      src/app/screens/ActivateInstitutionCode.js
  4. 29
      src/app/screens/ActivateInstitutionShowCode.js
  5. 5
      src/app/screens/LoginScreen.js
  6. 38
      src/app/screens/RegisterScreen.js

35
src/app/api/auth.js

@ -1,5 +1,6 @@
import { create } from "apisauce"; import { create } from "apisauce";
import authClient from "../auth/authClient"; import authClient from "../auth/authClient";
import authStorage from "../auth/storage";
function login(name, password) { function login(name, password) {
return authClient.post(`/login?username=${name}&password=${password}`); return authClient.post(`/login?username=${name}&password=${password}`);
@ -18,6 +19,7 @@ function signup({
secQuestion, secQuestion,
secQuestionAns, secQuestionAns,
consent, consent,
role,
}) { }) {
const body = { const body = {
username: number, username: number,
@ -32,22 +34,41 @@ function signup({
securityquestion: secQuestion, securityquestion: secQuestion,
securityanswer: secQuestionAns, securityanswer: secQuestionAns,
termsofusage: consent, termsofusage: consent,
roles: ["ROLE_CLIENT"],
roles: role !== "" ? [role] : ["ROLE_CLIENT"],
}; };
// Object.entries(body).forEach(([key, value]) => {
// value == "" && delete body[key];
// });
Object.entries(body).forEach(([key, value]) => {
value === "" && delete body[key];
});
return authClient.post(`/signup`, body); return authClient.post(`/signup`, body);
} }
function userPersonalData(token) {
async function userPersonalData() {
const authToken = await authStorage.getToken()
const localClient = create({ const localClient = create({
baseURL: "http://wpd.brazilsouth.cloudapp.azure.com:8080/users", baseURL: "http://wpd.brazilsouth.cloudapp.azure.com:8080/users",
}); });
localClient.setHeader("Authorization", `Bearer ${token}`);
localClient.setHeader("Authorization", `Bearer ${authToken}`);
return localClient.get(`/me`); return localClient.get(`/me`);
} }
export { login, signup, userPersonalData };
async function userActivation(code) {
const { username } = await authStorage.getUser();
const authToken = await authStorage.getToken()
console.log("TOKEN ACTIVATE: "+authToken);
console.log("USER NAME: " + username);
const localClient = create({
baseURL: "http://wpd.brazilsouth.cloudapp.azure.com:8080/users",
});
localClient.setHeader("Authorization", `Bearer ${authToken}`);
return localClient.post(`/activate?username=${username}&activationkey=0b7b37bb-0f6d-4c65-b1b4-d7cc816f52bd`);
}
export { login, signup, userPersonalData, userActivation };

33
src/app/screens/AccountScreen.js

@ -9,7 +9,6 @@ import { MaterialCommunityIcons, FontAwesome } from "@expo/vector-icons";
import colors from "../config/colors"; import colors from "../config/colors";
import ConfirmationModal from "../components/ConfirmationModal"; import ConfirmationModal from "../components/ConfirmationModal";
function UserHeader({ name, fone }) { function UserHeader({ name, fone }) {
return ( return (
<View style={{ flexDirection: "row", alignItems: "center" }}> <View style={{ flexDirection: "row", alignItems: "center" }}>
@ -74,16 +73,32 @@ function ProfileItensList({ icon, IconProvider, title, onPress }) {
function AccountScreen(props) { function AccountScreen(props) {
const { user, setUser } = useContext(AuthContext); const { user, setUser } = useContext(AuthContext);
const [ showLog, setShowLog ] = useState(false);
const [showLog, setShowLog] = useState(false);
console.log(user);
const logout = () => { const logout = () => {
setUser(null); setUser(null);
authStorage.removeToken(); authStorage.removeToken();
}; };
const activationActions = () => {
if (user?.providerActivationKey)
props.navigation.navigate("ActivateInstitutionShowCode");
else
props.navigation.navigate("ActivateInstitutionCode");
};
const showActivation = () => {
if (user.role === "ROLE_CLIENT")
return !user.active
else
return true
}
const profileItems = [ const profileItems = [
{ {
icon: "account", icon: "account",
show: true,
IconProvider: MaterialCommunityIcons, IconProvider: MaterialCommunityIcons,
title: "Cadastrar pluviômetro", title: "Cadastrar pluviômetro",
onPress: () => { onPress: () => {
@ -92,14 +107,16 @@ function AccountScreen(props) {
}, },
{ {
icon: "institution", icon: "institution",
show: showActivation(),
IconProvider: FontAwesome, IconProvider: FontAwesome,
title: "ATIVAR INSTITUIÇÃO", title: "ATIVAR INSTITUIÇÃO",
onPress: () => { onPress: () => {
props.navigation.navigate("ActivateInstitution");
activationActions();
}, },
}, },
{ {
icon: "information-outline", icon: "information-outline",
show: true,
IconProvider: MaterialCommunityIcons, IconProvider: MaterialCommunityIcons,
title: "SOBRE O PROJETO", title: "SOBRE O PROJETO",
onPress: () => { onPress: () => {
@ -108,10 +125,11 @@ function AccountScreen(props) {
}, },
{ {
icon: "logout", icon: "logout",
show: true,
IconProvider: MaterialCommunityIcons, IconProvider: MaterialCommunityIcons,
title: "sair", title: "sair",
onPress: () => { onPress: () => {
setShowLog(true)
setShowLog(true);
}, },
}, },
// { // {
@ -135,7 +153,9 @@ function AccountScreen(props) {
<UserHeader name={user.nickname} fone={user.username} image={"1"} /> <UserHeader name={user.nickname} fone={user.username} image={"1"} />
<View style={{ marginTop: 24 }}> <View style={{ marginTop: 24 }}>
{profileItems.map(({ icon, IconProvider, title, onPress }) => (
{profileItems.map(
({ icon, IconProvider, title, onPress, show }) =>
show && (
<View key={title}> <View key={title}>
<ProfileItensList <ProfileItensList
icon={icon} icon={icon}
@ -144,7 +164,8 @@ function AccountScreen(props) {
onPress={onPress} onPress={onPress}
/> />
</View> </View>
))}
)
)}
</View> </View>
<ConfirmationModal <ConfirmationModal
show={showLog} show={showLog}

73
src/app/screens/ActivateInstitutionCode.js

@ -7,8 +7,6 @@ import { MaterialCommunityIcons } from "@expo/vector-icons";
import { AuthContext } from "../auth/context"; import { AuthContext } from "../auth/context";
import authStorage from "../auth/storage"; import authStorage from "../auth/storage";
import { import {
Form, Form,
SubmitButton, SubmitButton,
@ -17,7 +15,7 @@ import {
} from "../components/forms"; } from "../components/forms";
import { KeyboardAwareScrollView } from "react-native-keyboard-aware-scroll-view"; import { KeyboardAwareScrollView } from "react-native-keyboard-aware-scroll-view";
import ConfirmationModal from "../components/ConfirmationModal"; import ConfirmationModal from "../components/ConfirmationModal";
import {userPersonalData} from "../api/auth";
import { userActivation } from "../api/auth";
function Header() { function Header() {
return ( return (
@ -43,20 +41,27 @@ function Header() {
} }
function Institution({ user, institutionRole }) { function Institution({ user, institutionRole }) {
var institutionMap = {
const institutionMap = {
E: "Escola", E: "Escola",
D: "Defesa Civil", D: "Defesa Civil",
N: "Não governamental", N: "Não governamental",
O: "Outra", O: "Outra",
N: "Nenhuma"
N: "Nenhuma",
}; };
const roleMap = {
ROLE_CLIENT: "Não responsável",
ROLE_INSTITUTION: "Responsável",
}
return ( return (
<View style={{ marginTop: 24, marginBottom: 24 }}> <View style={{ marginTop: 24, marginBottom: 24 }}>
<Text style={styles.label}>Tippo de instituição: </Text> <Text style={styles.label}>Tippo de instituição: </Text>
<View style={{ flexDirection: "row" }}> <View style={{ flexDirection: "row" }}>
<MaterialCommunityIcons name="bank" size={30} color={colors.primary} /> <MaterialCommunityIcons name="bank" size={30} color={colors.primary} />
<Text style={styles.subText}>{institutionMap[user.institutiontype]}</Text>
<Text style={styles.subText}>
{institutionMap[user.institutiontype]}
</Text>
</View> </View>
<Text style={[styles.label, { marginTop: 24 }]}> <Text style={[styles.label, { marginTop: 24 }]}>
@ -76,19 +81,24 @@ function Institution({ user, institutionRole }) {
size={30} size={30}
color={colors.primary} color={colors.primary}
/> />
<Text style={styles.subText}>{institutionRole}</Text>
<Text style={styles.subText}>{roleMap[user.role]}</Text>
</View> </View>
</View> </View>
); );
} }
function ValidateCode({ institutionRole, user }) {
// 950ebd56-7acc-4b45-9366-23a0f814f3f2
// 1199990987
function ValidateCode({ user }) {
return ( return (
<View flex={1} padding={16} width="100%"> <View flex={1} padding={16} width="100%">
<Header /> <Header />
<Institution user={user} institutionRole={institutionRole} />
<Institution user={user} />
<Text style={[styles.label]}>Código de ativação:</Text>
<View style={styles.iconField}> <View style={styles.iconField}>
<MaterialCommunityIcons <MaterialCommunityIcons
name="key" name="key"
@ -101,7 +111,7 @@ function ValidateCode({ institutionRole, user }) {
<FormField <FormField
paddingRight={2} paddingRight={2}
flex={1} flex={1}
maxLength={12}
maxLength={36}
name="code" name="code"
numberOfLines={2} numberOfLines={2}
placeholder="Digite o código de ativação" placeholder="Digite o código de ativação"
@ -113,33 +123,36 @@ function ValidateCode({ institutionRole, user }) {
); );
} }
function verifyCode(code) {
return true;
}
function processOnSubmit(navigation, form, instRole, setShowLog) {
async function processOnSubmit(navigation, form, instRole, setShowLog) {
const response = await userActivation(form.code);
console.log("==============================================================================")
console.log(response)
if (instRole == "Não responsável") { if (instRole == "Não responsável") {
if (verifyCode(form.code)) {
setShowLog({show: true, message: true});
if (response.ok) {
setShowLog({ show: true, message: true });
} else { } else {
setShowLog({show: true, message: false});
setShowLog({ show: true, message: false });
} }
} else if (verifyCode(form.code)) {
navigation.navigate("ActivateInstitutionShowCode", { code: form.code });
} else if (response.ok) {
navigation.navigate("ActivateInstitutionShowCode");
} else { } else {
setShowLog({show: true, message: false});
setShowLog({ show: true, message: false });
} }
// navigation.navigate("ActivateInstitutionShowCode", { code: form.code }); // navigation.navigate("ActivateInstitutionShowCode", { code: form.code });
} }
export default function ActivateInstitutionCode({ route, navigation }) {
const { instRole } = route.params;
export default function ActivateInstitutionCode({ navigation }) {
const { user, _ } = useContext(AuthContext); const { user, _ } = useContext(AuthContext);
// FIXME: wpdAuth has errors while giving /me data for ROLE_INSTITUTION
user.role = "ROLE_CLIENT"
// console.log(user)
const initialState = {show: false, message: true}
const initialState = { show: false, message: true };
const [showLog, setShowLog] = useState(initialState); const [showLog, setShowLog] = useState(initialState);
return ( return (
@ -149,19 +162,23 @@ export default function ActivateInstitutionCode({ route, navigation }) {
}} }}
onSubmit={(form) => { onSubmit={(form) => {
console.log("Forms values: \n" + JSON.stringify(form)); console.log("Forms values: \n" + JSON.stringify(form));
processOnSubmit(navigation, form, instRole, setShowLog);
processOnSubmit(navigation, form, user.role, setShowLog);
}} }}
> >
<ConfirmationModal <ConfirmationModal
show={showLog.show} show={showLog.show}
description={showLog.message ? "O código de ativação foi validado com sucesso." : "O código de ativação informado não coincide com o código do responsável pela instituição no Cemaden Educação."}
description={
showLog.message
? "O código de ativação foi validado com sucesso."
: "O código de ativação informado não coincide com o código do responsável pela instituição no Cemaden Educação."
}
confirmationLabel="OK" confirmationLabel="OK"
onConfirm={() => setShowLog(initialState)} onConfirm={() => setShowLog(initialState)}
onDecline={() => setShowLog(initialState)} onDecline={() => setShowLog(initialState)}
/> />
<KeyboardAwareScrollView> <KeyboardAwareScrollView>
<ValidateCode user={user} institutionRole={instRole} />
<ValidateCode user={user} />
</KeyboardAwareScrollView> </KeyboardAwareScrollView>
</Form> </Form>
); );

29
src/app/screens/ActivateInstitutionShowCode.js

@ -1,7 +1,10 @@
import React, { useState, useContext } from "react";
import React, { useState, useContext, useEffect } from "react";
import { View, Text } from "react-native"; import { View, Text } from "react-native";
import { dimensions } from "../config/dimensions"; import { dimensions } from "../config/dimensions";
import colors from "../config/colors"; import colors from "../config/colors";
import authStorage from "../auth/storage";
import { AuthContext } from "../auth/context";
import {userPersonalData} from "../api/auth";
function Header() { function Header() {
return ( return (
@ -26,10 +29,22 @@ function Header() {
); );
} }
export default function ActivateInstitutionShowCode() {
const [actCode, setActCode] = useState("");
const authContext = useContext(AuthContext);
useEffect(() => {
if (authContext.user?.providerActivationKey?.activationkey)
setActCode(authContext.user.providerActivationKey.activationkey);
else
userPersonalData().then((userData) => {
userData.ok && authContext.setUser(userData.data);
setActCode(userData.data.providerActivationKey.activationkey);
});
}, []);
export default function ActivateInstitutionShowCode({ route }) {
const { code } = route.params;
const [actCode, setActCode] = useState("123456789012");
return ( return (
<View> <View>
@ -52,9 +67,11 @@ export default function ActivateInstitutionShowCode({ route }) {
marginTop: 24, marginTop: 24,
fontWeight: "bold", fontWeight: "bold",
textAlign: "center", textAlign: "center",
fontSize: dimensions.text.header
fontSize: dimensions.text.header,
}} }}
>{actCode}</Text>
>
{actCode}
</Text>
</View> </View>
); );
} }

5
src/app/screens/LoginScreen.js

@ -79,10 +79,11 @@ export default function LoginScreen(props) {
const result = await login(name, password); const result = await login(name, password);
if (!result.ok) return setLoginFailed(true); if (!result.ok) return setLoginFailed(true);
authStorage.setToken(result.data);
await authStorage.setToken(result.data);
// console.log("TOKEN: " + result.data);
setLoginFailed(false); setLoginFailed(false);
const user = await userPersonalData(result.data);
const user = await userPersonalData();
user.ok && authContext.setUser(user.data); user.ok && authContext.setUser(user.data);
}; };

38
src/app/screens/RegisterScreen.js

@ -51,6 +51,7 @@ const validationSchema = Yup.object().shape({
.required("A resposta da pergunta de segurança é obrigatória") .required("A resposta da pergunta de segurança é obrigatória")
.max(255), .max(255),
consent: Yup.bool().equals([true], "Este campo é obrigatório"), consent: Yup.bool().equals([true], "Este campo é obrigatório"),
role: Yup.string(),
}); });
function LocalDatePicker({ date, setDate, _moment }) { function LocalDatePicker({ date, setDate, _moment }) {
@ -218,6 +219,24 @@ function SecQuestionPicker({ name }) {
); );
} }
function RolePicker({ name }) {
const [items, setItems] = useState([
{ value: "ROLE_INSTITUTION", label: "Responsável" },
{ value: "ROLE_CLIENT", label: "Não responsável" },
]);
return (
<SearchablePicker
name={name}
items={items}
setItems={setItems}
formPlaceholder={"Selecione o vínculo institucional"}
searchPlaceholder={"Busca..."}
/>
);
}
function MaterialCommunityIconsCustom({ function MaterialCommunityIconsCustom({
name, name,
color = colors.primary, color = colors.primary,
@ -249,7 +268,7 @@ export default function RegisterScreen(props) {
if (!result.ok) return; if (!result.ok) return;
authStorage.setToken(result.data); authStorage.setToken(result.data);
const user = await userPersonalData(result.data);
const user = await userPersonalData();
user.ok && authContext.setUser(user.data); user.ok && authContext.setUser(user.data);
} }
@ -258,6 +277,8 @@ export default function RegisterScreen(props) {
const formDate = date.format("DD/MM/yyyy") === moment().format("DD/MM/yyyy") ? "" : date; const formDate = date.format("DD/MM/yyyy") === moment().format("DD/MM/yyyy") ? "" : date;
const result = await signup({...form, dateofborn: formDate}) const result = await signup({...form, dateofborn: formDate})
console.log(result)
switch (result.status) { switch (result.status) {
case 200: case 200:
automaticLogin(form) automaticLogin(form)
@ -285,13 +306,12 @@ export default function RegisterScreen(props) {
institution: "", institution: "",
secQuestion: "", secQuestion: "",
secQuestionAns: "", secQuestionAns: "",
role: "",
consent: false, consent: false,
}} }}
onSubmit={(form) => { onSubmit={(form) => {
comparePassword(form.password, form.confirmPassword); comparePassword(form.password, form.confirmPassword);
handleSubmit(form) handleSubmit(form)
// console.log("cadastro ainda não implementado");
// console.log("Forms values: \n" + JSON.stringify(form));
}} }}
validationSchema={validationSchema} validationSchema={validationSchema}
> >
@ -316,7 +336,7 @@ export default function RegisterScreen(props) {
<FormField <FormField
paddingRight={2} paddingRight={2}
flex={1} flex={1}
maxLength={12}
maxLength={40}
name="name" name="name"
numberOfLines={2} numberOfLines={2}
placeholder="Digite o apelido de usuário" placeholder="Digite o apelido de usuário"
@ -409,6 +429,16 @@ export default function RegisterScreen(props) {
paddingRight={2} paddingRight={2}
/> />
</View> </View>
<Text style={styles.labelStyle}>Vínculo institucional:</Text>
<View style={[styles.iconField]}>
<MaterialCommunityIconsCustom name="bank" />
<RolePicker name="role"/>
</View>
<Text style={styles.labelStyle}>Pergunta de segurança*:</Text> <Text style={styles.labelStyle}>Pergunta de segurança*:</Text>
<View <View
style={{ style={{

Loading…
Cancel
Save