Page 1 of 1

Debtor API Key

PostPosted: Fri Nov 01, 2019 11:14 am
by SBarnes
Is there a way to determine who the debtor is when a call to the API is made using a debtor api key?

Re: Debtor API Key  Topic is solved

PostPosted: Fri Nov 01, 2019 1:58 pm
by Mike.Sheen
Sure - the nature of how the user was authenticated is stored in properties of the Database object - which is a property of the Manager.

So - in our standard REST API plugin you'll see numerous places where we check if the request was authenticated using a debtor API Key and then see if the debtor associated with that key is permitted to see the record requested:

Code: Select all
public void DebtorAPIKeySalesOrderGETRequestFilter(IRequest req, IResponse res, JiwaServiceModel.SalesOrderGETRequest dto)
{
   // This filter is designed to be used when customers authenticated via Debtor API Key are retrieving an order.
   // We want to make sure only orders belonging to the customer are able to be retrieved
   JiwaAuthUserSession session = (JiwaAuthUserSession)req.GetSession();

   if (session == null || session.Manager == null || session.Manager.Database.APIKey_Type != "Debtor")
      return;
   
   if (Helper.Service.IsStateful(req))
   {
      // a stateful request should always fetch from the in-memory ObjectDictionary instead of the database
      object objectDictionaryValue = null;
      if (!session.Manager.ObjectDictionary.TryGetValue(dto.InvoiceID, out objectDictionaryValue))
         throw new JiwaApplication.Exceptions.RecordNotFoundException();
      else
      {
         // Check the debtor this sales order belongs to is the same as the one associated with the Debtor API Key
         JiwaFinancials.Jiwa.JiwaSales.SalesOrder.SalesOrder salesOrder = (JiwaFinancials.Jiwa.JiwaSales.SalesOrder.SalesOrder)objectDictionaryValue;
         if (salesOrder.Debtor.DebtorID != session.Manager.Database.APIKey_PrincipalID)
            throw new JiwaApplication.Exceptions.RecordNotFoundException();
      }
   }
   else
   {
      var Db = AppHost.GetDbConnection();
      SO_Main salesOrder = Db.Single(Db.From<SO_Main>().Where(x => x.InvoiceID == dto.InvoiceID).Take(1));
      if (salesOrder != null && session.Manager.Database.APIKey_PrincipalID != salesOrder.DebtorID)
         throw new JiwaApplication.Exceptions.RecordNotFoundException();
   }           
}


It's the session.Manager.Database.APIKey_Type == "Debtor" and the session.Manager.Database.APIKey_PrincipalID (DebtorID when key type is "Debtor") that is what you're after.

Re: Debtor API Key

PostPosted: Fri Nov 01, 2019 3:25 pm
by SBarnes
Thanks