Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add input validation and error handling with Zod #9

Open
wants to merge 9 commits into
base: next
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion app.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"version": "1.0.0",
"orientation": "portrait",
"icon": "./assets/icon.png",
"userInterfaceStyle": "light",
"userInterfaceStyle": "dark",
"splash": {
"image": "./assets/splash.png",
"resizeMode": "contain",
Expand Down
44 changes: 44 additions & 0 deletions app/(auth)/login.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,23 @@ import {
TextInput,
View,
} from 'react-native';
import * as yup from 'yup';
import { colors } from '../../constants/colors';
import { validateToFieldErrors } from '../../util/validateToFieldErrors';
import type { UserResponseBodyGet } from '../api/user+api';
import type { LoginResponseBodyPost } from './api/login+api';

const loginSchema = yup.object({
username: yup
.string()
.min(3, 'Username must be at least 3 characters')
.required('Username is required'),
password: yup
.string()
.min(3, 'Password must be at least 3 characters')
.required('Password is required'),
});

const styles = StyleSheet.create({
container: {
flex: 1,
Expand Down Expand Up @@ -59,6 +72,14 @@ const styles = StyleSheet.create({
alignItems: 'center',
gap: 4,
},
inputError: {
borderColor: 'red',
},
errorText: {
color: 'red',
fontSize: 14,
marginBottom: 8,
},
button: {
marginTop: 30,
backgroundColor: colors.text,
Expand All @@ -82,6 +103,7 @@ const styles = StyleSheet.create({
export default function Login() {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});
const [focusedInput, setFocusedInput] = useState<string | undefined>();

const { returnTo } = useLocalSearchParams<{ returnTo: string }>();
Expand Down Expand Up @@ -118,24 +140,32 @@ export default function Login() {
style={[
styles.input,
focusedInput === 'username' && styles.inputFocused,
fieldErrors.username && styles.inputError,
]}
value={username}
onChangeText={setUsername}
onFocus={() => setFocusedInput('username')}
onBlur={() => setFocusedInput(undefined)}
/>
{fieldErrors.username && (
<Text style={styles.errorText}>{fieldErrors.username}</Text>
)}
<Text style={styles.label}>Password</Text>
<TextInput
style={[
styles.input,
focusedInput === 'password' && styles.inputFocused,
fieldErrors.password && styles.inputError,
]}
secureTextEntry
value={password}
onChangeText={setPassword}
onFocus={() => setFocusedInput('password')}
onBlur={() => setFocusedInput(undefined)}
/>
{fieldErrors.password && (
<Text style={styles.errorText}>{fieldErrors.password}</Text>
)}
<View style={styles.promptTextContainer}>
<Text style={{ color: colors.text }}>Don't have an account?</Text>
<Link href="/register" style={{ color: colors.text }}>
Expand All @@ -146,6 +176,20 @@ export default function Login() {
<Pressable
style={({ pressed }) => [styles.button, { opacity: pressed ? 0.5 : 1 }]}
onPress={async () => {
const validationResult = await validateToFieldErrors(loginSchema, {
username,
password,
});

if ('fieldErrors' in validationResult) {
const errors = Object.fromEntries(validationResult.fieldErrors);
setFieldErrors(errors);
return;
}

// Clear errors if validation passes
setFieldErrors({});

const response = await fetch('/api/login', {
method: 'POST',
body: JSON.stringify({ username, password, attending: false }),
Expand Down
44 changes: 44 additions & 0 deletions app/(auth)/register.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,22 @@ import {
TextInput,
View,
} from 'react-native';
import * as yup from 'yup';
import { colors } from '../../constants/colors';
import { validateToFieldErrors } from '../../util/validateToFieldErrors';
import type { RegisterResponseBodyPost } from './api/register+api';

const registerSchema = yup.object({
username: yup
.string()
.min(3, 'Username must be at least 3 characters')
.required('Username is required'),
password: yup
.string()
.min(3, 'Password must be at least 3 characters')
.required('Password is required'),
});

const styles = StyleSheet.create({
container: {
flex: 1,
Expand Down Expand Up @@ -46,6 +59,14 @@ const styles = StyleSheet.create({
inputFocused: {
borderColor: colors.white,
},
inputError: {
borderColor: 'red',
},
errorText: {
color: 'red',
fontSize: 14,
marginBottom: 8,
},
promptTextContainer: {
flexDirection: 'row',
justifyContent: 'center',
Expand Down Expand Up @@ -75,6 +96,7 @@ const styles = StyleSheet.create({
export default function Register() {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});
const [focusedInput, setFocusedInput] = useState<string | undefined>();

useFocusEffect(
Expand Down Expand Up @@ -103,24 +125,32 @@ export default function Register() {
style={[
styles.input,
focusedInput === 'username' && styles.inputFocused,
fieldErrors.username && styles.inputError,
]}
value={username}
onChangeText={setUsername}
onFocus={() => setFocusedInput('username')}
onBlur={() => setFocusedInput(undefined)}
/>
{fieldErrors.username && (
<Text style={styles.errorText}>{fieldErrors.username}</Text>
)}
<Text style={styles.label}>Password</Text>
<TextInput
style={[
styles.input,
focusedInput === 'password' && styles.inputFocused,
fieldErrors.password && styles.inputError,
]}
secureTextEntry
value={password}
onChangeText={setPassword}
onFocus={() => setFocusedInput('password')}
onBlur={() => setFocusedInput(undefined)}
/>
{fieldErrors.password && (
<Text style={styles.errorText}>{fieldErrors.password}</Text>
)}
<View style={styles.promptTextContainer}>
<Text style={{ color: colors.text }}>Already have an account?</Text>
<Link href="/(auth)/login" style={{ color: colors.text }}>
Expand All @@ -131,6 +161,20 @@ export default function Register() {
<Pressable
style={({ pressed }) => [styles.button, { opacity: pressed ? 0.5 : 1 }]}
onPress={async () => {
const validationResult = await validateToFieldErrors(registerSchema, {
username,
password,
});

if ('fieldErrors' in validationResult) {
const errors = Object.fromEntries(validationResult.fieldErrors);
setFieldErrors(errors);
return;
}

// Clear errors if validation passes
setFieldErrors({});

const response = await fetch('/api/register', {
method: 'POST',
body: JSON.stringify({ username, password, attending: false }),
Expand Down
34 changes: 18 additions & 16 deletions app/(tabs)/guests.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,32 +40,34 @@ export default function Guests() {
useCallback(() => {
if (!isStale) return;

async function getUser() {
const response = await fetch('/api/user');
async function getUserAndGuests() {
const [userResponse, guestsResponse]: [
UserResponseBodyGet,
GuestsResponseBodyGet,
] = await Promise.all([
fetch('/api/user').then((response) => response.json()),
fetch('/api/guests').then((response) => response.json()),
]);

const body: UserResponseBodyGet = await response.json();
setIsStale(false);

if ('error' in body) {
if ('error' in userResponse) {
router.replace('/(auth)/login?returnTo=/(tabs)/guests');
return;
}
}

async function getGuests() {
const response = await fetch('/api/guests');
const body: GuestsResponseBodyGet = await response.json();
if ('error' in guestsResponse) {
setGuests([]);
return;
}

setGuests(body.guests);
setIsStale(false);
setGuests(guestsResponse.guests);
}

getUser().catch((error) => {
console.error(error);
});

getGuests().catch((error) => {
getUserAndGuests().catch((error) => {
console.error(error);
});
}, [router, isStale]),
}, [isStale, router]),
);

if (!fontsLoaded) {
Expand Down
10 changes: 6 additions & 4 deletions app/(tabs)/profile.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { router, useFocusEffect } from 'expo-router';
import { useFocusEffect, useRouter } from 'expo-router';
import React, { useCallback } from 'react';
import { Alert, Pressable, StyleSheet, Text, View } from 'react-native';
import type { LogoutResponseBodyGet } from '../(auth)/api/logout+api';
Expand Down Expand Up @@ -33,6 +33,8 @@ const styles = StyleSheet.create({
});

export default function Profile() {
const router = useRouter();

useFocusEffect(
useCallback(() => {
async function getUser() {
Expand All @@ -41,14 +43,14 @@ export default function Profile() {
const body: UserResponseBodyGet = await response.json();

if ('error' in body) {
Alert.alert('Error', body.error, [{ text: 'OK' }]);
return router.push('/(auth)/login');
router.replace('/(auth)/login?returnTo=/(tabs)/profile');
return;
}
}
getUser().catch((error) => {
console.error(error);
});
}, []),
}, [router]),
);

return (
Expand Down
2 changes: 0 additions & 2 deletions app/_layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import {
} from '@expo-google-fonts/poppins';
import Constants from 'expo-constants';
import { Stack } from 'expo-router';
import { StatusBar } from 'expo-status-bar';
import { Platform, SafeAreaView, StyleSheet, View } from 'react-native';
import { colors } from '../constants/colors';

Expand Down Expand Up @@ -35,7 +34,6 @@ export default function HomeLayout() {

return (
<SafeAreaView style={styles.container}>
<StatusBar style="light" />
<View style={styles.view}>
<Stack>
<Stack.Screen
Expand Down
31 changes: 21 additions & 10 deletions app/guests/[guestId].tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Ionicons } from '@expo/vector-icons';
import { Image } from 'expo-image';
import { router, useFocusEffect, useLocalSearchParams } from 'expo-router';
import { useFocusEffect, useLocalSearchParams, useRouter } from 'expo-router';
import { useCallback, useState } from 'react';
import {
Pressable,
Expand All @@ -13,6 +13,7 @@ import {
import placeholder from '../../assets/candidate-default.avif';
import { colors } from '../../constants/colors';
import type { GuestResponseBodyGet } from '../api/guests/[guestId]+api';
import type { UserResponseBodyGet } from '../api/user+api';

const styles = StyleSheet.create({
container: {
Expand Down Expand Up @@ -115,30 +116,40 @@ export default function GuestPage() {
const [attending, setAttending] = useState(false);
const [focusedInput, setFocusedInput] = useState<string | undefined>();

const router = useRouter();

// Dynamic import of images
// const imageContext = require.context('../../assets', false, /\.(avif)$/);

useFocusEffect(
useCallback(() => {
async function loadGuest() {
async function getUserAndLoadGuest() {
if (typeof guestId !== 'string') {
return;
}
const [userResponse, guestResponse]: [
UserResponseBodyGet,
GuestResponseBodyGet,
] = await Promise.all([
fetch('/api/user').then((response) => response.json()),
fetch(`/api/guests/${guestId}`).then((response) => response.json()),
]);

const response = await fetch(`/api/guests/${guestId}`);
const responseBody: GuestResponseBodyGet = await response.json();
if ('error' in userResponse) {
router.replace(`/(auth)/login?returnTo=/guests/${guestId}`);
}

if ('guest' in responseBody) {
setFirstName(responseBody.guest.firstName);
setLastName(responseBody.guest.lastName);
setAttending(responseBody.guest.attending);
if ('guest' in guestResponse) {
setFirstName(guestResponse.guest.firstName);
setLastName(guestResponse.guest.lastName);
setAttending(guestResponse.guest.attending);
}
}

loadGuest().catch((error) => {
getUserAndLoadGuest().catch((error) => {
console.error(error);
});
}, [guestId]),
}, [guestId, router]),
);

if (typeof guestId !== 'string') {
Expand Down
Loading