Project

General

Profile

1 1425 tao
/**
2
 *  '$RCSfile$'
3
 *    Purpose: A class that handles checking permssision for a document
4 2245 sgarg
               and subtree in a document
5
 *
6 1425 tao
 *  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$'
11
 *     '$Date$'
12
 * '$Revision$'
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 2245 sgarg
30 1425 tao
import java.sql.*;
31 1485 tao
import java.util.Enumeration;
32 1434 tao
import java.util.Hashtable;
33 1425 tao
import java.util.Stack;
34
import java.util.Vector;
35 2245 sgarg
import java.util.Iterator;
36 1425 tao
37 2663 sgarg
import org.apache.log4j.Logger;
38
39 4080 daigle
import edu.ucsb.nceas.metacat.service.PropertyService;
40
import edu.ucsb.nceas.metacat.util.MetaCatUtil;
41
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
42
43 1425 tao
public class PermissionController
44
{
45
   private String docId = null;
46
   private boolean hasSubTreeAccessControl = false; // flag if has a subtree
47
                                                    // access for this docid
48
   private Vector subTreeList = new Vector();
49 2245 sgarg
50 1527 tao
   private long TOPLEVELSTARTNODEID = 0; //if start node is 0, means it is top
51
                                         //level document
52 2245 sgarg
53 2663 sgarg
   private static Logger logMetacat = Logger.getLogger(PermissionController.class);
54 2245 sgarg
55 1425 tao
   /**
56
    * Constructor for PermissionController
57
    * @param myDocid      the docid need to access
58
    */
59 1434 tao
   public PermissionController(String myDocid) throws McdbException
60 1425 tao
   {
61
     // Get rid of rev number
62 2045 tao
     docId = MetaCatUtil.getSmartDocId(myDocid);
63 2245 sgarg
     //hasSubTreeAccessControl = checkSubTreeAccessControl();
64 1425 tao
   }
65 2245 sgarg
66 1485 tao
   /**
67 2245 sgarg
    * Constructor for PermssionController
68
    * @param myDocid String
69
    * @param needDeleteRev boolean
70
    */
71
   public PermissionController(String myDocid, boolean needDeleteRevFromDocid)
72
   {
73
     if (!needDeleteRevFromDocid)
74
     {
75
       docId = myDocid;
76
     }
77
     else
78
     {
79
         docId = MetaCatUtil.getDocIdFromAccessionNumber(myDocid);
80
     }
81
   }
82
83
   /**
84 1485 tao
    * Return if a document has subtree access control
85
    */
86
   public boolean hasSubTreeAccessControl()
87
   {
88
     return hasSubTreeAccessControl;
89
   }
90 2245 sgarg
91
92 1425 tao
  /**
93
    * Check from db connection if at least one of the list of @principals
94
    * @param user  the user name
95
    * @param groups  the groups which the use is in
96
    * @param myPermission  permission type to check for
97
    */
98 2245 sgarg
  public boolean hasPermission(String user, String[]groups, String myPermission)
99 1425 tao
                              throws SQLException, Exception
100
  {
101
    boolean hasPermission=false;
102
    String [] userPackage=null;
103
    int permission =AccessControlList.intValue(myPermission);
104 2245 sgarg
105 1425 tao
    //for the commnad line invocation
106
    if ((user==null) && (groups==null || groups.length==0))
107
    {
108
      return true;
109
    }
110 2245 sgarg
111 1425 tao
    //create a userpackage including user, public and group member
112
    userPackage=createUsersPackage(user, groups);
113 2245 sgarg
114 1425 tao
    //if the requested document is access documents and requested permission
115
    //is "write", the user should have "all" right
116 2245 sgarg
117 1425 tao
    if (isAccessDocument(docId) && (permission == AccessControlInterface.WRITE))
118
    {
119 2245 sgarg
120 1425 tao
      hasPermission = hasPermission(userPackage,docId, 7);// 7 is all permission
121
    }//if
122
    else //in other situation, just check the request permission
123
    {
124 2245 sgarg
125
126 1425 tao
      // Check for @permission on @docid for @user and/or @groups
127
      hasPermission = hasPermission(userPackage,docId, permission);
128 2245 sgarg
129 1425 tao
    }//else
130 2245 sgarg
131 1425 tao
    return hasPermission;
132
  }
133 2245 sgarg
134
135 1425 tao
  /**
136
    * Check from db connection if the users in String array @principals has
137 2245 sgarg
    * @permission on @docid*
138 1425 tao
    * @param principals, names in userPakcage need to check for @permission
139
    * @param docid, document identifier to check on
140 2245 sgarg
    * @param permission, permission (write or all...) to check for
141 1425 tao
    */
142
  private boolean hasPermission(String [] principals, String docId,
143
                                           int permission)
144
                         throws SQLException
145
  {
146 1527 tao
    long startId = TOPLEVELSTARTNODEID;// this is for top level, so startid is 0
147 2245 sgarg
    try
148 1425 tao
    {
149
      //first, if there is a docid owner in user package, return true
150 2245 sgarg
      //because doc owner has all permssion
151 1425 tao
      if (containDocumentOwner(principals, docId))
152
      {
153 2245 sgarg
154 1425 tao
          return true;
155
      }
156 2245 sgarg
157 1425 tao
      //If there is no owner in user package, checking the table
158
      //check perm_order
159 1527 tao
      if (isAllowFirst(principals, docId, startId))
160 1425 tao
      {
161 2245 sgarg
162 1527 tao
        if (hasExplicitDenyRule(principals, docId, permission, startId))
163 1425 tao
        {
164
          //if it is allowfirst and has deny rule(either explicit )
165
          //deny access
166 2245 sgarg
167 1425 tao
          return false;
168
        }//if
169 1527 tao
        else if ( hasAllowRule(principals, docId, permission, startId))
170 1425 tao
        {
171
          //if it is allowfirst and hasn't deny rule and has allow rule
172
          //allow access
173 2245 sgarg
174 1425 tao
          return true;
175
        }//else if
176
        else
177
        {
178
          //other situation deny access
179 2245 sgarg
180 1425 tao
          return false;
181
        }//else
182
     }//if isAllowFirst
183
     else //denyFirst
184
     {
185 1527 tao
       if (hasAllowRule(principals, docId, permission, startId))
186 1425 tao
       {
187
         //if it is denyFirst and has allow rule, allow access
188
         return true;
189
       }
190
       else
191
       {
192
         //if it is denyfirst but no allow rule, deny access
193
         return false;
194
       }
195
     }//else denyfirst
196
    }//try
197
    catch (Exception e)
198
    {
199 2663 sgarg
      logMetacat.warn("There is a exception in hasPermission method: "
200
                         +e.getMessage());
201 1425 tao
    }
202 2245 sgarg
203 1425 tao
    return false;
204
  }//hasPermission
205 2245 sgarg
206 1425 tao
  /**
207 2245 sgarg
   *  Method to check if a person has permission to a inline data file
208
   * @param user String
209
   * @param groups String[]
210
   * @param myPermission String
211
   * @param inlineDataId String
212
   * @throws McdbException
213
   * @return boolean
214
   */
215
  private boolean hasPermissionForInlineData(String user, String[] groups,
216
                                      String myPermission, String inlineDataId)
217
                                      throws Exception
218
  {
219
     // this method can call the public method - hasPermission(...)
220
     // the only difference is about the ownership, you couldn't find the owner
221
     // from inlinedataId directly. You should get it from eml document itself
222
     String []userPackage = createUsersPackage(user, groups);
223
     if (containDocumentOwner(userPackage, docId))
224
     {
225
       return true;
226
     }
227
     else
228
     {
229
         PermissionController controller =
230
                               new PermissionController(inlineDataId, false);
231
         return controller.hasPermission(user, groups, myPermission);
232
     }
233
  }
234
235
  /**
236 1485 tao
   * The method to determine of a node can be access by a user just by subtree
237
   * access control
238
   */
239
  public boolean hasPermissionForSubTreeNode(String user, String[] groups,
240
                                             String myPermission, long nodeId)
241
                                             throws McdbException
242
  {
243 1492 tao
    boolean flag = true;
244 1485 tao
    // Get unaccessble subtree for this user
245 2245 sgarg
    Hashtable unaccessableSubTree = hasUnaccessableSubTree(user, groups,
246 1485 tao
                                                           myPermission);
247
    Enumeration en = unaccessableSubTree.elements();
248
    while (en.hasMoreElements())
249
    {
250
      SubTree tree = (SubTree)en.nextElement();
251
      long start = tree.getStartNodeId();
252
      long stop  = tree.getEndNodeId();
253 1492 tao
      // nodeid in unaccessablesubtree, return false
254 1485 tao
      if ( nodeId >= start && nodeId <= stop)
255
      {
256 1492 tao
        flag = false;
257 1485 tao
        break;
258
      }
259
    }
260
    return flag;
261
  }
262
  /**
263 2245 sgarg
   * This method will return a hasTable of subtree which user doesn't has the
264 1434 tao
   * permssion to access
265
   * @param user  the user name
266
   * @param groups  the groups which the use is in
267
   * @param myPermission  permission type to check for
268
   */
269 2245 sgarg
  public Hashtable hasUnaccessableSubTree(String user, String[] groups,
270 1434 tao
                                       String myPermission) throws McdbException
271
  {
272
    Hashtable resultUnaccessableSubTree = new Hashtable();
273
    String [] principals=null;
274
    int permission =AccessControlList.intValue(myPermission);
275 2245 sgarg
276 1434 tao
    //for the commnad line invocation return null(no unaccessable subtree)
277
    if ((user==null) && (groups==null || groups.length==0))
278
    {
279
      return resultUnaccessableSubTree;
280
    }
281 2245 sgarg
282 1434 tao
    //create a userpackage including user, public and group member
283
    principals=createUsersPackage(user, groups);
284
    //for the document owner return null(no unaccessable subtree)
285
    try
286
    {
287
      if (containDocumentOwner(principals, docId))
288
      {
289
       return resultUnaccessableSubTree;
290
      }
291
    }
292
    catch (SQLException ee)
293
    {
294
      throw new McdbException(ee);
295
    }
296 2245 sgarg
297 1434 tao
    // go through every subtree which has access control
298
    for (int i = 0; i< subTreeList.size(); i++)
299
    {
300
      SubTree tree = (SubTree)subTreeList.elementAt(i);
301 1527 tao
      long startId = tree.getStartNodeId();
302 2245 sgarg
303
304 1434 tao
        try
305
        {
306 1527 tao
          if (isAllowFirst(principals, docId, startId))
307 1434 tao
          {
308 2245 sgarg
309 1527 tao
            if (hasExplicitDenyRule(principals, docId, permission, startId ))
310 1434 tao
            {
311 2245 sgarg
312 1434 tao
             //if it is allowfirst and has deny rule
313
              // put the subtree into unaccessable vector
314 1527 tao
              if (!resultUnaccessableSubTree.containsKey(new Long(startId)))
315 1434 tao
              {
316 1527 tao
                resultUnaccessableSubTree.put(new Long(startId), tree);
317 1434 tao
              }
318
            }//if
319 1527 tao
            else if ( hasAllowRule(principals, docId, permission, startId))
320 1434 tao
            {
321
              //if it is allowfirst and hasn't deny rule and has allow rule
322
              //allow access do nothing
323 2245 sgarg
324 1434 tao
            }//else if
325
            else
326
            {
327
              //other situation deny access
328 1527 tao
              if (!resultUnaccessableSubTree.containsKey(new Long(startId)))
329 1434 tao
              {
330 1527 tao
                resultUnaccessableSubTree.put(new Long(startId), tree);
331 1434 tao
              }
332 2245 sgarg
333 1434 tao
            }//else
334
          }//if isAllowFirst
335
          else //denyFirst
336
          {
337 1527 tao
            if (hasAllowRule(principals, docId, permission,startId))
338 1434 tao
            {
339
              //if it is denyFirst and has allow rule, allow access, do nothing
340 2245 sgarg
341 1434 tao
            }
342
            else
343
            {
344
              //if it is denyfirst but no allow rule, deny access
345
              // add into vector
346 1527 tao
              if (!resultUnaccessableSubTree.containsKey(new Long(startId)))
347 1434 tao
              {
348 1527 tao
                resultUnaccessableSubTree.put(new Long(startId), tree);
349 1434 tao
              }
350
            }
351
          }//else denyfirst
352
        }//try
353
        catch( Exception e)
354
        {
355 2663 sgarg
          logMetacat.error("error in PermissionControl.has" +
356
                                   "UnaccessableSubTree "+e.getMessage());
357 1434 tao
          throw new McdbException(e);
358
        }
359 2245 sgarg
360 1434 tao
    }//for
361 2245 sgarg
    // merge the subtree if a subtree is another subtree'subtree
362 1521 tao
    resultUnaccessableSubTree = mergeEquivalentSubtree(resultUnaccessableSubTree);
363 1434 tao
    return resultUnaccessableSubTree;
364
  }//hasUnaccessableSubtree
365 2245 sgarg
366
367
  /*
368 1513 tao
   * A method to merge nested subtree into bigger one. For example subtree b
369
   * is a subtree of subtree a. And user doesn't have read permission for both
370
   * so we only use subtree a is enough.
371
   */
372 1521 tao
  private Hashtable mergeEquivalentSubtree(Hashtable unAccessSubTree)
373 1513 tao
  {
374
    Hashtable newSubTreeHash = new Hashtable();
375
    boolean   needDelete = false;
376
    // check the parameters
377
    if (unAccessSubTree == null || unAccessSubTree.isEmpty())
378
    {
379
      return newSubTreeHash;
380
    }
381
    else
382
    {
383
      // look every subtree start point and stop point, to see if it is embedded
384
      // in another one. If embedded, they are equavelent and we can use bigger
385
      // one to replace smaller one
386
      Enumeration en = unAccessSubTree.elements();
387
      while (en.hasMoreElements())
388
      {
389
        SubTree tree    = (SubTree)en.nextElement();
390
        String  treeId  = tree.getSubTreeId();
391
        long    startId = tree.getStartNodeId();
392
        long    endId   = tree.getEndNodeId();
393 2245 sgarg
394 1513 tao
        Enumeration enu = unAccessSubTree.elements();
395
        while (enu.hasMoreElements())
396
        {
397
          SubTree subTree = (SubTree)enu.nextElement();
398
          String subTreeId= subTree.getSubTreeId();
399
          long   subTreeStartId = subTree.getStartNodeId();
400
          long   subTreeEndId   = subTree.getEndNodeId();
401
          //compare and if the first subtree is a subtree of the second
402
          // one, set neeDelete true
403
          if (startId > subTreeStartId && endId < subTreeEndId)
404
          {
405
            needDelete = true;
406 2663 sgarg
            logMetacat.info("the subtree: "+ treeId +
407 1513 tao
                                     " need to be get rid of from unaccessable"+
408
                                     " subtree list becuase it is a subtree of"+
409 2663 sgarg
                                     " another subtree in the list");
410 1513 tao
            break;
411
          }//if
412
        }//while
413
        // if not need to delete, put the subtree into hash
414
        if (!needDelete)
415
        {
416 1527 tao
          newSubTreeHash.put(new Long(startId), tree);
417 1513 tao
        }
418
        //reset needDelete
419
        needDelete = false;
420
      }//while
421
      return newSubTreeHash;
422
    }//else
423
  }
424 2245 sgarg
425 1434 tao
  /**
426 4080 daigle
	 * Check if a document id is a access document. Access document need user
427
	 * has "all" permission to access it.
428
	 *
429
	 * @param docId,
430
	 *            the document id need to be checked
431
	 */
432
	private boolean isAccessDocument(String docId) throws SQLException {
433
		// detele the rev number if docid contains it
434
		docId = MetaCatUtil.getDocIdFromString(docId);
435
		PreparedStatement pStmt = null;
436
		DBConnection conn = null;
437
		int serialNumber = -1;
438
		try {
439
			// check out DBConnection
440
			conn = DBConnectionPool.getDBConnection("PermissionControl.isAccessDoc");
441
			serialNumber = conn.getCheckOutSerialNumber();
442
			pStmt = conn.prepareStatement("select doctype from xml_documents where "
443
					+ "docid like '" + docId + "'");
444
			pStmt.execute();
445
			ResultSet rs = pStmt.getResultSet();
446
			boolean hasRow = rs.next();
447
			String doctype = null;
448
			if (hasRow) {
449
				doctype = rs.getString(1);
450 2245 sgarg
451 4080 daigle
			}
452
			pStmt.close();
453 2245 sgarg
454 4080 daigle
			// if it is an access document
455
			if (doctype != null
456
					&& ((MetaCatUtil.getOptionList(PropertyService
457 4213 daigle
							.getProperty("xml.accessdoctype")).contains(doctype)))) {
458 2245 sgarg
459 4080 daigle
				return true;
460
			}
461 2245 sgarg
462 4080 daigle
		} catch (SQLException e) {
463
			throw new SQLException("PermissionControl.isAccessDocument "
464
					+ "Error checking" + " on document " + docId + ". " + e.getMessage());
465
		} catch (PropertyNotFoundException pnfe) {
466
			throw new SQLException("PermissionControl.isAccessDocument "
467
					+ "Error checking" + " on document " + docId + ". " + pnfe.getMessage());
468
		} finally {
469
			try {
470
				pStmt.close();
471
			} finally {
472
				DBConnectionPool.returnDBConnection(conn, serialNumber);
473
			}
474
		}
475 2245 sgarg
476 4080 daigle
		return false;
477
	}// isAccessDocument
478 2245 sgarg
479
480
481 1425 tao
  /**
482 4080 daigle
	 * Check if a stirng array contains a given documents' owner
483
	 *
484
	 * @param principals,
485
	 *            a string array storing the username, groups name and public.
486
	 * @param docid,
487
	 *            the id of given documents
488
	 */
489 1434 tao
  private boolean containDocumentOwner( String[] principals, String docId)
490 1425 tao
                    throws SQLException
491
  {
492
    int lengthOfArray=principals.length;
493 2245 sgarg
    boolean hasRow;
494 1425 tao
    PreparedStatement pStmt=null;
495
    DBConnection conn = null;
496
    int serialNumber = -1;
497 2245 sgarg
498 1425 tao
    try
499
    {
500
      //check out DBConnection
501 1434 tao
     conn=DBConnectionPool.getDBConnection("PermissionControl.containDocOnwer");
502 1425 tao
      serialNumber=conn.getCheckOutSerialNumber();
503
      pStmt = conn.prepareStatement(
504
                "SELECT 'x' FROM xml_documents " +
505 2245 sgarg
                "WHERE docid = ? AND lower(user_owner) = ?");
506 1425 tao
      //check every element in the string array too see if it conatains
507
      //the owner of document
508
      for (int i=0; i<lengthOfArray; i++)
509
      {
510 2245 sgarg
511 1425 tao
        // Bind the values to the query
512
        pStmt.setString(1, docId);
513
        pStmt.setString(2, principals[i]);
514 2663 sgarg
        logMetacat.info("the principle stack is : " +
515
                                  principals[i]);
516 1425 tao
517
        pStmt.execute();
518
        ResultSet rs = pStmt.getResultSet();
519
        hasRow = rs.next();
520 2245 sgarg
        if (hasRow)
521 1425 tao
        {
522
          pStmt.close();
523 2663 sgarg
           logMetacat.info("find the owner");
524 1425 tao
          return true;
525 2245 sgarg
        }//if
526
527 1425 tao
      }//for
528
    }//try
529 2245 sgarg
    catch (SQLException e)
530 1425 tao
    {
531
        pStmt.close();
532 2245 sgarg
533
        throw new
534 1434 tao
        SQLException("PermissionControl.hasPermission(). " +
535 1425 tao
                     "Error checking ownership for " + principals[0] +
536
                     " on document #" + docId + ". " + e.getMessage());
537
    }//catch
538
    finally
539
    {
540
      try
541
      {
542
        pStmt.close();
543
      }
544
      finally
545
      {
546
        DBConnectionPool.returnDBConnection(conn, serialNumber);
547
      }
548
    }
549 2245 sgarg
    return false;
550 1425 tao
  }//containDocumentOwner
551 2245 sgarg
552 1425 tao
  /**
553
    * Check if the permission order for user at that documents is allowFirst
554 2245 sgarg
    * @param principals, list of names of principals to check for
555 1425 tao
    * @param docid, document identifier to check for
556
    */
557 2245 sgarg
  private boolean isAllowFirst(String [] principals, String docId,
558 1527 tao
                               long startId)
559 1425 tao
                  throws SQLException, Exception
560
  {
561
    int lengthOfArray=principals.length;
562
    boolean hasRow;
563
    PreparedStatement pStmt = null;
564
    DBConnection conn = null;
565
    int serialNumber = -1;
566 1434 tao
    String sql = null;
567
    boolean topLever =false;
568 1527 tao
    if (startId == TOPLEVELSTARTNODEID)
569 1434 tao
    {
570
      //top level
571
      topLever = true;
572
      sql = "SELECT perm_order FROM xml_access " +
573 2045 tao
    "WHERE lower(principal_name) = ? AND docid = ? AND startnodeid is NULL";
574 1434 tao
    }
575
    else
576
    {
577
      //sub tree level
578
      sql = "SELECT perm_order FROM xml_access " +
579 2045 tao
        "WHERE lower(principal_name)= ? AND docid = ? AND startnodeid = ?";
580 1434 tao
    }
581 2245 sgarg
582 1425 tao
    try
583
    {
584
      //check out DBConnection
585
      conn=DBConnectionPool.getDBConnection("AccessControlList.isAllowFirst");
586
      serialNumber=conn.getCheckOutSerialNumber();
587 2245 sgarg
588 1425 tao
      //select permission order from database
589 1434 tao
      pStmt = conn.prepareStatement(sql);
590 2245 sgarg
591 1425 tao
      //check every name in the array
592
      for (int i=0; i<lengthOfArray;i++)
593
      {
594
        //bind value
595
        pStmt.setString(1, principals[i]);//user name
596
        pStmt.setString(2, docId);//docid
597 2245 sgarg
598
        // if subtree, we need set subtree id
599 1434 tao
        if (!topLever)
600
        {
601 1527 tao
          pStmt.setLong(3, startId);
602 1434 tao
        }
603 2245 sgarg
604 1425 tao
        pStmt.execute();
605
        ResultSet rs = pStmt.getResultSet();
606
        hasRow=rs.next();
607
        if (hasRow)
608
        {
609
          //get the permission order from data base
610
          String permissionOrder=rs.getString(1);
611
          //if the permission order is "allowFirst
612
          if (permissionOrder.equalsIgnoreCase(AccessControlInterface.ALLOWFIRST))
613
          {
614
            pStmt.close();
615
            return true;
616
          }
617
          else
618
          {
619
            pStmt.close();
620
            return false;
621
          }
622
        }//if
623
      }//for
624
    }//try
625
    catch (SQLException e)
626
    {
627
      throw e;
628
    }
629
    finally
630
    {
631
      try
632
      {
633
        pStmt.close();
634
      }
635
      finally
636
      {
637
        DBConnectionPool.returnDBConnection(conn, serialNumber);
638
      }
639
    }
640 2245 sgarg
641
    //if reach here, means there is no permssion record for given names and
642 1425 tao
    //docid. So throw a exception.
643 2245 sgarg
644 4080 daigle
    throw new Exception("There is no permission record for user"+principals[0]+
645
                        "at document "+docId);
646 2245 sgarg
647 1425 tao
  }//isAllowFirst
648 2245 sgarg
649 4419 leinfelder
/**
650
    * Check if the permission order for user at that documents is allowFirst
651
    * @param principals, list of names of principals to check for
652
    * @param docid, document identifier to check for
653
    */
654
  public Vector getAccessControl()
655
                  throws SQLException, Exception
656
  {
657
	  Vector accessControl = new Vector();
658
    boolean hasRow;
659
    PreparedStatement pStmt = null;
660
    DBConnection conn = null;
661
    int serialNumber = -1;
662
    String sql = null;
663
    boolean topLever =false;
664
    sql = "SELECT principal_name, permission, perm_type, perm_order FROM xml_access ";
665
666
    //TODO, need this?
667
    long startId = 0;
668
    if (startId == TOPLEVELSTARTNODEID)
669
    {
670
      //top level
671
      topLever = true;
672
      sql += "WHERE docid = ? AND startnodeid is NULL";
673
    }
674
    else
675
    {
676
      //sub tree level
677
      sql += "WHERE docid = ? AND startnodeid = ?";
678
    }
679
680
    try
681
    {
682
      //check out DBConnection
683
      conn=DBConnectionPool.getDBConnection("AccessControlList.getPermissions");
684
      serialNumber=conn.getCheckOutSerialNumber();
685
686
      //select permission order from database
687
      pStmt = conn.prepareStatement(sql);
688
689
        //bind value
690
        pStmt.setString(1, docId);//docid
691
692
        // if subtree, we need set subtree id
693
        if (!topLever)
694
        {
695
          pStmt.setLong(2, startId);
696
        }
697
698
        pStmt.execute();
699
        ResultSet rs = pStmt.getResultSet();
700
        while (rs.next())
701
        {
702
          //get the permission order from data base
703
          String principalName=rs.getString(1);
704
          String permission=rs.getString(2);
705
          String permType=rs.getString(3);
706
          String permOrder=rs.getString(4);
707
708
          //make it into an object
709
          AccessControlForSingleFile acfsf =
710
        	  new AccessControlForSingleFile(docId, principalName, permission, permType, permOrder);
711
          accessControl.add(acfsf);
712
        }
713
        pStmt.close();
714
    }//try
715
    catch (SQLException e)
716
    {
717
      throw e;
718
    }
719
    finally
720
    {
721
      try
722
      {
723
        pStmt.close();
724
      }
725
      finally
726
      {
727
        DBConnectionPool.returnDBConnection(conn, serialNumber);
728
      }
729
    }
730
731
    return accessControl;
732
733
  }//getPermissions
734
735 1425 tao
  /**
736 2245 sgarg
    * Check if the users array has allow rules for given users, docid and
737 1425 tao
    * permission.
738
    * If it has permission rule and ticket count is greater than 0, the ticket
739
    * number will decrease one for every allow rule
740 2245 sgarg
    * @param principals, list of names of principals to check for
741 1425 tao
    * @param docid, document identifier to check for
742
    * @param permission, the permssion need to check
743
    */
744 2245 sgarg
  private boolean hasAllowRule(String [] principals, String docId,
745 1527 tao
                                  int permission, long startId)
746 1425 tao
                  throws SQLException, Exception
747
 {
748
   int lengthOfArray=principals.length;
749
   boolean allow=false;//initial value is no allow rule
750
   ResultSet rs;
751
   PreparedStatement pStmt = null;
752
   int permissionValue=permission;
753
   int permissionValueInTable;
754
   int ticketCount;
755
   DBConnection conn = null;
756
   int serialNumber = -1;
757 1434 tao
   boolean topLever = false;
758
   String sql = null;
759 1527 tao
   if (startId == TOPLEVELSTARTNODEID)
760 1434 tao
   {
761
     // for toplevel
762
     topLever = true;
763 2245 sgarg
     sql = "SELECT permission FROM xml_access WHERE docid = ? " +
764 2045 tao
   "AND lower(principal_name) = ? AND perm_type = ? AND startnodeid is NULL";
765 1434 tao
   }
766
   else
767
   {
768
     topLever =false;
769 2245 sgarg
     sql = "SELECT permission FROM xml_access WHERE docid = ? " +
770 2045 tao
      "AND lower(principal_name) = ? AND perm_type = ? AND startnodeid = ?";
771 1434 tao
   }
772 1425 tao
   try
773
   {
774
     //check out DBConnection
775
     conn=DBConnectionPool.getDBConnection("AccessControlList.hasAllowRule");
776
     serialNumber=conn.getCheckOutSerialNumber();
777 2245 sgarg
    //This sql statement will select entry with
778 1425 tao
    //begin_time<=currentTime<=end_time in xml_access table
779
    //If begin_time or end_time is null in table, isnull(begin_time, sysdate)
780
    //function will assign begin_time=sysdate
781 1434 tao
    pStmt = conn.prepareStatement(sql);
782 1425 tao
    //bind docid, perm_type
783
    pStmt.setString(1, docId);
784
    pStmt.setString(3, AccessControlInterface.ALLOW);
785 2245 sgarg
786 1434 tao
    // if subtree lever, need to set subTreeId
787
    if (!topLever)
788
    {
789 1527 tao
      pStmt.setLong(4, startId);
790 1434 tao
    }
791 2245 sgarg
792 1425 tao
    //bind every elenment in user name array
793
    for (int i=0;i<lengthOfArray; i++)
794
    {
795
      pStmt.setString(2, principals[i]);
796
      pStmt.execute();
797
      rs=pStmt.getResultSet();
798
      while (rs.next())//check every entry for one user
799
      {
800
        permissionValueInTable=rs.getInt(1);
801 2245 sgarg
802
        //permission is ok
803 1425 tao
        //the user have a permission to access the file
804
        if (( permissionValueInTable & permissionValue )== permissionValue )
805
        {
806 2245 sgarg
807 1425 tao
           allow=true;//has allow rule entry
808
        }//if
809
      }//while
810
    }//for
811
   }//try
812
   catch (SQLException sqlE)
813
   {
814
     throw sqlE;
815
   }
816
   catch (Exception e)
817
   {
818
     throw e;
819
   }
820
   finally
821
   {
822
     try
823
     {
824
       pStmt.close();
825
     }
826
     finally
827
     {
828
       DBConnectionPool.returnDBConnection(conn, serialNumber);
829
     }
830
   }
831
    return allow;
832
 }//hasAllowRule
833 2245 sgarg
834
835
836 1425 tao
   /**
837 2245 sgarg
    * Check if the users array has explicit deny rules for given users, docid
838 1425 tao
    * and permission. That means the perm_type is deny and current time is
839
    * less than end_time and greater than begin time, or no time limit.
840 2245 sgarg
    * @param principals, list of names of principals to check for
841 1425 tao
    * @param docid, document identifier to check for
842
    * @param permission, the permssion need to check
843
    */
844 2245 sgarg
  private boolean hasExplicitDenyRule(String [] principals, String docId,
845 1527 tao
                                      int permission, long startId)
846 1425 tao
                  throws SQLException
847
 {
848
   int lengthOfArray=principals.length;
849
   ResultSet rs;
850
   PreparedStatement pStmt = null;
851
   int permissionValue=permission;
852
   int permissionValueInTable;
853
   DBConnection conn = null;
854
   int serialNumber = -1;
855 1434 tao
   String sql = null;
856
   boolean topLevel = false;
857 2245 sgarg
858 1434 tao
   // decide top level or subtree level
859 1527 tao
   if (startId == TOPLEVELSTARTNODEID)
860 1434 tao
   {
861
     topLevel = true;
862 2245 sgarg
     sql = "SELECT permission FROM xml_access WHERE docid = ? " +
863 2045 tao
    "AND lower(principal_name) = ? AND perm_type = ? AND startnodeid is NULL";
864 1434 tao
   }
865
   else
866
   {
867
     topLevel = false;
868 2245 sgarg
     sql = "SELECT permission FROM xml_access WHERE docid = ? " +
869 2045 tao
     "AND lower(principal_name) = ? AND perm_type = ? AND startnodeid = ?";
870 1434 tao
   }
871 2245 sgarg
872 1425 tao
   try
873
   {
874
     //check out DBConnection
875 1434 tao
     conn=DBConnectionPool.getDBConnection("PermissionControl.hasExplicitDeny");
876 1425 tao
     serialNumber=conn.getCheckOutSerialNumber();
877 2245 sgarg
878 1434 tao
     pStmt = conn.prepareStatement(sql);
879 1425 tao
    //bind docid, perm_type
880
    pStmt.setString(1, docId);
881
    pStmt.setString(3, AccessControlInterface.DENY);
882 2245 sgarg
883 1434 tao
    // subtree level need to set up subtreeid
884
    if (!topLevel)
885
    {
886 1527 tao
      pStmt.setLong(4, startId);
887 1434 tao
    }
888 2245 sgarg
889 1425 tao
    //bind every elenment in user name array
890
    for (int i=0;i<lengthOfArray; i++)
891
    {
892
      pStmt.setString(2, principals[i]);
893
      pStmt.execute();
894
      rs=pStmt.getResultSet();
895
      while (rs.next())//check every entry for one user
896
      {
897
        permissionValueInTable=rs.getInt(1);
898 2245 sgarg
899 1425 tao
        //permission is ok the user doesn't have permission to access the file
900
        if (( permissionValueInTable & permissionValue )== permissionValue )
901 2245 sgarg
902 1425 tao
        {
903
           pStmt.close();
904
           return true;
905
         }//if
906
      }//while
907
    }//for
908
   }//try
909
   catch (SQLException e)
910
   {
911
     throw e;
912
   }//catch
913
   finally
914
   {
915
     try
916
     {
917
       pStmt.close();
918
     }
919
     finally
920
     {
921
       DBConnectionPool.returnDBConnection(conn, serialNumber);
922
     }
923
   }//finally
924
   return false;//no deny rule
925 2245 sgarg
  }//hasExplicitDenyRule
926 1425 tao
927 2245 sgarg
928 1425 tao
  /**
929
    * Creat a users pakages to check permssion rule, user itself, public and
930
    * the gourps the user belong will be include in this package
931
    * @param user, the name of user
932
    * @param groups, the string array of the groups that user belong to
933
    */
934
  private String[] createUsersPackage(String user, String [] groups)
935
  {
936
    String [] usersPackage=null;
937
    int lengthOfPackage;
938 2245 sgarg
939 1425 tao
    if (groups!=null)
940
    {
941 2245 sgarg
      //if gouprs is not null and user is not public, we should create a array
942
      //to store the groups and user and public.
943 1425 tao
      //So the length of userPackage is the length of group plus two
944
      if (!user.equalsIgnoreCase(AccessControlInterface.PUBLIC))
945
      {
946
        lengthOfPackage=(groups.length)+2;
947
        usersPackage=new String [lengthOfPackage];
948
        //the first two elements is user self and public
949 2045 tao
        //in order to ignore case sensitive, we transfer user to lower case
950
        if (user != null)
951
        {
952
          usersPackage[0]= user.toLowerCase();
953 2663 sgarg
          logMetacat.info("after transfer to lower case(not null): "+
954
                                     usersPackage[0]);
955 2045 tao
        }
956
        else
957
        {
958
          usersPackage[0] = user;
959
          usersPackage[0]= user.toLowerCase();
960 2663 sgarg
          logMetacat.info("after transfer to lower case(null): "+
961
                                     usersPackage[0]);
962 2045 tao
        }
963 1425 tao
        usersPackage[1]=AccessControlInterface.PUBLIC;
964
        //put groups element from index 0 to lengthOfPackage-3 into userPackage
965
        //from index 2 to lengthOfPackage-1
966
        for (int i=2; i<lengthOfPackage; i++)
967
        {
968 2045 tao
          //tansfer group to lower case too
969
          if (groups[i-2] != null)
970
          {
971
            usersPackage[i]=groups[i-2].toLowerCase();
972
          }
973 1425 tao
        } //for
974
      }//if user!=public
975
      else//use=public
976
      {
977
        lengthOfPackage=(groups.length)+1;
978
        usersPackage=new String [lengthOfPackage];
979
        //the first lements is public
980
        usersPackage[0]=AccessControlInterface.PUBLIC;
981
        //put groups element from index 0 to lengthOfPackage-2 into userPackage
982
        //from index 1 to lengthOfPackage-1
983
        for (int i=1; i<lengthOfPackage; i++)
984
        {
985 2045 tao
          if (groups[i-1] != null)
986
          {
987
            usersPackage[i]=groups[i-1].toLowerCase();
988
          }
989 1425 tao
        } //for
990
      }//else user=public
991 2245 sgarg
992 1425 tao
    }//if groups!=null
993
    else
994
    {
995
      //because no groups, the userPackage only need two elements
996
      //one is for user, the other is for public
997
      if (!user.equalsIgnoreCase(AccessControlInterface.PUBLIC))
998
      {
999
        lengthOfPackage=2;
1000
        usersPackage=new String [lengthOfPackage];
1001 2045 tao
        if (user != null)
1002
        {
1003
          usersPackage[0]=user.toLowerCase();
1004
        }
1005
        else
1006
        {
1007
          usersPackage[0]=user;
1008
        }
1009 1425 tao
        usersPackage[1]=AccessControlInterface.PUBLIC;
1010
      }//if user!=public
1011
      else //user==public
1012
      {
1013
        //only put public into array
1014
        lengthOfPackage=1;
1015
        usersPackage=new String [lengthOfPackage];
1016
        usersPackage[0]=AccessControlInterface.PUBLIC;
1017
      }
1018
    }//else groups==null
1019
    return usersPackage;
1020
  }//createUsersPackage
1021 2245 sgarg
1022
1023 1425 tao
  /**
1024 2245 sgarg
   * A static method to get Hashtable which cointains a inlinedata object list that
1025
   * user can't read it. The key is subtree id of inlinedata, the data is
1026
   * internal file name for the inline data which is stored as docid
1027
   * in xml_access table or data object doc id.
1028
   * @param docidWithoutRev, metadata docid which should be the accessfileid
1029
   *                         in the table
1030
   * @param user , the name of user
1031
   * @param groups, the group which the user belong to
1032 1425 tao
   */
1033 2245 sgarg
   public static Hashtable getUnReadableInlineDataIdList(String docidWithoutRev,
1034 2291 sgarg
                                                   String user, String[] groups,
1035
                                                   boolean withRevision)
1036 2245 sgarg
                                                throws Exception
1037
   {
1038
     Hashtable inlineDataList = getUnAccessableInlineDataIdList(docidWithoutRev,
1039 2291 sgarg
                              user, groups, AccessControlInterface.READSTRING,
1040
                              withRevision);
1041 2245 sgarg
1042
     return inlineDataList;
1043
   }
1044
1045
   /**
1046
  * A static method to get Hashtable which cointains a inline  data object list that
1047
  * user can't overwrite it. The key is subtree id of inline data distrubition,
1048
  * the value is internal file name for the inline data which is stored as docid
1049
  * in xml_access table or data object doc id.
1050
  * @param docidWithoutRev, metadata docid which should be the accessfileid
1051
  *                         in the table
1052
  * @param user , the name of user
1053
  * @param groups, the group which the user belong to
1054
  */
1055
  public static Hashtable getUnWritableInlineDataIdList(String docidWithoutRev,
1056 2291 sgarg
                                                  String user, String[] groups,
1057
                                                  boolean withRevision)
1058 2245 sgarg
                                               throws Exception
1059 1425 tao
  {
1060 2245 sgarg
    Hashtable inlineDataList = getUnAccessableInlineDataIdList(docidWithoutRev,
1061 2291 sgarg
                            user, groups, AccessControlInterface.WRITESTRING,
1062
                            withRevision);
1063 2245 sgarg
1064
    return inlineDataList;
1065
  }
1066
1067
1068
   /*
1069
    * This method will get hashtable which contains a unaccessable distribution
1070
    * inlinedata object list
1071 2291 sgarg
    *
1072
    * withRevision is used to get inline id list with or without revision number
1073
    * e.g. when withRevision is true, temp.1.1.1, temp.1.1.2 would be returned
1074
    * otherwise temp.1.1 and temp.1.2 would be returned.
1075 2245 sgarg
    */
1076
   private static Hashtable getUnAccessableInlineDataIdList(String docid,
1077 2291 sgarg
                               String user, String[] groups, String permission,
1078
                               boolean withRevision)
1079 2245 sgarg
                             throws SQLException,McdbException, Exception
1080
   {
1081
      Hashtable unAccessbleIdList = new Hashtable();
1082
      Hashtable allIdList = getAllInlineDataIdList(docid);
1083
      Enumeration en = allIdList.keys();
1084
      while (en.hasMoreElements())
1085 1425 tao
      {
1086 2245 sgarg
        String subTreeId = (String) en.nextElement();
1087
        String fileId = (String) allIdList.get(subTreeId);
1088
        //Here fileid is internal file id for line data. It stored in docid
1089
        // field in xml_access table. so we don't need to delete rev
1090
        PermissionController controller = new PermissionController(docid, false);
1091
        if (!controller.hasPermissionForInlineData(user, groups, permission, fileId))
1092
        {
1093 2291 sgarg
            if(withRevision)
1094
            {
1095 2663 sgarg
                logMetacat.info("Put subtree id " + subTreeId +
1096 2291 sgarg
                                         " and " + "inline data file name " +
1097
                                         fileId + " into " + "un" + permission +
1098 2663 sgarg
                                         " hash");
1099 2291 sgarg
                unAccessbleIdList.put(subTreeId, fileId);
1100
1101
            }
1102
            else
1103
            {
1104 2663 sgarg
                logMetacat.info("Put subtree id " + subTreeId +
1105 2291 sgarg
                                         " and " + "inline data file name " +
1106
                                         MetaCatUtil.
1107
                                         getInlineDataIdWithoutRev(fileId) +
1108
                                         " into " + "un" + permission +
1109 2663 sgarg
                                         " hash");
1110 2291 sgarg
                unAccessbleIdList.put(subTreeId, MetaCatUtil.
1111
                                      getInlineDataIdWithoutRev(fileId));
1112
            }
1113 2245 sgarg
        }
1114 1425 tao
      }
1115 2245 sgarg
      return unAccessbleIdList;
1116
   }
1117
1118
1119
   /*
1120
    * This method will get a hash table from xml_access table for all records
1121
    * about the inline data. The key is subtree id and data is a inline internal
1122
    * file name
1123
    */
1124
   private static Hashtable getAllInlineDataIdList(String docid) throws SQLException
1125
   {
1126
     Hashtable inlineDataList = new Hashtable();
1127
     String sql = "SELECT subtreeid, docid FROM xml_access WHERE " +
1128
                   "accessfileid = ? AND subtreeid  IS NOT NULL";
1129
     PreparedStatement pStmt=null;
1130
     ResultSet rs=null;
1131
     DBConnection conn=null;
1132
     int serialNumber=-1;
1133
     try
1134
     {
1135
       //check out DBConnection
1136
       conn=DBConnectionPool.getDBConnection("PermissionControl.getDataSetId");
1137
       serialNumber=conn.getCheckOutSerialNumber();
1138
       pStmt=conn.prepareStatement(sql);
1139
       //bind the value to query
1140
       pStmt.setString(1, docid);
1141
       //execute the query
1142
       pStmt.execute();
1143
       rs=pStmt.getResultSet();
1144
       //process the result
1145
       while(rs.next())
1146
       {
1147
         String subTreeId = rs.getString(1);
1148
         String inlineDataId = rs.getString(2);
1149
         if (subTreeId != null && !subTreeId.trim().equals("") &&
1150
            inlineDataId != null && !inlineDataId.trim().equals(""))
1151
         {
1152
           inlineDataList.put(subTreeId, inlineDataId);
1153
         }
1154
      }//while
1155
     }//try
1156
     finally
1157
     {
1158
       try
1159
       {
1160
         pStmt.close();
1161
       }
1162
       finally
1163
       {
1164
         DBConnectionPool.returnDBConnection(conn, serialNumber);
1165
       }
1166
     }//finally
1167
     return inlineDataList;
1168
   }//getAllInlineDataIdList
1169 1425 tao
}