# User Auth Example

> See how to authenticate a database user in API Maker using authAMDB, complete with setup and sample token data.

Source: https://docs.apimaker.dev/v1/examples/req/auth/authAMDB.html

<!-- --8<-- [start:body] -->

### Authorization of AM database user

To get the value of request header `x-am-user-authorization`, use `g.req.auth.authAMDB`. 

```ts
const database_user_auth = g.req.auth.authAMDB;
```

## Custom API example to get token

```typescript
import * as T from 'types';
import * as db from 'db-interfaces';

// Database table information
const instanceName = 'mongodb';
const databaseName = 'Company';
const tableName = 'auth_users';
const userNameColumn = 'email';
const passwordColumn = 'password';
const userTypeColumn = 'userType';

/*
import * as T from 'types';

let Secret: T.ISecretType | any = {
    common: <T.ISecretTypeCommon>{
        apiUserPasswords: {
            ADMIN: 'admin_1234', // 👈 apiUserPasswords
            guest: 'guest_1234',
        },
    }
};
module.exports = Secret;
*/

async function main(g: T.IAMGlobal) {
    const userNameFromRequest = g.req.body.userName || null;
    const passwordFromRequest = g.req.body.password || null;

    const userData: db.mongodb.Company.IAuthUsers = await g.sys.db.getById({
        instance: instanceName, database: databaseName, collection: tableName,
        primaryKey: userNameColumn,
        id: userNameFromRequest,
    });

    if (!userData) throw new Error('Invalid credentials.');
    const encryptSecret = await g.sys.system.getSecret("common.secret");
    const decryptedPass = await g.sys.system.decrypt(
        userData.password,
        T.EEncryptionAlgorithm.AES,
        encryptSecret
    );

    let tokens: any = {};
    if (decryptedPass === passwordFromRequest) {
        const adminUserName = userData.userType;
        const adminUserPass = await g.sys.system.getSecret(
            "common.apiUserPasswords." + userData[userTypeColumn]  // 👈 apiUserPasswords
        );

        const outputArr = await g.sys.system.getToken([
            { authTokenType: T.EAuthTokenType.AM, "authTokenAM": { "u": adminUserName, "p": adminUserPass } },
            {
                authTokenType: T.EAuthTokenType.AM_DB,
                authTokenAMDB: {
                    instance: instanceName, database: databaseName, collection: tableName,
                    usernameColumn: userNameColumn, passwordColumn: passwordColumn,
                    u: userNameFromRequest,
                    p: passwordFromRequest,
                }
            }
        ]);

        tokens.amToken = outputArr[0];
        tokens.amDbToken = outputArr[1];
    }
    return tokens;
};
module.exports = main;
```

### Setting sample object

- Provide the groups name comma separated in the 'groupsColumn' field and provide the 'instance', 'database', 'table' from which that 'groupsColumn' exist.
- With `passwordChangedAtColumn` (v1.11.0+), the JWT token holds the value of that column instead of the password. Update it on every password change: tokens and refresh tokens made before the change stop working.

```json linenums="1"
{
    "authTokenType": "AM_DB",
    "authTokenAMDB": {
        "instance": "INSTANCE_NAME",
        "database": "DATABASE_NAME",
        "collection": "COLLECTION_NAME",
        "usernameColumn": "USER_NAME_COLUMN",
        "passwordColumn": "USER_PASSWORD_COLUMN",
        "passwordChangedAtColumn": "passwordChangedAt",
        "groupsColumn": "COMMA_SEPARATED_GROUPS",
        "select": {
            "COLUMN_NAME1": 1,
            "COLUMN_NAME2": 1
        }
    }
}
```

### Get token

- Get a token of API Maker's database user(application user).
- For more information [click here](/v1/docs/apis-all/system-apis/system-generated-token-api.html).

```json linenums="1"
{
    "authTokenType": "AM_DB",
    "authTokenAMDB": {
        "instance": "INSTANCE_NAME",
        "database": "DATABASE_NAME",
        "collection": "COLLECTION_NAME",
        "usernameColumn": "USER_NAME_COLUMN",
        "passwordColumn": "USER_PASSWORD_COLUMN",
        "u": "USER_NAME",
        "p": "PASSWORD"
    }
}
```

<!-- --8<-- [end:body] -->

## Related

- [The global object g](/v1/docs/pre-defined-terms/global-object-g.html) · [Custom APIs](/v1/docs/apis-all/custom-apis/user-created-custom-api.html)
