# Auto User Creation

Once SSO is configured, new users won't be able to access the CloudIO application, even after successful authentication, until the user account with the same SSO username is created within CloudIO.

You could automate the process of user account creation in CloudIO by implementing the following cloud function under the `cloudio` app.

{% hint style="info" %}
The function must be defined in the **cloudio** app with Module URI **`create-user`** that exports a named function **`createUser`**.
{% endhint %}

<figure><img src="/files/iae9aOQvEOCXH6bq1qGV" alt=""><figcaption></figcaption></figure>

{% code title="create-user function" overflow="wrap" lineNumbers="true" %}

```typescript
import { IoUserRolesEdit, NewRow } from "@cloudio-saas/datasource-types";

async function createUser({ userName, displayName, emailAddress }) {

    // validate if the userName/emailAddress is allowed to sign-in
    if (!emailAddress.endsWith('@example-domain.com')) {
        throw new UserError(`Email ${emailAddress} is not allowed to sign-in!`);
    }

    let appRoles: Record<string, string[]> = {};

    /*
        // get all the roles by app, that are to be assigned to this userName

        // fetch from a REST API
        const resp = await db.fetch('https://get-user-roles');
        appRoles = resp.json();

        // or fetch from a database table
        const rows = await db.executeQuery('select app_uid `appUid`, role_uid `roleUid` from approved_roles where user_name = ?', [userName]);
        appRoles = rows.reduce((pv, row) => {
            const { appUid, roleUid } = row;
            let roles = pv[appUid];
            if (!roles) {
                roles = [];
                pv[appUid] = roles;
            }
            if (!roles.includes(roleUid)) {
                roles.push(roleUid);
            }
            return pv;
        }, {} as Record<string, string[]>);

        // or hardcode it
        appRoles = {
            cloudio: ['administrator', 'developer', 'patch_administrator'],
            'my-app': ['administrator', 'developer', 'patch_administrator']
        };
    */

    const startDate = new Date();
    startDate.setHours(0, 0, 0, 0);

    // create a user account with the given userName & emailAddress
    await db.insertOne('IoUsers',
        { userName, displayName, emailAddress, startDate }
    );

    let userRoles: NewRow<IoUserRolesEdit>[] = [];
    let seqNo = 0;
    const apps = Object.keys(appRoles);
    for (let i = 0; i < apps.length; i++) {
        const appUid = apps[i];
        const roleCodes = appRoles[appUid];
        roleCodes.forEach((roleUid) => {
            seqNo += 10;
            userRoles.push({
                appUid,
                userName,
                roleUid,
                seqNo,
                startDate,
            });
        });
    }

    // assign roles to the user
    await db.insertMany('IoUserRolesEdit', userRoles);
}

export { createUser };
```

{% endcode %}

Use the following patch to upload the above sample function in cloudio app.

{% file src="/files/65Mmvz7VKKCjgLAVrvkV" %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://next-docs.cloudio.io/app-deployment/configure-sso/auto-user-creation.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
