Skip to content

Commit 8a7d07d

Browse files
committed
Fix: Signup + Auth + everything
1 parent b8dd2eb commit 8a7d07d

File tree

7 files changed

+129
-64
lines changed

7 files changed

+129
-64
lines changed

client/src/components/admin/ManageAccounts.tsx

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -137,11 +137,11 @@ export const ManageAccounts = () => {
137137

138138
const handleDelete = async () => {
139139
try {
140-
await Promise.all(
141-
selectedRowIds.map((row_id) =>
142-
backend.delete(`/caseManagers/${row_id}`)
143-
)
144-
);
140+
141+
selectedRowIds.map(async (row_id) => {
142+
const caseManager = await backend.delete(`/caseManagers/${row_id}`);
143+
await backend.delete(`/users/email/${caseManager.data[0].email}`);
144+
})
145145
setPersons(
146146
persons.filter((client) => !selectedRowIds.includes(client.id))
147147
);

client/src/components/authentification/authentification.tsx

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -84,16 +84,24 @@ export const Authentification = () => {
8484
}
8585
};
8686

87-
useEffect( () => {
88-
const generateCode = async () => {
89-
try {
90-
await createCode();
91-
} catch (err) {
92-
console.error('Error posting code: ', err);
93-
}
94-
};
95-
generateCode();
96-
}, [createCode]);
87+
// const generateCode = async () => {
88+
// try {
89+
// await createCode();
90+
// } catch (err) {
91+
// console.error('Error posting code: ', err);
92+
// }
93+
// };
94+
95+
// useEffect( () => {
96+
// const generateCode = async () => {
97+
// try {
98+
// await createCode();
99+
// } catch (err) {
100+
// console.error('Error posting code: ', err);
101+
// }
102+
// };
103+
// generateCode();
104+
// }, [createCode]);
97105

98106
useEffect(() => {
99107
handleRedirectResult(backend, navigate, toast);

client/src/components/clientlist/ClientList.tsx

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -430,6 +430,7 @@ export const ClientList = ({ admin }: ClientListProps) => {
430430
<IconButton
431431
aria-label="Download CSV"
432432
onClick={() => onPressCSVButton()}
433+
isDisabled={selectedRowIds.length === 0}
433434
>
434435
<FiUpload />
435436
</IconButton>

client/src/components/login/Login.tsx

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ export const Login = () => {
4444
const { userType = "Admin"} = useParams<{ userType: string }>();
4545
const userAbbreviation = userType === "Case Manager" ? "CM" : userType === "Client" ? "CL" : "AD";
4646

47-
const { login, handleRedirectResult, loading } = useAuthContext();
47+
const { login, handleRedirectResult, loading, createCode } = useAuthContext();
4848
const { backend } = useBackendContext();
4949

5050
const {
@@ -70,16 +70,21 @@ export const Login = () => {
7070

7171
const handleLogin = async (data: SigninFormValues) => {
7272
try {
73-
await login({
73+
const authCredential = await login({
7474
email: data.email,
7575
password: data.password,
7676
});
77-
if (userType === "Case Manager") navigate("/authentification/Case Manager");
78-
else if (userType === "Admin") {
77+
78+
await createCode(data.email, authCredential);
79+
80+
if (userType === "Case Manager") {
81+
navigate("/authentification/Case Manager");
82+
} else if (userType === "Admin") {
7983
navigate("/authentification/Admin");
8084
} else if (userType === "Client") {
8185
navigate("/authentification/Client");
8286
}
87+
8388
//else if (userType === "Client") navigate("/client-landing-page");
8489
} catch (err) {
8590
const errorCode = err.code;

client/src/contexts/AuthContext.tsx

Lines changed: 53 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ import {
1515
User,
1616
UserCredential,
1717
} from "firebase/auth";
18-
import { Navigate, NavigateFunction } from "react-router-dom";
18+
import { useNavigate, Navigate, NavigateFunction } from "react-router-dom";
1919

2020
import { auth } from "../utils/auth/firebase";
2121
import { useBackendContext } from "./hooks/useBackendContext";
@@ -34,7 +34,7 @@ interface AuthContextProps {
3434
role,
3535
}: SignupInfo) => Promise<UserCredential>;
3636
login: ({ email, password }: EmailPassword) => Promise<EmailAuthCredential>;
37-
createCode: () => Promise<void>;
37+
createCode: (email: string, authCredential: EmailAuthCredential) => Promise<void>;
3838
logout: () => Promise<void>;
3939
authenticate: ({ code }: Authenticate) => Promise<UserCredential | void>;
4040
resetPassword: ({ email }: Pick<EmailPassword, "email">) => Promise<void>;
@@ -75,6 +75,7 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
7575
const [authCredential, setAuthCredential] =
7676
useState<EmailAuthCredential | null>(null);
7777
const [email, setEmail] = useState<string | null>(null);
78+
const navigate = useNavigate();
7879

7980
const signup = async ({
8081
email,
@@ -103,59 +104,77 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
103104
throw new Error("Not authorized to create this type of user");
104105
}
105106

106-
await backend.delete(`users/email/${email}`);
107+
// await backend.delete(`users/email/${email}`);
107108

108109
const userCredential = await createUserWithEmailAndPassword(
109110
auth,
110111
email,
111112
password
112113
);
113114

114-
await backend.post("/users/create", {
115-
email: email,
116-
firebaseUid: userCredential.user.uid,
117-
firstName: firstName,
118-
lastName: lastName,
119-
phoneNumber: phoneNumber,
120-
role,
121-
});
115+
try {
116+
await backend.put("/users/updateUser", {
117+
email: email,
118+
firstName: firstName,
119+
lastName: lastName,
120+
phoneNumber: phoneNumber,
121+
firebaseUid: userCredential.user.uid,
122+
});
123+
} catch (error) {
124+
console.error("Error updating user:", error);
125+
}
126+
127+
// await backend.post("/users/create", {
128+
// email: email,
129+
// firebaseUid: userCredential.user.uid,
130+
// firstName: firstName,
131+
// lastName: lastName,
132+
// phoneNumber: phoneNumber,
133+
// role,
134+
// });
122135

123136
return userCredential;
124137
};
125138

126139
const login = async ({ email, password }: EmailPassword) => {
127140
if (currentUser) {
141+
// TODO CHANGE TO REDIRECT IF LOGGED IN
128142
signOut(auth);
129143
}
144+
145+
const user = await backend.get(`/users/email/${email}`)
146+
147+
if(user.data.length === 0){
148+
throw new Error("Incorrect username or password");
149+
}
150+
130151
const authCredential = EmailAuthProvider.credential(email, password);
131152
setAuthCredential(authCredential);
132153
setEmail(email);
133154

134155
return authCredential;
135156
};
136157

137-
const createCode = async () => {
138-
if (authCredential && email) {
139-
try {
140-
// Delete all the stale codes associated with this email
141-
// await backend.delete(`authentification/email?email=${email}`);
142-
143-
// Create new code for them
144-
const now = new Date();
145-
const validUntil = new Date(now.getTime() + 24 * 60 * 60 * 1000);
146-
147-
const authData = await backend.post("/authentification", {
148-
email: email,
149-
validUntil: validUntil,
150-
});
151-
//const code = authData?.data[0]?.code;
152-
153-
// Send the code to the user via email
154-
155-
return;
156-
} catch (error) {
157-
console.error("Error signing in with credential:", error);
158-
}
158+
const createCode = async (email: string, authCredential: EmailAuthCredential) => {
159+
try {
160+
161+
// Delete all the stale codes associated with this email
162+
// await backend.delete(`authentification/email?email=${email}`);
163+
164+
// Create new code for them
165+
const now = new Date();
166+
const validUntil = new Date(now.getTime() + 24 * 60 * 60 * 1000);
167+
168+
const authData = await backend.post(`/authentification`, {
169+
email: email,
170+
validUntil: validUntil,
171+
});
172+
173+
174+
//const code = authData?.data[0]?.code;
175+
// Send the code to the user via email
176+
} catch (error) {
177+
console.error("Error creating code:", error);
159178
}
160179
};
161180

@@ -164,12 +183,11 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
164183
const response = await backend.post(
165184
`/authentification/verify?email=${email}&code=${code}`
166185
);
167-
if (response.data.length == 0) {
186+
if (response.data.length === 0) {
168187
throw new Error("Invalid code. Try again.");
169188
}
170189

171190
const userCredential = await signInWithCredential(auth, authCredential);
172-
173191
// we have to update the currnet user role BEFORE we sign in or else the app won't know what role we are currently
174192
const userData = await backend.get(`/users/${userCredential.user.uid}`);
175193
setCurrentUserRole(userData.data[0]?.role);

server/routes/authentification.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ authentificationRouter.post("/", async (req, res) => {
7474
}
7575

7676
const mail = {
77-
from: sendEmail,
77+
from: "cchautomatedemail@gmail.com",
7878
to: email,
7979
subject: "Your Two-Factor Authentication Code",
8080
text: message,

server/routes/users.ts

Lines changed: 42 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -68,20 +68,33 @@ usersRouter.delete("/:firebaseUid", async (req, res) => {
6868
usersRouter.delete("/email/:email", async (req, res) => {
6969
try {
7070
const { email } = req.params;
71+
console.log("email", email)
72+
73+
// try {
74+
// const userRecord = await admin.auth().getUserByEmail(email);
75+
// console.log("userRecord", userRecord)
76+
// const uid = userRecord.uid;
77+
// console.log("uid", uid)
78+
// await admin.auth().deleteUser(uid);
79+
// } catch (firebaseError) {
80+
// // If user doesn't exist in Firebase, that's okay - they might be a placeholder user
81+
// console.log(`Firebase Error: ${firebaseError}`);
82+
// }
7183

72-
const user = await db.query("DELETE FROM users WHERE email = $1", [
84+
const user = await db.query("SELECT * FROM users WHERE email = $1", [
7385
email,
7486
]);
87+
console.log("user", user)
88+
89+
// Only delete from Firebase if the user has a valid firebase_uid
90+
if (user[0] && user[0].firebase_uid && user[0].firebase_uid.trim() !== '') {
91+
const deletedUser = await admin.auth().deleteUser(user[0].firebase_uid);
92+
console.log("deletedUser", deletedUser)
93+
} else {
94+
console.log("No valid firebase_uid found, skipping Firebase deletion")
95+
}
7596

7697
// Only try to delete from Firebase if the user exists there
77-
try {
78-
const userRecord = await admin.auth().getUserByEmail(email);
79-
const uid = userRecord.uid;
80-
await admin.auth().deleteUser(uid);
81-
} catch (firebaseError) {
82-
// If user doesn't exist in Firebase, that's okay - they might be a placeholder user
83-
console.log(`User ${email} not found in Firebase, skipping Firebase deletion`);
84-
}
8598

8699
res.status(200).json(keysToCamel(user));
87100
} catch (err) {
@@ -170,3 +183,23 @@ usersRouter.put("/update/set-role", verifyRole("admin"), async (req, res) => {
170183
res.status(400).send(err.message);
171184
}
172185
});
186+
187+
usersRouter.put("/updateUser", async (req, res) => {
188+
try {
189+
const { email, firstName, lastName, phoneNumber, firebaseUid } = req.body;
190+
191+
const user = await db.query(
192+
`UPDATE users
193+
SET first_name = COALESCE($1, first_name),
194+
last_name = COALESCE($2, last_name),
195+
phone_number = COALESCE($3, phone_number),
196+
firebase_uid = COALESCE($4, firebase_uid)
197+
WHERE email = $5
198+
RETURNING *`,
199+
[firstName, lastName, phoneNumber, firebaseUid, email]
200+
);
201+
res.status(200).json(keysToCamel(user));
202+
} catch (err) {
203+
res.status(400).send(err.message);
204+
}
205+
});

0 commit comments

Comments
 (0)