All files authController.ts

97.43% Statements 76/78
85.71% Branches 30/35
100% Functions 7/7
97.36% Lines 74/76

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231                              1x     5x     5x 5x 5x   5x   5x     4x 1x 1x           3x 3x   3x   3x 3x   1x 1x       2x                   2x     1x                                 1x           1x     1x                 1x 1x               3x 3x 3x 3x   2x 1x   1x     1x         3x       3x 3x 3x 2x 2x 2x       2x 1x                 1x 1x                     1x   1x                     1x   1x         1x 1x   1x         1x 1x         3x 3x 3x 3x 2x 1x   2x   1x 1x 1x 1x 1x 1x 1x       1x     1x         2x 2x 2x 1x   1x          
import express, { Response } from "express";
import { UserInfo, AdminInfo, CustomRequest, CustomUserRequest, ConciergeInfo } from "@deliverables.org/types";
import { signUpAdmin, signUpConcierge, signInConcierge, signInAdmin, signOutAdmin } from "./authHelper";
import { addItem, getByID, getItem, updateItem } from "@deliverables.org/database"
import { Company, Complex, IAdmin } from "@deliverables.org/types";
import { v4 as uuidv4 } from "uuid";
 
interface IUserController {
    signUpConcierge: express.Handler,
    signInConcierge: express.Handler,
    signUpRoot: express.Handler,
    signOutAdmin: express.Handler,
    signInAdmin: express.Handler
}
 
const authController: IUserController = {
 
    signUpConcierge: async (req: CustomUserRequest, res: Response) => {
        const ConciergeInfo: ConciergeInfo = {
            email: req.body.credentials
        }
        const password = req.body.password as string;
        const conciergeName = req.body.name as string;
        const complexId = req.body.complexId;
 
        try {
            // Step 1: Create user in Cognito
            const response = await signUpConcierge(ConciergeInfo, password);
 
            // Handle string response (error message)
            if (typeof response === "string") {
                res.status(400).json({ message: response });
                return;
            }
 
            // Handle successful Cognito signup
            // UserConfirmed can be true (auto-confirmed) or false (email verification required)
            // Both are valid successful signup responses
            if (response && typeof response === "object" && response.UserSub) {
                const userSub = response.UserSub as string;
 
                try {
                    // Step 2: Verify complex exists
                    const { Items } = await getByID(complexId);
                    if (!Items || Items.length === 0) {
                        // Rollback: Would need to delete Cognito user here (future enhancement)
                        res.status(400).json({ message: "Complex not found" });
                        return;
                    }
 
                    // Step 3: Add concierge to DynamoDB
                    const concierge: IAdmin = {
                        PK: 'COMPLEX#' + complexId,
                        SK: 'CONCIERGE#' + userSub,
                        type: "concierge",
                        name: conciergeName,
                        email: ConciergeInfo.email,
                        id: userSub,
                        complexIds: [complexId],
                        createdAt: new Date().toISOString(),
                    };
                    await addItem({ TableName: "DELIVERABLES", Item: concierge });
 
                    // Step 4: Update complex with concierge reference
                    await updateItem({
                        TableName: "DELIVERABLES",
                        Key: { PK: Items[0].PK, SK: Items[0].SK },
                        UpdateExpression:
                            "SET concierges = list_append(if_not_exists(concierges, :empty_list), :new_concierge)",
                        ExpressionAttributeValues: {
                            ":empty_list": [],
                            ":new_concierge": [
                                {
                                    email: ConciergeInfo.email,
                                    sub: userSub,
                                    name: conciergeName
                                }
                            ],
                        },
                    });
 
                    res.status(201).json({
                        message: "Concierge signed up successfully",
                        userId: userSub,
                        complexId: complexId
                    });
                } catch (dbError) {
                    console.error("Database error during concierge signup:", dbError);
                    // Note: Cognito user already created but DB failed
                    // In production, implement compensating transaction to delete Cognito user
                    res.status(500).json({
                        message: "Failed to complete concierge registration. Please contact support.",
                        error: dbError instanceof Error ? dbError.message : 'Unknown error'
                    });
                }
            } else E{
                res.status(400).json({ message: "Failed to sign up concierge" });
            }
        } catch (error) {
            console.error("Error in signUpConcierge:", error);
            res.status(500).json({
                message: "Error signing up concierge",
                error: error instanceof Error ? error.message : 'Unknown error'
            });
        }
    },
 
    signInConcierge: async (req: CustomRequest, res: Response) => {
        const Email = req.body.credentials;
        const Password = req.body.password;
        try {
            const response = await signInConcierge(Email, Password);
 
            if (typeof response === 'string') {
                res.status(401).send(response);
            } else {
                res.send(response);
            }
        } catch (error) {
            res.status(500).send('Error signing in user');
        }
    },
 
    signUpRoot: async (req: CustomRequest, res: Response) => {
        const AdminInfo: AdminInfo = {
            email: req.body?.credentials.email,
            givenName: req.body?.credentials.givenName,
        }
        const password = req.body.password as string
        try {
            const response = await signUpAdmin(AdminInfo, password as string);
            console.log("SignUpRoot response:", response);
            const address = req.body.address;
            const complexId = uuidv4();
 
            // UserConfirmed can be true (auto-confirmed) or false (email verification required)
            // Both are valid successful signup responses - check for UserSub instead
            if (response && typeof response === "object" && response.UserSub) {
                const company: Company = {
                    PK: 'COMPANY#' + response.UserSub + "o",
                    SK: 'COMPANY#' + response.UserSub + "o",
                    type: "company",
                    root: response.UserSub as string,
                    id: response.UserSub + "o" as string,
                    createdAt: new Date().toISOString(),
                };
 
                await addItem({ TableName: "DELIVERABLES", Item: company }); // Creates new company
                const complex: Complex = {
                    PK: 'COMPANY#' + response.UserSub + "o",
                    SK: 'COMPLEX#' + complexId,
                    type: "complex",
                    id: complexId,
                    address: address,
                    admins: [response.UserSub as string],
                    concierges: [],
                    users: [],
                    createdAt: new Date().toISOString(),
                };
                await addItem({ TableName: "DELIVERABLES", Item: complex }); // Creates new complex
 
                const admin: IAdmin = {
                    PK: 'COMPANY#' + response.UserSub + "o",
                    SK: 'ROOT#' + response.UserSub,
                    type: "root",
                    name: AdminInfo.givenName,
                    email: AdminInfo.email,
                    id: response.UserSub as string,
                    companyId: response.UserSub + "o",
                    complexIds: [complexId],
                    createdAt: new Date().toISOString(),
                };
                await addItem({ TableName: "DELIVERABLES", Item: admin }); // Creates new root admin
 
                res.status(201).json({
                    message: "Admin signed up successfully",
                    userId: response.UserSub,
                    complexId: complexId
                });
            } else if (response && typeof response === "string") {
                console.error(response)
                // Error message from helper (e.g., "Username already exists")
                res.status(400).json({ message: response });
            } else E{
                res.status(400).json({ message: "Failed to sign up admin" });
            }
        } catch (error: any) {
            console.error("Error in signUpRoot:", error);
            res.status(500).json({ message: 'Error signing up user', error: error.message });
        }
    },
 
    signInAdmin: async (req: CustomRequest, res: Response) => {
        const Email = req.body.credentials.email;
        const Password = req.body.password
        try {
            const response = await signInAdmin(Email, Password);
            if (typeof response === "string") {
                res.status(401).send(response);
            }
            if (response && typeof response === "object" && response.sub !== undefined) {
                // Get admin from DynamoDB
                const adminResult = await getByID(response.sub as string); //TODO FIX ANY
                const admin = adminResult.Items;
                console.log(admin);
                const complexIds = admin?.map((item: any) => item.complexIds).flat();
                const companyId = admin?.map((item: any) => item.companyId)[0];
                Eif (admin) {
                    res.send({ ...response, complexIds, companyId });
                }
            }
            else {
                res.status(400).send('Invalid response from signInAdmin');
            }
        } catch (error) {
            res.status(500).send('Error signing in user');
        }
    },
 
    signOutAdmin: async (req: CustomRequest, res: Response) => {
        const AccessToken = req.body.AccessToken;
        try {
            const response = await signOutAdmin(AccessToken);
            res.send(response);
        } catch (error) {
            res.status(500).send('Error signing out user');
        }
    },
 
};
export default authController;