Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *    Purpose: A class that handles checking permssision for a document
4
               and subtree in a document
5
 *
6
 *  Copyright: 2000 Regents of the University of California and the
7
 *             National Center for Ecological Analysis and Synthesis
8
 *    Authors: Chad Berkley
9
 *
10
 *   '$Author: leinfelder $'
11
 *     '$Date: 2011-06-23 17:10:56 -0700 (Thu, 23 Jun 2011) $'
12
 * '$Revision: 6196 $'
13
 *
14
 * This program is free software; you can redistribute it and/or modify
15
 * it under the terms of the GNU General Public License as published by
16
 * the Free Software Foundation; either version 2 of the License, or
17
 * (at your option) any later version.
18
 *
19
 * This program is distributed in the hope that it will be useful,
20
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22
 * GNU General Public License for more details.
23
 *
24
 * You should have received a copy of the GNU General Public License
25
 * along with this program; if not, write to the Free Software
26
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
27
 */
28
package edu.ucsb.nceas.metacat;
29

    
30
import java.sql.*;
31
import java.util.Enumeration;
32
import java.util.Hashtable;
33
import java.util.Stack;
34
import java.util.Vector;
35
import java.util.Iterator;
36

    
37
import org.apache.log4j.Logger;
38

    
39
import edu.ucsb.nceas.metacat.accesscontrol.AccessControlForSingleFile;
40
import edu.ucsb.nceas.metacat.accesscontrol.AccessControlInterface;
41
import edu.ucsb.nceas.metacat.accesscontrol.AccessControlList;
42
import edu.ucsb.nceas.metacat.database.DBConnection;
43
import edu.ucsb.nceas.metacat.database.DBConnectionPool;
44
import edu.ucsb.nceas.metacat.properties.PropertyService;
45
import edu.ucsb.nceas.metacat.service.SessionService;
46
import edu.ucsb.nceas.metacat.util.DocumentUtil;
47
import edu.ucsb.nceas.metacat.util.MetacatUtil;
48
import edu.ucsb.nceas.metacat.util.SessionData;
49
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
50
import edu.ucsb.nceas.metacat.shared.ServiceException;
51

    
52
public class PermissionController
53
{
54
   private String docId = null;
55
   private boolean hasSubTreeAccessControl = false; // flag if has a subtree
56
                                                    // access for this docid
57
   private Vector subTreeList = new Vector();
58

    
59
   private static final long TOPLEVELSTARTNODEID = 0; //if start node is 0, means it is top
60
                                         //level document
61

    
62
   private static Logger logMetacat = Logger.getLogger(PermissionController.class);
63

    
64
   /**
65
    * Constructor for PermissionController
66
    * @param myDocid      the docid need to access
67
    */
68
   public PermissionController(String myDocid) throws McdbException
69
   {
70
     // Get rid of rev number
71
     docId = DocumentUtil.getSmartDocId(myDocid);
72
     //hasSubTreeAccessControl = checkSubTreeAccessControl();
73
   }
74

    
75
   /**
76
    * Constructor for PermssionController
77
    * @param myDocid String
78
    * @param needDeleteRev boolean
79
    */
80
   public PermissionController(String myDocid, boolean needDeleteRevFromDocid)
81
   {
82
     if (!needDeleteRevFromDocid)
83
     {
84
       docId = myDocid;
85
     }
86
     else
87
     {
88
         docId = DocumentUtil.getDocIdFromAccessionNumber(myDocid);
89
     }
90
   }
91

    
92
   /**
93
    * Return if a document has subtree access control
94
    */
95
   public boolean hasSubTreeAccessControl()
96
   {
97
     return hasSubTreeAccessControl;
98
   }
99

    
100
   public boolean hasPermission(String sessionId, String myPermission) throws SQLException {
101
       SessionData sessionData = null;
102
       sessionData = SessionService.getInstance().getRegisteredSession(sessionId);
103
       if (sessionData == null) {
104
           return false;
105
       }
106
	   
107
	   return hasPermission(sessionData.getUserName(), sessionData.getGroupNames(), myPermission); 
108
   }
109
   
110

    
111
  /**
112
    * Check from db connection if at least one of the list of @principals
113
    * @param user  the user name
114
    * @param groups  the groups which the use is in
115
    * @param myPermission  permission type to check for
116
    */
117
  public boolean hasPermission(String user, String[]groups, String myPermission)
118
                              throws SQLException //, Exception
119
  {
120
    boolean hasPermission=false;
121
    String [] userPackage=null;
122
    int permission = AccessControlList.intValue(myPermission);
123

    
124
    //for the commnad line invocation
125
    if ((user==null) && (groups==null || groups.length==0))
126
    {
127
      return true;
128
    }
129

    
130
    //create a userpackage including user, public and group member
131
    userPackage=createUsersPackage(user, groups);
132

    
133
    //if the requested document is access documents and requested permission
134
    //is "write", the user should have "all" right
135

    
136
    if (isAccessDocument(docId) && (permission == AccessControlInterface.WRITE))
137
    {
138

    
139
      hasPermission = hasPermission(userPackage,docId, 7);// 7 is all permission
140
    }//if
141
    else //in other situation, just check the request permission
142
    {
143
      // Check for @permission on @docid for @user and/or @groups
144
      hasPermission = hasPermission(userPackage,docId, permission);
145
    }//else
146

    
147
    return hasPermission;
148
  }
149

    
150

    
151
  /**
152
    * Check from db connection if the users in String array @principals has
153
    * @permission on @docid*
154
    * @param principals, names in userPakcage need to check for @permission
155
    * @param docid, document identifier to check on
156
    * @param permission, permission (write or all...) to check for
157
    */
158
  private boolean hasPermission(String [] principals, String docId,
159
                                           int permission)
160
                         throws SQLException
161
  {
162
    long startId = TOPLEVELSTARTNODEID;// this is for top level, so startid is 0
163
    try
164
    {
165
      //first, if there is a docid owner in user package, return true
166
      //because doc owner has all permssion
167
      if (containDocumentOwner(principals, docId))
168
      {
169

    
170
          return true;
171
      }
172

    
173
      //If there is no owner in user package, checking the table
174
      //check perm_order
175
      if (isAllowFirst(principals, docId, startId))
176
      {
177

    
178
        if (hasExplicitDenyRule(principals, docId, permission, startId))
179
        {
180
          //if it is allowfirst and has deny rule(either explicit )
181
          //deny access
182

    
183
          return false;
184
        }//if
185
        else if ( hasAllowRule(principals, docId, permission, startId))
186
        {
187
          //if it is allowfirst and hasn't deny rule and has allow rule
188
          //allow access
189

    
190
          return true;
191
        }//else if
192
        else
193
        {
194
          //other situation deny access
195

    
196
          return false;
197
        }//else
198
     }//if isAllowFirst
199
     else //denyFirst
200
     {
201
       if (hasAllowRule(principals, docId, permission, startId))
202
       {
203
         //if it is denyFirst and has allow rule, allow access
204
         return true;
205
       }
206
       else
207
       {
208
         //if it is denyfirst but no allow rule, deny access
209
         return false;
210
       }
211
     }//else denyfirst
212
    }//try
213
    catch (Exception e)
214
    {
215
      logMetacat.warn("PermissionController.hasPermission - There is a exception in hasPermission method: "
216
                         +e.getMessage());
217
    }
218

    
219
    return false;
220
  }//hasPermission
221

    
222
  /**
223
   *  Method to check if a person has permission to a inline data file
224
   * @param user String
225
   * @param groups String[]
226
   * @param myPermission String
227
   * @param inlineDataId String
228
   * @throws McdbException
229
   * @return boolean
230
   */
231
  private boolean hasPermissionForInlineData(String user, String[] groups,
232
                                      String myPermission, String inlineDataId)
233
      throws McdbException
234
  {
235
     // this method can call the public method - hasPermission(...)
236
     // the only difference is about the ownership, you couldn't find the owner
237
     // from inlinedataId directly. You should get it from eml document itself
238
     String []userPackage = createUsersPackage(user, groups);
239
     try {
240
        if (containDocumentOwner(userPackage, docId))
241
         {
242
           return true;
243
         }
244
         else
245
         {
246
             PermissionController controller =
247
                                   new PermissionController(inlineDataId, false);
248
             return controller.hasPermission(user, groups, myPermission);
249
         }
250
    } catch (SQLException e) {
251
        throw new McdbException(e.getMessage());
252
    }
253
  }
254

    
255
  /**
256
   * The method to determine of a node can be access by a user just by subtree
257
   * access control
258
   */
259
  public boolean hasPermissionForSubTreeNode(String user, String[] groups,
260
                                             String myPermission, long nodeId)
261
                                             throws McdbException
262
  {
263
    boolean flag = true;
264
    // Get unaccessble subtree for this user
265
    Hashtable unaccessableSubTree = hasUnaccessableSubTree(user, groups,
266
                                                           myPermission);
267
    Enumeration en = unaccessableSubTree.elements();
268
    while (en.hasMoreElements())
269
    {
270
      SubTree tree = (SubTree)en.nextElement();
271
      long start = tree.getStartNodeId();
272
      long stop  = tree.getEndNodeId();
273
      // nodeid in unaccessablesubtree, return false
274
      if ( nodeId >= start && nodeId <= stop)
275
      {
276
        flag = false;
277
        break;
278
      }
279
    }
280
    return flag;
281
  }
282
  /**
283
   * This method will return a hasTable of subtree which user doesn't has the
284
   * permssion to access
285
   * @param user  the user name
286
   * @param groups  the groups which the use is in
287
   * @param myPermission  permission type to check for
288
   */
289
  public Hashtable hasUnaccessableSubTree(String user, String[] groups,
290
                                       String myPermission) throws McdbException
291
  {
292
    Hashtable resultUnaccessableSubTree = new Hashtable();
293
    String [] principals=null;
294
    int permission =AccessControlList.intValue(myPermission);
295

    
296
    //for the commnad line invocation return null(no unaccessable subtree)
297
    if ((user==null) && (groups==null || groups.length==0))
298
    {
299
      return resultUnaccessableSubTree;
300
    }
301

    
302
    //create a userpackage including user, public and group member
303
    principals=createUsersPackage(user, groups);
304
    //for the document owner return null(no unaccessable subtree)
305
    try
306
    {
307
      if (containDocumentOwner(principals, docId))
308
      {
309
       return resultUnaccessableSubTree;
310
      }
311
    }
312
    catch (SQLException ee)
313
    {
314
      throw new McdbException(ee);
315
    }
316

    
317
    // go through every subtree which has access control
318
    for (int i = 0; i< subTreeList.size(); i++)
319
    {
320
      SubTree tree = (SubTree)subTreeList.elementAt(i);
321
      long startId = tree.getStartNodeId();
322

    
323

    
324
        try
325
        {
326
          if (isAllowFirst(principals, docId, startId))
327
          {
328

    
329
            if (hasExplicitDenyRule(principals, docId, permission, startId ))
330
            {
331

    
332
             //if it is allowfirst and has deny rule
333
              // put the subtree into unaccessable vector
334
              if (!resultUnaccessableSubTree.containsKey(new Long(startId)))
335
              {
336
                resultUnaccessableSubTree.put(new Long(startId), tree);
337
              }
338
            }//if
339
            else if ( hasAllowRule(principals, docId, permission, startId))
340
            {
341
              //if it is allowfirst and hasn't deny rule and has allow rule
342
              //allow access do nothing
343

    
344
            }//else if
345
            else
346
            {
347
              //other situation deny access
348
              if (!resultUnaccessableSubTree.containsKey(new Long(startId)))
349
              {
350
                resultUnaccessableSubTree.put(new Long(startId), tree);
351
              }
352

    
353
            }//else
354
          }//if isAllowFirst
355
          else //denyFirst
356
          {
357
            if (hasAllowRule(principals, docId, permission,startId))
358
            {
359
              //if it is denyFirst and has allow rule, allow access, do nothing
360

    
361
            }
362
            else
363
            {
364
              //if it is denyfirst but no allow rule, deny access
365
              // add into vector
366
              if (!resultUnaccessableSubTree.containsKey(new Long(startId)))
367
              {
368
                resultUnaccessableSubTree.put(new Long(startId), tree);
369
              }
370
            }
371
          }//else denyfirst
372
        }//try
373
        catch( Exception e)
374
        {
375
          logMetacat.error("PermissionController.hasUnaccessableSubTree - error in PermissionControl.has" +
376
                                   "UnaccessableSubTree "+e.getMessage());
377
          throw new McdbException(e);
378
        }
379

    
380
    }//for
381
    // merge the subtree if a subtree is another subtree'subtree
382
    resultUnaccessableSubTree = mergeEquivalentSubtree(resultUnaccessableSubTree);
383
    return resultUnaccessableSubTree;
384
  }//hasUnaccessableSubtree
385

    
386

    
387
  /*
388
   * A method to merge nested subtree into bigger one. For example subtree b
389
   * is a subtree of subtree a. And user doesn't have read permission for both
390
   * so we only use subtree a is enough.
391
   */
392
  private Hashtable mergeEquivalentSubtree(Hashtable unAccessSubTree)
393
  {
394
    Hashtable newSubTreeHash = new Hashtable();
395
    boolean   needDelete = false;
396
    // check the parameters
397
    if (unAccessSubTree == null || unAccessSubTree.isEmpty())
398
    {
399
      return newSubTreeHash;
400
    }
401
    else
402
    {
403
      // look every subtree start point and stop point, to see if it is embedded
404
      // in another one. If embedded, they are equavelent and we can use bigger
405
      // one to replace smaller one
406
      Enumeration en = unAccessSubTree.elements();
407
      while (en.hasMoreElements())
408
      {
409
        SubTree tree    = (SubTree)en.nextElement();
410
        String  treeId  = tree.getSubTreeId();
411
        long    startId = tree.getStartNodeId();
412
        long    endId   = tree.getEndNodeId();
413

    
414
        Enumeration enu = unAccessSubTree.elements();
415
        while (enu.hasMoreElements())
416
        {
417
          SubTree subTree = (SubTree)enu.nextElement();
418
          String subTreeId= subTree.getSubTreeId();
419
          long   subTreeStartId = subTree.getStartNodeId();
420
          long   subTreeEndId   = subTree.getEndNodeId();
421
          //compare and if the first subtree is a subtree of the second
422
          // one, set neeDelete true
423
          if (startId > subTreeStartId && endId < subTreeEndId)
424
          {
425
            needDelete = true;
426
            logMetacat.info("PermissionController.mergeEquivalentSubtree - the subtree: "+ treeId +
427
                                     " need to be get rid of from unaccessable"+
428
                                     " subtree list becuase it is a subtree of"+
429
                                     " another subtree in the list");
430
            break;
431
          }//if
432
        }//while
433
        // if not need to delete, put the subtree into hash
434
        if (!needDelete)
435
        {
436
          newSubTreeHash.put(new Long(startId), tree);
437
        }
438
        //reset needDelete
439
        needDelete = false;
440
      }//while
441
      return newSubTreeHash;
442
    }//else
443
  }
444

    
445
  /**
446
	 * Check if a document id is a access document. Access document need user
447
	 * has "all" permission to access it.
448
	 * 
449
	 * @param docId,
450
	 *            the document id need to be checked
451
	 */
452
	private boolean isAccessDocument(String docId) throws SQLException {
453
		// detele the rev number if docid contains it
454
		docId = DocumentUtil.getDocIdFromString(docId);
455
		PreparedStatement pStmt = null;
456
		DBConnection conn = null;
457
		int serialNumber = -1;
458
		try {
459
			// check out DBConnection
460
			conn = DBConnectionPool.getDBConnection("PermissionControl.isAccessDoc");
461
			serialNumber = conn.getCheckOutSerialNumber();
462
			pStmt = conn.prepareStatement("select doctype from xml_documents where "
463
					+ "docid like '" + docId + "'");
464
			pStmt.execute();
465
			ResultSet rs = pStmt.getResultSet();
466
			boolean hasRow = rs.next();
467
			String doctype = null;
468
			if (hasRow) {
469
				doctype = rs.getString(1);
470

    
471
			}
472
			pStmt.close();
473

    
474
			// if it is an access document
475
			if (doctype != null
476
					&& ((MetacatUtil.getOptionList(PropertyService
477
							.getProperty("xml.accessdoctype")).contains(doctype)))) {
478

    
479
				return true;
480
			}
481

    
482
		} catch (SQLException e) {
483
			throw new SQLException("PermissionControl.isAccessDocument "
484
					+ "Error checking" + " on document " + docId + ". " + e.getMessage());
485
		} catch (PropertyNotFoundException pnfe) {
486
			throw new SQLException("PermissionControl.isAccessDocument "
487
					+ "Error checking" + " on document " + docId + ". " + pnfe.getMessage());
488
		} finally {
489
			try {
490
				pStmt.close();
491
			} finally {
492
				DBConnectionPool.returnDBConnection(conn, serialNumber);
493
			}
494
		}
495

    
496
		return false;
497
	}// isAccessDocument
498

    
499

    
500

    
501
  /**
502
	 * Check if a stirng array contains a given documents' owner
503
	 * 
504
	 * @param principals,
505
	 *            a string array storing the username, groups name and public.
506
	 * @param docid,
507
	 *            the id of given documents
508
	 */
509
  private boolean containDocumentOwner( String[] principals, String docId)
510
                    throws SQLException
511
  {
512
    int lengthOfArray=principals.length;
513
    boolean hasRow;
514
    PreparedStatement pStmt=null;
515
    DBConnection conn = null;
516
    int serialNumber = -1;
517

    
518
    try
519
    {
520
      //check out DBConnection
521
     conn=DBConnectionPool.getDBConnection("PermissionControl.containDocOnwer");
522
      serialNumber=conn.getCheckOutSerialNumber();
523
      pStmt = conn.prepareStatement(
524
                "SELECT 'x' FROM xml_documents " +
525
                "WHERE docid = ? AND lower(user_owner) = ? " +
526
                "UNION ALL " +
527
                "SELECT 'x' FROM xml_revisions " +
528
                "WHERE docid = ? AND lower(user_owner) = ? ");
529
      //check every element in the string array too see if it conatains
530
      //the owner of document
531
      for (int i=0; i<lengthOfArray; i++)
532
      {
533

    
534
        // Bind the values to the query
535
        pStmt.setString(1, docId);
536
        pStmt.setString(2, principals[i]);
537
        pStmt.setString(3, docId);
538
        pStmt.setString(4, principals[i]);
539
        logMetacat.info("PermissionController.containDocumentOwner - the principle stack is : " +
540
                                  principals[i]);
541

    
542
        pStmt.execute();
543
        ResultSet rs = pStmt.getResultSet();
544
        hasRow = rs.next();
545
        if (hasRow)
546
        {
547
          pStmt.close();
548
           logMetacat.info("PermissionController.containDocumentOwner - find the owner");
549
          return true;
550
        }//if
551

    
552
      }//for
553
    }//try
554
    catch (SQLException e)
555
    {
556
        pStmt.close();
557

    
558
        throw new
559
        SQLException("PermissionControl.hasPermission - " +
560
                     "Error checking ownership for " + principals[0] +
561
                     " on document #" + docId + ". " + e.getMessage());
562
    }//catch
563
    finally
564
    {
565
      try
566
      {
567
        pStmt.close();
568
      }
569
      finally
570
      {
571
        DBConnectionPool.returnDBConnection(conn, serialNumber);
572
      }
573
    }
574
    return false;
575
  }//containDocumentOwner
576

    
577
  /**
578
    * Check if the permission order for user at that documents is allowFirst
579
    * @param principals, list of names of principals to check for
580
    * @param docid, document identifier to check for
581
    */
582
  private boolean isAllowFirst(String [] principals, String docId,
583
                               long startId)
584
                  throws SQLException, Exception
585
  {
586
    int lengthOfArray=principals.length;
587
    boolean hasRow;
588
    PreparedStatement pStmt = null;
589
    DBConnection conn = null;
590
    int serialNumber = -1;
591
    String sql = null;
592
    boolean topLever =false;
593
    if (startId == TOPLEVELSTARTNODEID)
594
    {
595
      //top level
596
      topLever = true;
597
      sql = "SELECT perm_order FROM xml_access " +
598
    "WHERE lower(principal_name) = ? AND docid = ? AND startnodeid is NULL";
599
    }
600
    else
601
    {
602
      //sub tree level
603
      sql = "SELECT perm_order FROM xml_access " +
604
        "WHERE lower(principal_name)= ? AND docid = ? AND startnodeid = ?";
605
    }
606

    
607
    try
608
    {
609
      //check out DBConnection
610
      conn=DBConnectionPool.getDBConnection("AccessControlList.isAllowFirst");
611
      serialNumber=conn.getCheckOutSerialNumber();
612

    
613
      //select permission order from database
614
      pStmt = conn.prepareStatement(sql);
615

    
616
      //check every name in the array
617
      for (int i=0; i<lengthOfArray;i++)
618
      {
619
        //bind value
620
        pStmt.setString(1, principals[i]);//user name
621
        pStmt.setString(2, docId);//docid
622

    
623
        // if subtree, we need set subtree id
624
        if (!topLever)
625
        {
626
          pStmt.setLong(3, startId);
627
        }
628

    
629
        pStmt.execute();
630
        ResultSet rs = pStmt.getResultSet();
631
        hasRow=rs.next();
632
        if (hasRow)
633
        {
634
          //get the permission order from data base
635
          String permissionOrder=rs.getString(1);
636
          //if the permission order is "allowFirst
637
          if (permissionOrder.equalsIgnoreCase(AccessControlInterface.ALLOWFIRST))
638
          {
639
            pStmt.close();
640
            return true;
641
          }
642
          else
643
          {
644
            pStmt.close();
645
            return false;
646
          }
647
        }//if
648
      }//for
649
    }//try
650
    catch (SQLException e)
651
    {
652
      throw e;
653
    }
654
    finally
655
    {
656
      try
657
      {
658
        pStmt.close();
659
      }
660
      finally
661
      {
662
        DBConnectionPool.returnDBConnection(conn, serialNumber);
663
      }
664
    }
665

    
666
    //if reach here, means there is no permssion record for given names and
667
    //docid. So throw a exception.
668

    
669
    throw new Exception("PermissionController.isAllowFirst - There is no permission record for user "+ principals[0] + 
670
                        " at document " + docId);
671

    
672
  }//isAllowFirst
673

    
674
  /**
675
    * Check if the users array has allow rules for given users, docid and
676
    * permission.
677
    * If it has permission rule and ticket count is greater than 0, the ticket
678
    * number will decrease one for every allow rule
679
    * @param principals, list of names of principals to check for
680
    * @param docid, document identifier to check for
681
    * @param permission, the permssion need to check
682
    */
683
  private boolean hasAllowRule(String [] principals, String docId,
684
                                  int permission, long startId)
685
                  throws SQLException, Exception
686
 {
687
   int lengthOfArray=principals.length;
688
   boolean allow=false;//initial value is no allow rule
689
   ResultSet rs;
690
   PreparedStatement pStmt = null;
691
   int permissionValue=permission;
692
   int permissionValueInTable;
693
   int ticketCount;
694
   DBConnection conn = null;
695
   int serialNumber = -1;
696
   boolean topLever = false;
697
   String sql = null;
698
   if (startId == TOPLEVELSTARTNODEID)
699
   {
700
     // for toplevel
701
     topLever = true;
702
     sql = "SELECT permission FROM xml_access WHERE docid = ? " +
703
   "AND lower(principal_name) = ? AND perm_type = ? AND startnodeid is NULL";
704
   }
705
   else
706
   {
707
     topLever =false;
708
     sql = "SELECT permission FROM xml_access WHERE docid = ? " +
709
      "AND lower(principal_name) = ? AND perm_type = ? AND startnodeid = ?";
710
   }
711
   try
712
   {
713
     //check out DBConnection
714
     conn=DBConnectionPool.getDBConnection("AccessControlList.hasAllowRule");
715
     serialNumber=conn.getCheckOutSerialNumber();
716
    //This sql statement will select entry with
717
    //begin_time<=currentTime<=end_time in xml_access table
718
    //If begin_time or end_time is null in table, isnull(begin_time, sysdate)
719
    //function will assign begin_time=sysdate
720
    pStmt = conn.prepareStatement(sql);
721
    //bind docid, perm_type
722
    pStmt.setString(1, docId);
723
    pStmt.setString(3, AccessControlInterface.ALLOW);
724

    
725
    // if subtree lever, need to set subTreeId
726
    if (!topLever)
727
    {
728
      pStmt.setLong(4, startId);
729
    }
730

    
731
    //bind every elenment in user name array
732
    for (int i=0;i<lengthOfArray; i++)
733
    {
734
      pStmt.setString(2, principals[i]);
735
      pStmt.execute();
736
      rs=pStmt.getResultSet();
737
      while (rs.next())//check every entry for one user
738
      {
739
        permissionValueInTable=rs.getInt(1);
740

    
741
        //permission is ok
742
        //the user have a permission to access the file
743
        if (( permissionValueInTable & permissionValue )== permissionValue )
744
        {
745

    
746
           allow=true;//has allow rule entry
747
        }//if
748
      }//while
749
    }//for
750
   }//try
751
   catch (SQLException sqlE)
752
   {
753
     throw sqlE;
754
   }
755
   catch (Exception e)
756
   {
757
     throw e;
758
   }
759
   finally
760
   {
761
     try
762
     {
763
       pStmt.close();
764
     }
765
     finally
766
     {
767
       DBConnectionPool.returnDBConnection(conn, serialNumber);
768
     }
769
   }
770
    return allow;
771
 }//hasAllowRule
772

    
773

    
774

    
775
   /**
776
    * Check if the users array has explicit deny rules for given users, docid
777
    * and permission. That means the perm_type is deny and current time is
778
    * less than end_time and greater than begin time, or no time limit.
779
    * @param principals, list of names of principals to check for
780
    * @param docid, document identifier to check for
781
    * @param permission, the permssion need to check
782
    */
783
  private boolean hasExplicitDenyRule(String [] principals, String docId,
784
                                      int permission, long startId)
785
                  throws SQLException
786
 {
787
   int lengthOfArray=principals.length;
788
   ResultSet rs;
789
   PreparedStatement pStmt = null;
790
   int permissionValue=permission;
791
   int permissionValueInTable;
792
   DBConnection conn = null;
793
   int serialNumber = -1;
794
   String sql = null;
795
   boolean topLevel = false;
796

    
797
   // decide top level or subtree level
798
   if (startId == TOPLEVELSTARTNODEID)
799
   {
800
     topLevel = true;
801
     sql = "SELECT permission FROM xml_access WHERE docid = ? " +
802
    "AND lower(principal_name) = ? AND perm_type = ? AND startnodeid is NULL";
803
   }
804
   else
805
   {
806
     topLevel = false;
807
     sql = "SELECT permission FROM xml_access WHERE docid = ? " +
808
     "AND lower(principal_name) = ? AND perm_type = ? AND startnodeid = ?";
809
   }
810

    
811
   try
812
   {
813
     //check out DBConnection
814
     conn=DBConnectionPool.getDBConnection("PermissionControl.hasExplicitDeny");
815
     serialNumber=conn.getCheckOutSerialNumber();
816

    
817
     pStmt = conn.prepareStatement(sql);
818
    //bind docid, perm_type
819
    pStmt.setString(1, docId);
820
    pStmt.setString(3, AccessControlInterface.DENY);
821

    
822
    // subtree level need to set up subtreeid
823
    if (!topLevel)
824
    {
825
      pStmt.setLong(4, startId);
826
    }
827

    
828
    //bind every elenment in user name array
829
    for (int i=0;i<lengthOfArray; i++)
830
    {
831
      pStmt.setString(2, principals[i]);
832
      pStmt.execute();
833
      rs=pStmt.getResultSet();
834
      while (rs.next())//check every entry for one user
835
      {
836
        permissionValueInTable=rs.getInt(1);
837

    
838
        //permission is ok the user doesn't have permission to access the file
839
        if (( permissionValueInTable & permissionValue )== permissionValue )
840

    
841
        {
842
           pStmt.close();
843
           return true;
844
         }//if
845
      }//while
846
    }//for
847
   }//try
848
   catch (SQLException e)
849
   {
850
     throw e;
851
   }//catch
852
   finally
853
   {
854
     try
855
     {
856
       pStmt.close();
857
     }
858
     finally
859
     {
860
       DBConnectionPool.returnDBConnection(conn, serialNumber);
861
     }
862
   }//finally
863
   return false;//no deny rule
864
  }//hasExplicitDenyRule
865

    
866

    
867
  /**
868
    * Creat a users pakages to check permssion rule, user itself, public and
869
    * the gourps the user belong will be include in this package
870
    * @param user, the name of user
871
    * @param groups, the string array of the groups that user belong to
872
    */
873
  private String[] createUsersPackage(String user, String [] groups)
874
  {
875
    String [] usersPackage=null;
876
    int lengthOfPackage;
877

    
878
    if (groups!=null)
879
    {
880
      //if gouprs is not null and user is not public, we should create a array
881
      //to store the groups and user and public.
882
      //So the length of userPackage is the length of group plus two
883
      if (!user.equalsIgnoreCase(AccessControlInterface.PUBLIC))
884
      {
885
        lengthOfPackage=(groups.length)+2;
886
        usersPackage=new String [lengthOfPackage];
887
        //the first two elements is user self and public
888
        //in order to ignore case sensitive, we transfer user to lower case
889
        if (user != null)
890
        {
891
          usersPackage[0]= user.toLowerCase();
892
          logMetacat.info("PermissionController.createUsersPackage - after transfer to lower case(not null): "+
893
                                     usersPackage[0]);
894
        }
895
        else
896
        {
897
          usersPackage[0] = user;
898
          usersPackage[0]= user.toLowerCase();
899
          logMetacat.info("PermissionController.createUsersPackage - after transfer to lower case(null): "+
900
                                     usersPackage[0]);
901
        }
902
        usersPackage[1]=AccessControlInterface.PUBLIC;
903
        //put groups element from index 0 to lengthOfPackage-3 into userPackage
904
        //from index 2 to lengthOfPackage-1
905
        for (int i=2; i<lengthOfPackage; i++)
906
        {
907
          //tansfer group to lower case too
908
          if (groups[i-2] != null)
909
          {
910
            usersPackage[i]=groups[i-2].toLowerCase();
911
          }
912
        } //for
913
      }//if user!=public
914
      else//use=public
915
      {
916
        lengthOfPackage=(groups.length)+1;
917
        usersPackage=new String [lengthOfPackage];
918
        //the first lements is public
919
        usersPackage[0]=AccessControlInterface.PUBLIC;
920
        //put groups element from index 0 to lengthOfPackage-2 into userPackage
921
        //from index 1 to lengthOfPackage-1
922
        for (int i=1; i<lengthOfPackage; i++)
923
        {
924
          if (groups[i-1] != null)
925
          {
926
            usersPackage[i]=groups[i-1].toLowerCase();
927
          }
928
        } //for
929
      }//else user=public
930

    
931
    }//if groups!=null
932
    else
933
    {
934
      //because no groups, the userPackage only need two elements
935
      //one is for user, the other is for public
936
      if (!user.equalsIgnoreCase(AccessControlInterface.PUBLIC))
937
      {
938
        lengthOfPackage=2;
939
        usersPackage=new String [lengthOfPackage];
940
        if (user != null)
941
        {
942
          usersPackage[0]=user.toLowerCase();
943
        }
944
        else
945
        {
946
          usersPackage[0]=user;
947
        }
948
        usersPackage[1]=AccessControlInterface.PUBLIC;
949
      }//if user!=public
950
      else //user==public
951
      {
952
        //only put public into array
953
        lengthOfPackage=1;
954
        usersPackage=new String [lengthOfPackage];
955
        usersPackage[0]=AccessControlInterface.PUBLIC;
956
      }
957
    }//else groups==null
958
    return usersPackage;
959
  }//createUsersPackage
960

    
961

    
962
  /**
963
   * A static method to get Hashtable which cointains a inlinedata object list that
964
   * user can't read it. The key is subtree id of inlinedata, the data is
965
   * internal file name for the inline data which is stored as docid
966
   * in xml_access table or data object doc id.
967
   * @param docidWithoutRev, metadata docid which should be the accessfileid
968
   *                         in the table
969
   * @param user , the name of user
970
   * @param groups, the group which the user belong to
971
   */
972
   public static Hashtable<String, String> getUnReadableInlineDataIdList(String docidWithoutRev,
973
                                                   String user, String[] groups,
974
                                                   boolean withRevision)
975
                                                throws McdbException
976
   {
977
     Hashtable<String, String> inlineDataList = getUnAccessableInlineDataIdList(docidWithoutRev,
978
                              user, groups, AccessControlInterface.READSTRING,
979
                              withRevision);
980

    
981
     return inlineDataList;
982
   }
983

    
984
   /**
985
  * A static method to get Hashtable which cointains a inline  data object list that
986
  * user can't overwrite it. The key is subtree id of inline data distrubition,
987
  * the value is internal file name for the inline data which is stored as docid
988
  * in xml_access table or data object doc id.
989
  * @param docidWithoutRev, metadata docid which should be the accessfileid
990
  *                         in the table
991
  * @param user , the name of user
992
  * @param groups, the group which the user belong to
993
  */
994
  public static Hashtable<String, String> getUnWritableInlineDataIdList(String docidWithoutRev,
995
                                                  String user, String[] groups,
996
                                                  boolean withRevision)
997
                                               throws Exception
998
  {
999
    Hashtable<String, String> inlineDataList = getUnAccessableInlineDataIdList(docidWithoutRev,
1000
                            user, groups, AccessControlInterface.WRITESTRING,
1001
                            withRevision);
1002

    
1003
    return inlineDataList;
1004
  }
1005

    
1006

    
1007
   /*
1008
    * This method will get hashtable which contains a unaccessable distribution
1009
    * inlinedata object list
1010
    *
1011
    * withRevision is used to get inline id list with or without revision number
1012
    * e.g. when withRevision is true, temp.1.1.1, temp.1.1.2 would be returned
1013
    * otherwise temp.1.1 and temp.1.2 would be returned.
1014
    */
1015
   private static Hashtable<String, String> getUnAccessableInlineDataIdList(String docid,
1016
                               String user, String[] groups, String permission,
1017
                               boolean withRevision)
1018
                             throws McdbException
1019
   {
1020
       Hashtable<String, String> unAccessibleIdList = new Hashtable();
1021
       if (user == null) {
1022
           return unAccessibleIdList;
1023
       }
1024

    
1025
       Hashtable allIdList;
1026
       try {
1027
           allIdList = getAllInlineDataIdList(docid);
1028
       } catch (SQLException e) {
1029
           throw new McdbException(e.getMessage());
1030
       }
1031
       Enumeration<String> en = allIdList.keys();
1032
      while (en.hasMoreElements())
1033
      {
1034
        String subTreeId = (String) en.nextElement();
1035
        String fileId = (String) allIdList.get(subTreeId);
1036
        //Here fileid is internal file id for line data. It stored in docid
1037
        // field in xml_access table. so we don't need to delete rev
1038
        PermissionController controller = new PermissionController(docid, false);
1039
        if (!controller.hasPermissionForInlineData(user, groups, permission, fileId))
1040
        {
1041
            if(withRevision)
1042
            {
1043
                logMetacat.info("PermissionController.getUnAccessableInlineDataIdList - Put subtree id " + subTreeId +
1044
                                         " and " + "inline data file name " +
1045
                                         fileId + " into " + "un" + permission +
1046
                                         " hash");
1047
                unAccessibleIdList.put(subTreeId, fileId);
1048

    
1049
            }
1050
            else
1051
            {
1052
                logMetacat.info("PermissionController.getUnAccessableInlineDataIdList - Put subtree id " + subTreeId +
1053
                                         " and " + "inline data file name " +
1054
                                         DocumentUtil.getInlineDataIdWithoutRev(fileId) +
1055
                                         " into " + "un" + permission +
1056
                                         " hash");
1057
                unAccessibleIdList.put(subTreeId, 
1058
                		DocumentUtil.getInlineDataIdWithoutRev(fileId));
1059
            }
1060
        }
1061
      }
1062
      return unAccessibleIdList;
1063
   }
1064

    
1065

    
1066
   /*
1067
    * This method will get a hash table from xml_access table for all records
1068
    * about the inline data. The key is subtree id and data is a inline internal
1069
    * file name
1070
    */
1071
   private static Hashtable getAllInlineDataIdList(String docid) throws SQLException
1072
   {
1073
     Hashtable inlineDataList = new Hashtable();
1074
     String sql = "SELECT subtreeid, docid FROM xml_access WHERE " +
1075
                   "accessfileid = ? AND subtreeid  IS NOT NULL";
1076
     PreparedStatement pStmt=null;
1077
     ResultSet rs=null;
1078
     DBConnection conn=null;
1079
     int serialNumber=-1;
1080
     try
1081
     {
1082
       //check out DBConnection
1083
       conn=DBConnectionPool.getDBConnection("PermissionControl.getDataSetId");
1084
       serialNumber=conn.getCheckOutSerialNumber();
1085
       pStmt=conn.prepareStatement(sql);
1086
       //bind the value to query
1087
       pStmt.setString(1, docid);
1088
       //execute the query
1089
       pStmt.execute();
1090
       rs=pStmt.getResultSet();
1091
       //process the result
1092
       while(rs.next())
1093
       {
1094
         String subTreeId = rs.getString(1);
1095
         String inlineDataId = rs.getString(2);
1096
         if (subTreeId != null && !subTreeId.trim().equals("") &&
1097
            inlineDataId != null && !inlineDataId.trim().equals(""))
1098
         {
1099
           inlineDataList.put(subTreeId, inlineDataId);
1100
         }
1101
      }//while
1102
     }//try
1103
     finally
1104
     {
1105
       try
1106
       {
1107
         pStmt.close();
1108
       }
1109
       finally
1110
       {
1111
         DBConnectionPool.returnDBConnection(conn, serialNumber);
1112
       }
1113
     }//finally
1114
     return inlineDataList;
1115
   }//getAllInlineDataIdList
1116
}
(52-52/65)