/**
 * @license
 * Copyright 2018 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

package foam.dao;

import foam.core.Detachable;
import foam.core.FObject;
import foam.core.X;
import foam.nanos.auth.AuthorizationException;
import foam.nanos.auth.Authorizer;

public class AuthorizationSink
  extends ProxySink
{
  public Authorizer authorizer_;
  public Boolean checkDelete_;

  public AuthorizationSink(X x, Authorizer authorizer, Sink delegate) {
    this(x, authorizer, delegate, false);
  }

  public AuthorizationSink(X x, Authorizer authorizer, Sink delegate, Boolean checkDelete) {
    super(x, delegate);
    authorizer_ = authorizer;
    checkDelete_ = checkDelete;
  }

  @Override
  public void put(Object obj, Detachable sub) {
    try {
      if ( checkDelete_ ) {
        authorizer_.authorizeOnDelete(getX(), (FObject) obj);
      } else {
        authorizer_.authorizeOnRead(getX(), (FObject) obj);
      }
      super.put(obj, sub);
    } catch ( AuthorizationException e ) {
      // Do not put to sink if not authorized.
    }
  }
}

@@ -771,24 +771,56 @@
 able sub) %7B%0A
+    Boolean authorized = true;%0A%0A
     try %7B%0A  
@@ -817,16 +817,16 @@
   try %7B%0A
-
       if
@@ -994,35 +994,8 @@
   %7D%0A
-      super.put(obj, sub);%0A
     
@@ -1043,54 +1043,413 @@
     
-// Do not put to sink if not authorized.%0A    %7D
+authorized = false;%0A    %7D%0A%0A    // The reason this isn't just at the end of the try block above is because%0A    // if a sink down the delegate chain wants to throw an%0A    // AuthorizationException, we don't want it to be caught and ignored. We%0A    // only want to catch and ignore AuthorizationExceptions thrown by%0A    // %60authorizeOnRead%60 and %60authorizeOnDelete%60.%0A    if ( authorized ) super.put(obj, sub);
 %0A  %7D

Fix bug in AuthorizationSink logic