Skip to content

CodeCoupler API Auth Login Hook

You can register an hook which will be called before the login process starts. The hook function gets the username and the password to validate. The function have to:

  • Return an object with the permissions of the user and optional an external id if the login succeed
  • null if the login process should continue against the internal user database
  • Throw an HttpErrors.Unauthorized or an HttpErrors.NotFound if login failed

Registering the function and some examples of how to handle the different situations:

 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
//Add this code into your Application Class
this.bind(CcApiAuthComponentBindings.AUTHENTICATION_STRATEGIES_HOOKS).to({
  //Define the function "login" which recieve an unsername and a password
  login: async (username, password, response) => {
    //Look somewhere if username and password is correct. Here just an example
    //in wich an "externaluser" with "externalpassword" can login:
    if (username === "externaluser") {
      if (password === "externalpassword") {
        //If everything worked, you can modify the response if needed.
        //Do not use a cookie name like defined in your ".env". This
        //will already set.
        // response.cookie("TokenName", "TokenContent", {
        //   maxAge: 1000, //Maximal age in Milliseconds
        //   sameSite: 'strict', //Set this to avoid browser warnings
        // });
        //If everything worked, return the following object:
        return {
          app: this,
          permissions: ["externalpermission"],
          externalId: null, //Keep in mind: This must be a string or null
        };
      } else {
        //If the password was wrong, throw this Exception:
        throw new HttpErrors.Unauthorized("The credentials are not correct.");
      }
    } else if (username === "admin") {
      //You can specify some paths where the internal database should be used.
      //Usefull for default users and passwords which always resists in the
      //user database. Return in this case "null":
      return null;
    } else {
      //If the user is unknown you could throw this Exception:
      throw new HttpErrors.NotFound(`User not found.`);
    }
  },
});

If the login hook returns an succesfull login, the user, the external id and the permissions will be added into the internal database. The user will be marked as "enabled" and the permissions will be assigned to the user as "allowed".

For existing users the password and the externalId will be updated. With this you could implement a fallback if the external authorization fails for network reasons.