📦 EqualifyEverything / equalify

📄 updateUser.ts · 55 lines
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
55import { db, cognito, event } from "#src/utils";

export const updateUser = async () => {
    await db.connect();
    const unverifiedAttributes = ['email', 'phone_number'];
    const verifiedAttributes = [];
    const isSsoUser = !event.claims['cognito:username']; // SSO users don't have cognito:username

    console.log(event.claims);

    // First check if we're updating the email or phone number (Cognito users only)
    if (!isSsoUser) {
        for (const unverifiedAttribute of unverifiedAttributes) {
            if (Object.keys(event.body).includes(unverifiedAttribute) && event.claims[unverifiedAttribute] !== event.body[unverifiedAttribute]) {
                try {
                    await cognito.adminUpdateUserAttributes({
                        UserAttributes: [{ Name: unverifiedAttribute, Value: event.body[unverifiedAttribute] }],
                        UserPoolId: process.env.USER_POOL_ID,
                        Username: event.claims['cognito:username']
                    });
                    if (event.body[unverifiedAttribute].length) {
                        verifiedAttributes.push(unverifiedAttribute.replace('_', ' '));
                    }
                }
                catch (err) {
                    return {
                        statusCode: 400,
                        body: JSON.stringify(`There was an error updating your ${unverifiedAttribute}`)
                    }
                }
                if (event.body[unverifiedAttribute].length) {
                    delete event.body[unverifiedAttribute];
                }
            }
        }
    } else {
        // For SSO users, email/phone changes are managed by their SSO provider
        // Remove these attributes from the update
        for (const attr of unverifiedAttributes) {
            if (Object.keys(event.body).includes(attr)) {
                delete event.body[attr];
            }
        }
    }

    for (const [key, value] of Object.entries(event.body)) {
        await db.query({
            text: `UPDATE "users" SET "${key}"=$1 WHERE "id"=$2`,
            values: [value, event.claims.sub]
        });
    }

    await db.clean();
    return JSON.stringify(`Success!${verifiedAttributes.length ? ` Please verify your new ${verifiedAttributes.join(',')} in order to finish updating your profile` : ''}`);
}