Backend: Handling Response

Register or Login your user to your Database

When the user is authenticated, you will receive a response similar to this from your front end. Your frontend is reponsible for sending this payload to your server.

{
    "email": "myemail@gmail.com", // User's email (or phone number)
    "oauth_token": {
        "access_token": "eyJhbGciOiJFUzI1NiIsImt...", // Access Token to validate
        "id_token": "eyJhbGciOiJFUzI1Ni...",
        "refresh_token": "27805:CNf76faa8trMhjXM...",
        "expires_in": 3600,
        "token_type": "Bearer",
        "auth_method": "OTP"
    },
    "user": {
        "ID": "abcdefgh-abcd-abcd-abcd-af6f81fb5432", // Cotter User ID
        "created_at": "2020-07-21T05:50:14.182738Z",
        "updated_at": "2020-07-21T06:00:47.115096Z",
        "deleted_at": "0001-01-01T00:00:00Z",
        "issuer": "<YOUR_API_KEY_ID>",
        "identifier": "putrikarunian@gmail.com"
    }
}

Send this payload to your backend to register or login the user in your database. A typical flow would look like this:

  1. Validate the access token

  2. Check if the email exists in your database

    • If it doesn't exists: Create a new user

    • If it exists: Continue login

  3. (Optional) If you want to use your own session tokens, set the cookie here after validating the access token.

  4. (Optional) if you want to use Cotter's tokens, either store Cotter's access token in the cookie or on the front-end side.

Examples:

const express = require("express");
const app = express();
var cors = require("cors");
var bodyParser = require("body-parser");
var cotterNode = require("cotter-node");
var cotterToken = require("cotter-token-js");
var session = require("express-session");
const port = 3005;
app.use(cors());
app.use(bodyParser.json());


// EXAMPLE LOGIN ENDPOINT
app.post("/login", async (req, res) => {
  console.log(req.body);

  // Validate access token
  const access_token = req.body.oauth_token.access_token;
  var valid = false;
  try {
    valid = await cotterNode.CotterValidateJWT(access_token);
  } catch (e) {
    valid = false;
  }
  if (!valid) {
    res.status(403).end("Invalid access token");
    return;
  }

  // (Optional) Read access token
  let decoded = new cotterToken.CotterAccessToken(access_token);
  console.log(decoded);
    
  // (Optional) Register or Login User

  // (Optional) Set access token as cookie

  res.status(200).json(decoded.payload).end();
});

app.listen(port, () =>
  console.log(`Example app listening at http://localhost:${port}`)
);

Validating Cotter's Access Token

Read more on how to verify the OAuth Tokens from Cotter here:

Last updated