first stage of transitioning to the new SecurityMonitor-based security

architecture--it's implemented at the global level and for communities,
conferences still use the old hard-coded implementation.  The new
StaticSecurityMonitor is configured via XML data, which will be important
when we implement the new Community Services architecture
This commit is contained in:
Eric J. Bowersox 2001-11-18 09:32:21 +00:00
parent 47b88efd75
commit 5f966a6450
36 changed files with 2024 additions and 572 deletions

View File

@ -54,6 +54,137 @@
<wait-if-busy/> <wait-if-busy/>
</database> </database>
<!-- This section is used to configure the default security contexts, and should probably
not be tampered with. -->
<security>
<security-definition id="Global">
<defined-roles>
<role id="Anonymous" value="L+100">Anonymous User</role>
<role id="Unverified" value="L+500">Unauthenticated User</role>
<role id="Normal" value="L+1000">Normal User</role>
<role id="AnyAdmin" value="HMIN">Any System Administrator</role>
<role id="PFY" value="H+1000">System Assistant Administrator</role>
<role id="BOFH" value="HMAX">Global System Administrator</role>
</defined-roles>
<defined-lists>
<list id="UserLevels">
<element role="Global.Anonymous"/>
<element role="Global.Unverified"/>
<element role="Global.Normal"/>
<element role="UnrestrictedUser"/>
</list>
<list id="UserLevelsPFY">
<element role="Global.Anonymous"/>
<element role="Global.Unverified"/>
<element role="Global.Normal"/>
<element role="UnrestrictedUser"/>
<element role="Global.PFY"/>
</list>
<list id="CreateCommunity">
<permission/>
<element role="Global.Normal" default="true"/>
<element role="UnrestrictedUser"/>
<element role="Global.AnyAdmin"/>
<element role="Global.PFY"/>
<element role="Global.BOFH"/>
</list>
</defined-lists>
<defaults>
<default id="NewUser" role="Global.Unverified"/>
<default id="AfterVerify" role="Global.Normal"/>
<default id="AfterEmailChange" role="Global.Unverified"/>
</defaults>
<permissions>
<permission id="ShowHiddenCategories" role="Global.AnyAdmin"/>
<permission id="NoEmailVerify" role="Global.AnyAdmin"/>
<permission id="SeeHiddenContactInfo" role="Global.AnyAdmin"/>
<permission id="SearchHiddenCommunities" role="Global.AnyAdmin"/>
<permission id="ShowHiddenCommunities" role="Global.AnyAdmin"/>
<permission id="SearchHiddenCategories" role="Global.AnyAdmin"/>
<permission id="SysAdminAccess" role="Global.AnyAdmin"/>
<permission id="PublishFP" role="Global.AnyAdmin"/>
<permission id="DesignatePFY" role="Global.BOFH"/>
</permissions>
</security-definition>
<security-definition id="Community" parent="Global">
<defined-roles>
<role id="Member" value="L+500">Community Member</role>
<role id="AnyAdmin" value="HMIN">Any Community Administrator</role>
<role id="Cohost" value="H+1000">Community Co-Host</role>
<role id="Host" value="H+1500">Community Host</role>
</defined-roles>
<defined-lists>
<list id="Read">
<permission/>
<element role="Global.Anonymous"/>
<element role="Global.Unverified"/>
<element role="Global.Normal"/>
<element role="Community.Member" default="true"/>
<element role="UnrestrictedUser"/>
<element role="Community.AnyAdmin"/>
<element role="Community.Cohost"/>
<element role="Community.Host"/>
<element role="Global.AnyAdmin"/>
</list>
<list id="Write">
<permission/>
<element role="Community.AnyAdmin"/>
<element role="Community.Cohost" default="true"/>
<element role="Community.Host"/>
<element role="Global.AnyAdmin"/>
<element role="Global.PFY"/>
<element role="Global.BOFH"/>
</list>
<list id="Create">
<permission/>
<element role="Global.Normal"/>
<element role="Community.Member"/>
<element role="UnrestrictedUser"/>
<element role="Community.AnyAdmin"/>
<element role="Community.Cohost" default="true"/>
<element role="Community.Host"/>
<element role="Global.AnyAdmin"/>
</list>
<list id="Delete">
<permission/>
<element role="Community.AnyAdmin"/>
<element role="Community.Cohost"/>
<element role="Community.Host" default="true"/>
<element role="Global.AnyAdmin"/>
<element role="Global.PFY"/>
<element role="Global.BOFH"/>
<element role="NoAccess"/>
</list>
<list id="Join">
<permission/>
<element role="Global.Anonymous"/>
<element role="Global.Unverified"/>
<element role="Global.Normal" default="true"/>
</list>
<list id="UserLevels">
<element role="NotInList"/>
<element role="Global.Anonymous"/>
<element role="Global.Unverified"/>
<element role="Global.Normal"/>
<element role="Community.Member"/>
<element role="UnrestrictedUser"/>
<element role="Community.Cohost"/>
</list>
</defined-lists>
<defaults>
<default id="NewUser" role="Community.Member"/>
<default id="Creator" role="Community.Host"/>
</defaults>
<permissions>
<permission id="ShowAdmin" role="Community.AnyAdmin"/>
<permission id="NoJoinRequired" role="Global.AnyAdmin"/>
<permission id="NoKeyRequired" role="Global.AnyAdmin"/>
<permission id="ShowHiddenMembers" role="Community.AnyAdmin"/>
<permission id="ShowHiddenObjects" role="Community.AnyAdmin"/>
</permissions>
</security-definition>
</security>
<!-- This section is used to configure electronic mail services. --> <!-- This section is used to configure electronic mail services. -->
<email> <email>
<!-- The SMTP server to use when sending messages out. This server must be <!-- The SMTP server to use when sending messages out. This server must be

View File

@ -21,8 +21,12 @@ import java.util.List;
public interface AdminOperations public interface AdminOperations
{ {
public abstract SecurityInfo getSecurityInfo();
public abstract boolean isGlobalAdmin(); public abstract boolean isGlobalAdmin();
public abstract List getAllowedRoleList();
public abstract List getAuditRecords(int offset, int count) throws DataException; public abstract List getAuditRecords(int offset, int count) throws DataException;
public abstract int getAuditRecordCount() throws DataException; public abstract int getAuditRecordCount() throws DataException;

View File

@ -20,6 +20,7 @@ package com.silverwrist.venice.core;
import java.util.Date; import java.util.Date;
import java.util.Locale; import java.util.Locale;
import java.util.TimeZone; import java.util.TimeZone;
import com.silverwrist.venice.security.Role;
public interface AdminUserContext public interface AdminUserContext
{ {
@ -37,6 +38,10 @@ public interface AdminUserContext
public abstract void setBaseLevel(int new_level) throws DataException; public abstract void setBaseLevel(int new_level) throws DataException;
public abstract Role getBaseRole();
public abstract void setBaseRole(Role new_role) throws DataException;
public abstract boolean isEmailVerified(); public abstract boolean isEmailVerified();
public abstract void setEmailVerified(boolean flag) throws DataException; public abstract void setEmailVerified(boolean flag) throws DataException;

View File

@ -175,4 +175,6 @@ public interface CommunityContext extends SearchMode
public abstract void setProperties(CommunityProperties props) throws DataException, AccessError; public abstract void setProperties(CommunityProperties props) throws DataException, AccessError;
public abstract SecurityInfo getSecurityInfo();
} // end interface CommunityContext } // end interface CommunityContext

View File

@ -0,0 +1,35 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Communities System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.core;
import java.util.List;
import com.silverwrist.venice.security.Role;
public interface SecurityInfo
{
public abstract List getRoleList(String symbol);
public abstract Role getRole(String symbol);
public abstract Role getRoleForLevel(int level);
public abstract Role getDefaultRole(String symbol);
public abstract String getID();
} // end interface SecurityInfo

View File

@ -85,4 +85,6 @@ public interface VeniceEngine extends SearchMode
public abstract Dimension getCommunityLogoSize(); public abstract Dimension getCommunityLogoSize();
public abstract SecurityInfo getSecurityInfo();
} // end interface VeniceEngine } // end interface VeniceEngine

View File

@ -58,12 +58,27 @@ class AdminOperationsImpl implements AdminOperations
*-------------------------------------------------------------------------------- *--------------------------------------------------------------------------------
*/ */
public SecurityInfo getSecurityInfo()
{
return env.getEngine().getSelf().getSecurityInfo();
} // end getSecurityInfo
public boolean isGlobalAdmin() public boolean isGlobalAdmin()
{ {
return (env.getUser().realBaseLevel()==SecLevels.GLOBAL_BOFH); return (env.getUser().realBaseLevel()==SecLevels.GLOBAL_BOFH);
} // end isGlobalAdmin } // end isGlobalAdmin
public List getAllowedRoleList()
{
if (env.testPermission(EnvUser.PERM_DESIGNATEPFY))
return env.getRoleList("Global.UserLevelsPFY");
else
return env.getRoleList("Global.UserLevels");
} // end getAllowedRoleList
public List getAuditRecords(int offset, int count) throws DataException public List getAuditRecords(int offset, int count) throws DataException
{ {
Connection conn = null; Connection conn = null;

View File

@ -24,8 +24,7 @@ import com.silverwrist.util.International;
import com.silverwrist.venice.core.*; import com.silverwrist.venice.core.*;
import com.silverwrist.venice.core.internals.*; import com.silverwrist.venice.core.internals.*;
import com.silverwrist.venice.db.*; import com.silverwrist.venice.db.*;
import com.silverwrist.venice.security.PasswordHash; import com.silverwrist.venice.security.*;
import com.silverwrist.venice.security.AuditRecord;
class AdminUserContextImpl implements AdminUserContext class AdminUserContextImpl implements AdminUserContext
{ {
@ -203,6 +202,18 @@ class AdminUserContextImpl implements AdminUserContext
} // end setBaseLevel } // end setBaseLevel
public Role getBaseRole()
{
return env.getRoleForLevel(level);
} // end getBaseRole
public void setBaseRole(Role new_role) throws DataException
{
setBaseLevel(new_role.getLevel());
} // end setBaseRole
public boolean isEmailVerified() public boolean isEmailVerified()
{ {
return email_verified; return email_verified;

View File

@ -370,7 +370,7 @@ class CategoryDescriptorImpl implements CategoryDescriptor, Cloneable
*-------------------------------------------------------------------------------- *--------------------------------------------------------------------------------
*/ */
static List getTopLevelCategoryList(EnvEngine env, boolean do_hide) throws DataException static List getTopLevelCategoryList(EnvEngine env, boolean show_all) throws DataException
{ {
Connection conn = null; Connection conn = null;
ArrayList rc = new ArrayList(); ArrayList rc = new ArrayList();
@ -379,7 +379,7 @@ class CategoryDescriptorImpl implements CategoryDescriptor, Cloneable
conn = env.getConnection(); conn = env.getConnection();
Statement stmt = conn.createStatement(); Statement stmt = conn.createStatement();
StringBuffer sql = new StringBuffer("SELECT catid, symlink, name FROM refcategory WHERE parent = -1"); StringBuffer sql = new StringBuffer("SELECT catid, symlink, name FROM refcategory WHERE parent = -1");
if (do_hide) if (!show_all)
sql.append(" AND hide_dir = 0"); sql.append(" AND hide_dir = 0");
sql.append(';'); sql.append(';');
@ -388,7 +388,7 @@ class CategoryDescriptorImpl implements CategoryDescriptor, Cloneable
while (rs.next()) while (rs.next())
{ // turn data values into CategoryDescriptor objects { // turn data values into CategoryDescriptor objects
CategoryDescriptor ncd = new CategoryDescriptorImpl(env,rs.getInt(1),rs.getInt(2),rs.getString(3), CategoryDescriptor ncd = new CategoryDescriptorImpl(env,rs.getInt(1),rs.getInt(2),rs.getString(3),
do_hide); !show_all);
rc.add(ncd); rc.add(ncd);
} // end while } // end while
@ -409,7 +409,7 @@ class CategoryDescriptorImpl implements CategoryDescriptor, Cloneable
} // end getTopLevelCategoryList } // end getTopLevelCategoryList
static List searchForCategories(EnvEngine env, boolean do_hide, boolean search_all, int mode, static List searchForCategories(EnvEngine env, boolean show_all, boolean search_all, int mode,
String term, int offset, int count) throws DataException String term, int offset, int count) throws DataException
{ {
if (logger.isDebugEnabled()) if (logger.isDebugEnabled())
@ -444,7 +444,7 @@ class CategoryDescriptorImpl implements CategoryDescriptor, Cloneable
} // end switch } // end switch
if (do_hide) if (!show_all)
sql.append(" AND hide_dir = 0"); sql.append(" AND hide_dir = 0");
if (!search_all) if (!search_all)
sql.append(" AND hide_search = 0"); sql.append(" AND hide_search = 0");
@ -464,7 +464,7 @@ class CategoryDescriptorImpl implements CategoryDescriptor, Cloneable
for (int i=0; i<n; i++) for (int i=0; i<n; i++)
{ // convert all the simple category IDs into full-blown CategoryDescriptor objects { // convert all the simple category IDs into full-blown CategoryDescriptor objects
CategoryDescriptor tmp = new CategoryDescriptorImpl(env,conn,rc_raw[i],do_hide); CategoryDescriptor tmp = new CategoryDescriptorImpl(env,conn,rc_raw[i],!show_all);
rc.add(tmp); rc.add(tmp);
} // end for } // end for
@ -486,7 +486,7 @@ class CategoryDescriptorImpl implements CategoryDescriptor, Cloneable
} // end searchForCategories } // end searchForCategories
static int getSearchCategoryCount(EnvEngine env, boolean do_hide, boolean search_all, int mode, static int getSearchCategoryCount(EnvEngine env, boolean show_all, boolean search_all, int mode,
String term) throws DataException String term) throws DataException
{ {
if (logger.isDebugEnabled()) if (logger.isDebugEnabled())
@ -519,7 +519,7 @@ class CategoryDescriptorImpl implements CategoryDescriptor, Cloneable
} // end switch } // end switch
if (do_hide) if (!show_all)
sql.append(" AND hide_dir = 0"); sql.append(" AND hide_dir = 0");
if (!search_all) if (!search_all)
sql.append(" AND hide_search = 0"); sql.append(" AND hide_search = 0");

View File

@ -27,7 +27,6 @@ import com.silverwrist.venice.db.*;
import com.silverwrist.venice.core.*; import com.silverwrist.venice.core.*;
import com.silverwrist.venice.core.internals.*; import com.silverwrist.venice.core.internals.*;
import com.silverwrist.venice.security.AuditRecord; import com.silverwrist.venice.security.AuditRecord;
import com.silverwrist.venice.security.Capability;
import com.silverwrist.venice.security.DefaultLevels; import com.silverwrist.venice.security.DefaultLevels;
class CommunityCoreData implements CommunityData, CommunityDataBackend class CommunityCoreData implements CommunityData, CommunityDataBackend
@ -183,16 +182,17 @@ class CommunityCoreData implements CommunityData, CommunityDataBackend
{ {
if (logger.isDebugEnabled()) if (logger.isDebugEnabled())
logger.debug("new CommunityCoreData for BRAND NEW COMMUNITY " + cid); logger.debug("new CommunityCoreData for BRAND NEW COMMUNITY " + cid);
this.env = new EnvCommunityData(env,this); EnvCommunityData new_env = new EnvCommunityData(env,this);
this.env = new_env;
this.cid = cid; this.cid = cid;
this.created = creation; this.created = creation;
this.last_access = creation; this.last_access = creation;
this.last_update = creation; this.last_update = creation;
this.read_level = DefaultLevels.newCommunityRead(); this.read_level = new_env.getDefaultRole("Community.Read").getLevel();
this.write_level = DefaultLevels.newCommunityWrite(); this.write_level = new_env.getDefaultRole("Community.Write").getLevel();
this.create_level = DefaultLevels.newCommunityCreate(); this.create_level = new_env.getDefaultRole("Community.Create").getLevel();
this.delete_level = DefaultLevels.newCommunityDelete(); this.delete_level = new_env.getDefaultRole("Community.Delete").getLevel();
this.join_level = DefaultLevels.newCommunityJoin(); this.join_level = new_env.getDefaultRole("Community.Join").getLevel();
this.contactid = -1; this.contactid = -1;
this.host_uid = host_uid; this.host_uid = host_uid;
this.category_id = 0; this.category_id = 0;
@ -430,7 +430,7 @@ class CommunityCoreData implements CommunityData, CommunityDataBackend
{ {
if (deleted) if (deleted)
throw new DataException("This community has been deleted."); throw new DataException("This community has been deleted.");
if (Capability.exemptFromMembershipRequirement(level)) if (env.testPermission(EnvCommunityData.PERM_NOJOINREQUIRED,level))
return; return;
if (members_only && !is_member) if (members_only && !is_member)
{ // the membership test failed { // the membership test failed
@ -445,7 +445,7 @@ class CommunityCoreData implements CommunityData, CommunityDataBackend
{ {
if (deleted) if (deleted)
return false; return false;
if (Capability.exemptFromMembershipRequirement(level)) if (env.testPermission(EnvCommunityData.PERM_NOJOINREQUIRED,level))
return true; return true;
return !members_only || is_member; return !members_only || is_member;
@ -1980,16 +1980,19 @@ class CommunityCoreData implements CommunityData, CommunityDataBackend
+ "rules, joinkey, alias) VALUES ('"); + "rules, joinkey, alias) VALUES ('");
creation = new java.util.Date(); creation = new java.util.Date();
String creation_str = SQLUtil.encodeDate(creation); String creation_str = SQLUtil.encodeDate(creation);
int level_read = env.getCommunityDefaultRole("Community.Read").getLevel();
int level_write = env.getCommunityDefaultRole("Community.Write").getLevel();
int level_create = env.getCommunityDefaultRole("Community.Create").getLevel();
int level_delete = env.getCommunityDefaultRole("Community.Delete").getLevel();
int level_join = env.getCommunityDefaultRole("Community.Join").getLevel();
sql.append(creation).append("', '").append(creation).append("', '").append(creation).append("', "); sql.append(creation).append("', '").append(creation).append("', '").append(creation).append("', ");
sql.append(DefaultLevels.newCommunityRead()).append(", ").append(DefaultLevels.newCommunityWrite()); sql.append(level_read).append(", ").append(level_write).append(", ").append(level_create).append(", ");
sql.append(", ").append(DefaultLevels.newCommunityCreate()).append(", "); sql.append(level_delete).append(", ").append(level_join).append(", ").append(host_uid).append(", ");
sql.append(DefaultLevels.newCommunityDelete()).append(", ").append(DefaultLevels.newCommunityJoin()); sql.append(hide_dir ? '1' : '0').append(", ").append(hide_search ? '1' : '0').append(", ");
sql.append(", ").append(host_uid).append(", ").append(hide_dir ? '1' : '0').append(", "); sql.append(SQLUtil.encodeStringArg(name)).append(", ").append(SQLUtil.encodeStringArg(language));
sql.append(hide_search ? '1' : '0').append(", ").append(SQLUtil.encodeStringArg(name)).append(", "); sql.append(", ").append(SQLUtil.encodeStringArg(synopsis)).append(", ");
sql.append(SQLUtil.encodeStringArg(language)).append(", ").append(SQLUtil.encodeStringArg(synopsis)); sql.append(SQLUtil.encodeStringArg(rules)).append(", ").append(SQLUtil.encodeStringArg(joinkey));
sql.append(", ").append(SQLUtil.encodeStringArg(rules)).append(", "); sql.append(", ").append(SQLUtil.encodeStringArg(alias)).append(");");
sql.append(SQLUtil.encodeStringArg(joinkey)).append(", ").append(SQLUtil.encodeStringArg(alias));
sql.append(");");
if (logger.isDebugEnabled()) if (logger.isDebugEnabled())
logger.debug("SQL: " + sql.toString()); logger.debug("SQL: " + sql.toString());
@ -2037,8 +2040,8 @@ class CommunityCoreData implements CommunityData, CommunityDataBackend
// is "locked" so they can't unjoin and leave the community hostless. // is "locked" so they can't unjoin and leave the community hostless.
sql.setLength(0); sql.setLength(0);
sql.append("INSERT INTO sigmember(sigid, uid, granted_lvl, locked) VALUES (").append(new_cid); sql.append("INSERT INTO sigmember(sigid, uid, granted_lvl, locked) VALUES (").append(new_cid);
sql.append(", ").append(host_uid).append(", ").append(DefaultLevels.creatorCommunity()); sql.append(", ").append(host_uid).append(", ");
sql.append(", 1);"); sql.append(env.getCommunityDefaultRole("Community.Creator").getLevel()).append(", 1);");
if (logger.isDebugEnabled()) if (logger.isDebugEnabled())
logger.debug("SQL: " + sql.toString()); logger.debug("SQL: " + sql.toString());
stmt.executeUpdate(sql.toString()); stmt.executeUpdate(sql.toString());

View File

@ -25,8 +25,8 @@ import com.silverwrist.venice.core.*;
import com.silverwrist.venice.core.internals.*; import com.silverwrist.venice.core.internals.*;
import com.silverwrist.venice.db.*; import com.silverwrist.venice.db.*;
import com.silverwrist.venice.security.AuditRecord; import com.silverwrist.venice.security.AuditRecord;
import com.silverwrist.venice.security.Capability;
import com.silverwrist.venice.security.DefaultLevels; import com.silverwrist.venice.security.DefaultLevels;
import com.silverwrist.venice.security.Role;
class CommunityUserContextImpl implements CommunityContext, CommunityBackend class CommunityUserContextImpl implements CommunityContext, CommunityBackend
{ {
@ -118,11 +118,12 @@ class CommunityUserContextImpl implements CommunityContext, CommunityBackend
{ {
if (logger.isDebugEnabled()) if (logger.isDebugEnabled())
logger.debug("CommunityUserContextImpl constructor:newCommunity"); logger.debug("CommunityUserContextImpl constructor:newCommunity");
this.env = new EnvCommunity(env,this); EnvCommunity new_env = new EnvCommunity(env,this);
this.env = new_env;
this.cid = data.getID(); this.cid = data.getID();
this.cache = null; // no cache required - we have the CommunityData this.cache = null; // no cache required - we have the CommunityData
this.data = data; this.data = data;
setMemberValues(DefaultLevels.creatorCommunity(),true,true); setMemberValues(new_env.getDefaultRole("Community.Creator").getLevel(),true,true);
} // end constructor } // end constructor
@ -139,7 +140,7 @@ class CommunityUserContextImpl implements CommunityContext, CommunityBackend
this.level = Math.max(env.getUser().realBaseLevel(),granted_level); this.level = Math.max(env.getUser().realBaseLevel(),granted_level);
this.is_member = member; this.is_member = member;
this.show_admin = Capability.isCommunityAdmin(granted_level); this.show_admin = env.isLevelAdmin(granted_level);
this.locked = locked; this.locked = locked;
} // end setMemberValues } // end setMemberValues
@ -327,7 +328,7 @@ class CommunityUserContextImpl implements CommunityContext, CommunityBackend
if (deleted) if (deleted)
throw new DataException("This community has been deleted."); throw new DataException("This community has been deleted.");
return new CategoryDescriptorImpl(env,getData().getCategoryID(), return new CategoryDescriptorImpl(env,getData().getCategoryID(),
Capability.hideHiddenCategories(env.getUser().realBaseLevel())); !(env.testPermission(EnvUser.PERM_SHOWHIDDENCATS)));
} // end getCategory } // end getCategory
@ -363,8 +364,7 @@ class CommunityUserContextImpl implements CommunityContext, CommunityBackend
conn = env.getConnection(); conn = env.getConnection();
// load the profile for the user // load the profile for the user
return new UserProfileImpl(env,conn,getData().getHostUID(), return new UserProfileImpl(env,conn,getData().getHostUID());
Capability.canSeeHiddenContactFields(env.getUser().realBaseLevel()));
} // end try } // end try
catch (SQLException e) catch (SQLException e)
@ -953,7 +953,7 @@ class CommunityUserContextImpl implements CommunityContext, CommunityBackend
if (!(getData().isPublicCommunity())) if (!(getData().isPublicCommunity()))
{ // this is a private community - but admins can join anyway { // this is a private community - but admins can join anyway
if (!(Capability.canJoinPrivateCommunityWithoutKey(level))) if (!(env.testPermission(EnvCommunity.PERM_NOKEYREQUIRED)))
{ // we need to test the join key against the one they supply { // we need to test the join key against the one they supply
String real_key = getData().getJoinKey(); String real_key = getData().getJoinKey();
if (!(real_key.equals(joinkey))) if (!(real_key.equals(joinkey)))
@ -970,10 +970,11 @@ class CommunityUserContextImpl implements CommunityContext, CommunityBackend
// else we can join without specifying a key // else we can join without specifying a key
// actually set the data in the database // actually set the data in the database
getData().setMembership(env,env.getUserID(),DefaultLevels.memberCommunity(),false,false); Role new_role = env.getDefaultRole("Community.NewUser");
getData().setMembership(env,env.getUserID(),new_role.getLevel(),false,false);
// and update our internal data store // and update our internal data store
setMemberValues(DefaultLevels.memberCommunity(),true,false); setMemberValues(new_role.getLevel(),true,false);
// and that's it! You expected lightning bolts maybe? // and that's it! You expected lightning bolts maybe?
@ -1008,7 +1009,7 @@ class CommunityUserContextImpl implements CommunityContext, CommunityBackend
public int getMemberCount() throws DataException public int getMemberCount() throws DataException
{ {
return getData().getMemberCount(Capability.showHiddenCommunityMembers(level)); return getData().getMemberCount(env.testPermission(EnvCommunity.PERM_SHOWHIDDENMEMBERS));
} // end getMemberCount } // end getMemberCount
@ -1095,19 +1096,20 @@ class CommunityUserContextImpl implements CommunityContext, CommunityBackend
throws DataException throws DataException
{ {
return getData().searchForMembers(field,mode,term,offset,count, return getData().searchForMembers(field,mode,term,offset,count,
Capability.showHiddenCommunityMembers(level)); env.testPermission(EnvCommunity.PERM_SHOWHIDDENMEMBERS));
} // end searchForMembers } // end searchForMembers
public int getSearchMemberCount(int field, int mode, String term) throws DataException public int getSearchMemberCount(int field, int mode, String term) throws DataException
{ {
return getData().getSearchMemberCount(field,mode,term,Capability.showHiddenCommunityMembers(level)); return getData().getSearchMemberCount(field,mode,term,
env.testPermission(EnvCommunity.PERM_SHOWHIDDENMEMBERS));
} // end getSearchMemberCount } // end getSearchMemberCount
public List getMemberList() throws DataException public List getMemberList() throws DataException
{ {
return getData().getMemberList(Capability.showHiddenCommunityMembers(level)); return getData().getMemberList(env.testPermission(EnvCommunity.PERM_SHOWHIDDENMEMBERS));
} // end getMemberList } // end getMemberList
@ -1349,6 +1351,12 @@ class CommunityUserContextImpl implements CommunityContext, CommunityBackend
} // end setProperties } // end setProperties
public SecurityInfo getSecurityInfo()
{
return env.getSecurityInfo();
} // end getSecurityInfo
/*-------------------------------------------------------------------------------- /*--------------------------------------------------------------------------------
* Implementations from interface CommunityBackend * Implementations from interface CommunityBackend
*-------------------------------------------------------------------------------- *--------------------------------------------------------------------------------
@ -1368,7 +1376,7 @@ class CommunityUserContextImpl implements CommunityContext, CommunityBackend
public boolean userHideHiddenConferences() public boolean userHideHiddenConferences()
{ {
return Capability.hideHiddenConferences(level); return !(env.testPermission(EnvCommunity.PERM_SHOWHIDDENOBJECTS));
} // end userHideHiddenConferences } // end userHideHiddenConferences
@ -1420,6 +1428,33 @@ class CommunityUserContextImpl implements CommunityContext, CommunityBackend
} // end getDataBackend } // end getDataBackend
public boolean env_testPermission(String symbol)
{
if (deleted)
return false;
CommunityData d = getDataNE();
if (d==null)
return false;
if (symbol.equals(EnvCommunity.PERM_JOIN))
return (is_member ? false : d.canJoinCommunity(env.getUserID(),level));
if (!(d.checkMembership(level,is_member)))
return false;
if (symbol.equals(EnvCommunity.PERM_READ))
return d.canReadCommunitySubObjects(level);
if (symbol.equals(EnvCommunity.PERM_WRITE))
return d.canModifyCommunityProfile(level);
if (symbol.equals(EnvCommunity.PERM_CREATE))
return d.canCreateCommunitySubObjects(level);
if (symbol.equals(EnvCommunity.PERM_DELETE))
return d.canDeleteCommunity(level);
return false;
} // end env_testPermission
/*-------------------------------------------------------------------------------- /*--------------------------------------------------------------------------------
* Static operations for use within the implementation package * Static operations for use within the implementation package
*-------------------------------------------------------------------------------- *--------------------------------------------------------------------------------
@ -1591,7 +1626,7 @@ class CommunityUserContextImpl implements CommunityContext, CommunityBackend
} // end switch } // end switch
if (Capability.hideHiddenSearchCommunities(env.getUser().realBaseLevel())) if (!(env.testPermission(EnvUser.PERM_SEARCHHIDDENCOMMUNITIES)))
sql.append(" AND hide_search = 0"); sql.append(" AND hide_search = 0");
sql.append(" ORDER BY signame LIMIT ").append(offset).append(", ").append(count+1).append(';'); sql.append(" ORDER BY signame LIMIT ").append(offset).append(", ").append(count+1).append(';');
@ -1676,7 +1711,7 @@ class CommunityUserContextImpl implements CommunityContext, CommunityBackend
} // end switch } // end switch
if (Capability.hideHiddenSearchCommunities(env.getUser().realBaseLevel())) if (!(env.testPermission(EnvUser.PERM_SEARCHHIDDENCOMMUNITIES)))
sql.append(" AND hide_search = 0"); sql.append(" AND hide_search = 0");
sql.append(';'); sql.append(';');
@ -1720,7 +1755,7 @@ class CommunityUserContextImpl implements CommunityContext, CommunityBackend
Statement stmt = conn.createStatement(); Statement stmt = conn.createStatement();
StringBuffer sql = new StringBuffer("SELECT sigid, signame, alias FROM sigs WHERE catid = "); StringBuffer sql = new StringBuffer("SELECT sigid, signame, alias FROM sigs WHERE catid = ");
sql.append(catid); sql.append(catid);
if (Capability.hideHiddenDirectoryCommunities(env.getUser().realBaseLevel())) if (!(env.testPermission(EnvUser.PERM_SHOWHIDDENCOMMUNITIES)))
sql.append(" AND hide_dir = 0"); sql.append(" AND hide_dir = 0");
sql.append(" ORDER BY signame LIMIT ").append(offset).append(", ").append(count+1).append(';'); sql.append(" ORDER BY signame LIMIT ").append(offset).append(", ").append(count+1).append(';');
@ -1770,7 +1805,7 @@ class CommunityUserContextImpl implements CommunityContext, CommunityBackend
Statement stmt = conn.createStatement(); Statement stmt = conn.createStatement();
StringBuffer sql = new StringBuffer("SELECT COUNT(*) FROM sigs WHERE catid = "); StringBuffer sql = new StringBuffer("SELECT COUNT(*) FROM sigs WHERE catid = ");
sql.append(catid); sql.append(catid);
if (Capability.hideHiddenDirectoryCommunities(env.getUser().realBaseLevel())) if (!(env.testPermission(EnvUser.PERM_SHOWHIDDENCOMMUNITIES)))
sql.append(" AND hide_dir = 0"); sql.append(" AND hide_dir = 0");
sql.append(';'); sql.append(';');

View File

@ -28,7 +28,6 @@ import com.silverwrist.venice.core.*;
import com.silverwrist.venice.core.internals.*; import com.silverwrist.venice.core.internals.*;
import com.silverwrist.venice.db.*; import com.silverwrist.venice.db.*;
import com.silverwrist.venice.security.AuditRecord; import com.silverwrist.venice.security.AuditRecord;
import com.silverwrist.venice.security.Capability;
class TopicMessageUserContextImpl implements TopicMessageContext class TopicMessageUserContextImpl implements TopicMessageContext
{ {
@ -47,23 +46,23 @@ class TopicMessageUserContextImpl implements TopicMessageContext
*/ */
private EnvConference env; // the conference environment private EnvConference env; // the conference environment
private long postid; private long postid; // the ID of this post
private long parent; private long parent; // the parent post ID (not really used)
private int num; private int num; // the post number within the topic
private int linecount; private int linecount; // number of lines in message
private int creator_uid; private int creator_uid; // the UID of the poster
private java.util.Date posted; private java.util.Date posted; // date and time posted
private boolean hidden; private boolean hidden; // has this post been hidden?
private int scribble_uid; private int scribble_uid; // UID of the user who scribbled it
private java.util.Date scribble_date; private java.util.Date scribble_date; // date and time it was scribbled
private String pseud; private String pseud; // the pseud attached to this message
private int datalen; private int datalen; // length in bytes of attachment
private String filename; private String filename; // file name of attachment
private String mimetype; private String mimetype; // MIME type for attachment
private int stgmethod; private int stgmethod; // storage method for attachment
private boolean nuked = false; private boolean nuked = false; // has this message been nuked?
private String creator_cache = null; private String creator_cache = null; // cache for username of creator
private String text_cache = null; private String text_cache = null; // cache for actual message text
/*-------------------------------------------------------------------------------- /*--------------------------------------------------------------------------------
* Constructors * Constructors
@ -966,7 +965,7 @@ class TopicMessageUserContextImpl implements TopicMessageContext
public boolean canPublish() public boolean canPublish()
{ {
if (!(Capability.canPublishToFrontPage(env.getUser().realBaseLevel()))) if (!(env.testPermission(EnvUser.PERM_PUBLISH_FP)))
return false; // must be a sysadmin to publish return false; // must be a sysadmin to publish
if ((scribble_date!=null) || nuked) if ((scribble_date!=null) || nuked)
return false; // cannot publish a scribbled or nuked message return false; // cannot publish a scribbled or nuked message
@ -1001,13 +1000,7 @@ class TopicMessageUserContextImpl implements TopicMessageContext
public void publish() throws DataException, AccessError public void publish() throws DataException, AccessError
{ {
if (!(Capability.canPublishToFrontPage(env.getUser().realBaseLevel()))) env.testPermission(EnvUser.PERM_PUBLISH_FP,"You are not permitted to publish postings to the front page.");
{ // you aren't allowed to publish - naughty naughty!
logger.error("unable to publish because we're not allowed");
throw new AccessError("You are not permitted to publish postings to the front page.");
} // end if
if (nuked) if (nuked)
{ // we can't publish a nuked message! { // we can't publish a nuked message!
logger.error("unable to publish because message nuked"); logger.error("unable to publish because message nuked");

View File

@ -25,10 +25,7 @@ import com.silverwrist.venice.*;
import com.silverwrist.venice.core.*; import com.silverwrist.venice.core.*;
import com.silverwrist.venice.core.internals.*; import com.silverwrist.venice.core.internals.*;
import com.silverwrist.venice.db.*; import com.silverwrist.venice.db.*;
import com.silverwrist.venice.security.PasswordHash; import com.silverwrist.venice.security.*;
import com.silverwrist.venice.security.Capability;
import com.silverwrist.venice.security.DefaultLevels;
import com.silverwrist.venice.security.AuditRecord;
class UserContextImpl implements UserContext, UserBackend class UserContextImpl implements UserContext, UserBackend
{ {
@ -238,6 +235,7 @@ class UserContextImpl implements UserContext, UserBackend
// Figure out which of those communities we haven't joined yet and set up to autojoin them. // Figure out which of those communities we haven't joined yet and set up to autojoin them.
sql.setLength(0); sql.setLength(0);
int new_level = env.getCommunityDefaultRole("Community.NewUser").getLevel();
for (int i=0; i<tmp_cid.size(); i++) for (int i=0; i<tmp_cid.size(); i++)
{ // see if the user is already a member of this community { // see if the user is already a member of this community
Integer x_cid = (Integer)(tmp_cid.get(i)); Integer x_cid = (Integer)(tmp_cid.get(i));
@ -250,9 +248,8 @@ class UserContextImpl implements UserContext, UserBackend
sql.append("INSERT INTO sigmember (sigid, uid, granted_lvl, locked) VALUES "); sql.append("INSERT INTO sigmember (sigid, uid, granted_lvl, locked) VALUES ");
else else
sql.append(", "); sql.append(", ");
sql.append("(").append(x_cid).append(", ").append(uid).append(", "); sql.append("(").append(x_cid).append(", ").append(uid).append(", ").append(new_level).append(", ");
sql.append(DefaultLevels.memberCommunity()).append(", ").append(x_locked.booleanValue() ? '1' : '0'); sql.append(x_locked.booleanValue() ? '1' : '0').append(")");
sql.append(")");
} // end if } // end if
@ -481,7 +478,7 @@ class UserContextImpl implements UserContext, UserBackend
{ {
if (logger.isDebugEnabled()) if (logger.isDebugEnabled())
logger.debug("confirmEmail(): confirming for UID " + uid); logger.debug("confirmEmail(): confirming for UID " + uid);
if ((email_verified) || Capability.exemptFromEmailVerification(level)) if ((email_verified) || env.testPermission(EnvUser.PERM_NOEMAILVERIFY))
{ // already confirmed { // already confirmed
if (logger.isDebugEnabled()) if (logger.isDebugEnabled())
logger.debug("...user has either already confirmed or is exempt"); logger.debug("...user has either already confirmed or is exempt");
@ -501,16 +498,17 @@ class UserContextImpl implements UserContext, UserBackend
} // end if } // end if
Connection conn = null; Connection conn = null;
Role new_role = env.getDefaultRole("Global.AfterVerify");
try try
{ // get a connection and set the user's status to reflect the verification { // get a connection and set the user's status to reflect the verification
conn = env.getConnection(); conn = env.getConnection();
Statement stmt = conn.createStatement(); Statement stmt = conn.createStatement();
StringBuffer sql = new StringBuffer("UPDATE users SET verify_email = 1, base_lvl = "); StringBuffer sql = new StringBuffer("UPDATE users SET verify_email = 1, base_lvl = ");
sql.append(DefaultLevels.afterEmailVerification()).append(" WHERE uid = ").append(uid).append(';'); sql.append(new_role.getLevel()).append(" WHERE uid = ").append(uid).append(';');
stmt.executeUpdate(sql.toString()); stmt.executeUpdate(sql.toString());
email_verified = true; email_verified = true;
level = DefaultLevels.afterEmailVerification(); level = new_role.getLevel();
autoJoinCommunities(conn); // EJB 4/14/2001 - handle autojoin of any SIGs we couldn't autojoin at autoJoinCommunities(conn); // EJB 4/14/2001 - handle autojoin of any SIGs we couldn't autojoin at
// account creation time // account creation time
@ -549,7 +547,7 @@ class UserContextImpl implements UserContext, UserBackend
{ {
if (logger.isDebugEnabled()) if (logger.isDebugEnabled())
logger.debug("resendEmailConfirmation(): resending for UID " + uid); logger.debug("resendEmailConfirmation(): resending for UID " + uid);
if ((email_verified) || Capability.exemptFromEmailVerification(level)) if ((email_verified) || env.testPermission(EnvUser.PERM_NOEMAILVERIFY))
{ // already confirmed, no need to resend { // already confirmed, no need to resend
if (logger.isDebugEnabled()) if (logger.isDebugEnabled())
logger.debug("...user has either already confirmed or is exempt"); logger.debug("...user has either already confirmed or is exempt");
@ -678,7 +676,7 @@ class UserContextImpl implements UserContext, UserBackend
if (my_email==null) // filling in, this is not necessarily the first time if (my_email==null) // filling in, this is not necessarily the first time
my_email = ci.getEmail(); my_email = ci.getEmail();
else if (!(my_email.equals(ci.getEmail())) && !Capability.exemptFromEmailVerification(level)) else if (!(my_email.equals(ci.getEmail())) && !(env.testPermission(EnvUser.PERM_NOEMAILVERIFY)))
{ // email address change - need to reconfirm - but choose a new confirmation { // email address change - need to reconfirm - but choose a new confirmation
// number and save it in the database first; also turn off the verify flag // number and save it in the database first; also turn off the verify flag
// and set the base level to GLOBAL_UNVERIFIED // and set the base level to GLOBAL_UNVERIFIED
@ -689,10 +687,11 @@ class UserContextImpl implements UserContext, UserBackend
// generate new confirmation number // generate new confirmation number
int new_confirm_num = env.getEngine().getNewConfirmationNumber(); int new_confirm_num = env.getEngine().getNewConfirmationNumber();
Role new_role = env.getDefaultRole("Global.Unverified");
// create an SQL statement to reset the user account information, and execute it // create an SQL statement to reset the user account information, and execute it
StringBuffer sql = new StringBuffer("UPDATE users SET verify_email = 0, email_confnum = "); StringBuffer sql = new StringBuffer("UPDATE users SET verify_email = 0, email_confnum = ");
sql.append(new_confirm_num).append(", base_lvl = ").append(DefaultLevels.afterEmailAddressChange()); sql.append(new_confirm_num).append(", base_lvl = ").append(new_role.getLevel());
sql.append(" WHERE uid = ").append(uid).append(';'); sql.append(" WHERE uid = ").append(uid).append(';');
Statement stmt = conn.createStatement(); Statement stmt = conn.createStatement();
stmt.executeUpdate(sql.toString()); stmt.executeUpdate(sql.toString());
@ -700,7 +699,7 @@ class UserContextImpl implements UserContext, UserBackend
// save off changed data // save off changed data
email_verified = false; email_verified = false;
confirm_num = new_confirm_num; confirm_num = new_confirm_num;
level = DefaultLevels.afterEmailAddressChange(); level = new_role.getLevel();
// now send the email confirmation! // now send the email confirmation!
sendEmailConfirmation(); sendEmailConfirmation();
@ -755,8 +754,7 @@ class UserContextImpl implements UserContext, UserBackend
try try
{ // retrieve a connection from the data pool { // retrieve a connection from the data pool
conn = env.getConnection(); conn = env.getConnection();
UserProfileImpl prof = new UserProfileImpl(env,conn,xusername, UserProfileImpl prof = new UserProfileImpl(env,conn,xusername);
Capability.canSeeHiddenContactFields(level));
if (logger.isDebugEnabled()) if (logger.isDebugEnabled())
logger.debug("...found it!"); logger.debug("...found it!");
return prof; return prof;
@ -785,8 +783,7 @@ class UserContextImpl implements UserContext, UserBackend
try try
{ // retrieve a connection from the data pool { // retrieve a connection from the data pool
conn = env.getConnection(); conn = env.getConnection();
UserProfileImpl prof = new UserProfileImpl(env,conn,xuid, UserProfileImpl prof = new UserProfileImpl(env,conn,xuid);
Capability.canSeeHiddenContactFields(level));
if (logger.isDebugEnabled()) if (logger.isDebugEnabled())
logger.debug("...found it!"); logger.debug("...found it!");
return prof; return prof;
@ -914,13 +911,13 @@ class UserContextImpl implements UserContext, UserBackend
public List getRootCategoryList() throws DataException public List getRootCategoryList() throws DataException
{ {
return CategoryDescriptorImpl.getTopLevelCategoryList(env,Capability.hideHiddenCategories(level)); return CategoryDescriptorImpl.getTopLevelCategoryList(env,env.testPermission(EnvUser.PERM_SHOWHIDDENCATS));
} // end getRootCategoryList } // end getRootCategoryList
public CategoryDescriptor getCategoryDescriptor(int catid) throws DataException public CategoryDescriptor getCategoryDescriptor(int catid) throws DataException
{ {
return new CategoryDescriptorImpl(env,catid,Capability.hideHiddenCategories(level)); return new CategoryDescriptorImpl(env,catid,!(env.testPermission(EnvUser.PERM_SHOWHIDDENCATS)));
} // end getCategoryDescriptor } // end getCategoryDescriptor
@ -963,16 +960,16 @@ class UserContextImpl implements UserContext, UserBackend
public List searchForCategories(int mode, String term, int offset, int count) throws DataException public List searchForCategories(int mode, String term, int offset, int count) throws DataException
{ {
return CategoryDescriptorImpl.searchForCategories(env,Capability.hideHiddenCategories(level), return CategoryDescriptorImpl.searchForCategories(env,env.testPermission(EnvUser.PERM_SHOWHIDDENCATS),
Capability.showHiddenSearchCategories(level),mode, env.testPermission(EnvUser.PERM_SEARCHHIDDENCATS),mode,
term,offset,count); term,offset,count);
} // end searchForCategories } // end searchForCategories
public int getSearchCategoryCount(int mode, String term) throws DataException public int getSearchCategoryCount(int mode, String term) throws DataException
{ {
return CategoryDescriptorImpl.getSearchCategoryCount(env,Capability.hideHiddenCategories(level), return CategoryDescriptorImpl.getSearchCategoryCount(env,env.testPermission(EnvUser.PERM_SHOWHIDDENCATS),
Capability.showHiddenSearchCategories(level), env.testPermission(EnvUser.PERM_SEARCHHIDDENCATS),
mode,term); mode,term);
} // end getSearchCategoryCount } // end getSearchCategoryCount
@ -981,8 +978,7 @@ class UserContextImpl implements UserContext, UserBackend
String rules, String joinkey, int hide_mode) String rules, String joinkey, int hide_mode)
throws DataException, AccessError throws DataException, AccessError
{ {
if (!canCreateCommunity()) env.testPermission(EnvUser.PERM_CREATECOMMUNITY,"You are not authorized to create new communities.");
throw new AccessError("You are not authorized to create new communities.");
// Convert the "hide mode" value into the two hide flags. // Convert the "hide mode" value into the two hide flags.
boolean hide_dir = (hide_mode!=CommunityContext.HIDE_NONE); boolean hide_dir = (hide_mode!=CommunityContext.HIDE_NONE);
@ -1003,7 +999,7 @@ class UserContextImpl implements UserContext, UserBackend
public boolean canCreateCommunity() public boolean canCreateCommunity()
{ {
return (level>=env.getEngine().getParamInt(EngineBackend.IP_CREATECOMMUNITYLVL)); return env.testPermission(EnvUser.PERM_CREATECOMMUNITY);
} // end canCreateCommunity } // end canCreateCommunity
@ -1112,20 +1108,13 @@ class UserContextImpl implements UserContext, UserBackend
public boolean hasAdminAccess() public boolean hasAdminAccess()
{ {
return Capability.canAdministerSystem(level); return env.testPermission(EnvUser.PERM_SYSADMINACCESS);
} // end hasAdminAccess } // end hasAdminAccess
public AdminOperations getAdminInterface() throws AccessError public AdminOperations getAdminInterface() throws AccessError
{ {
if (!(Capability.canAdministerSystem(level))) env.testPermission(EnvUser.PERM_SYSADMINACCESS,"You are not permitted to administer the server.");
{ // you don't have access to get this!
logger.error("user does not have access to do system admin stuff");
throw new AccessError("You are not permitted to administer the server.");
} // end if
// create the return object
return new AdminOperationsImpl(env); return new AdminOperationsImpl(env);
} // end getAdminInterface } // end getAdminInterface

View File

@ -72,11 +72,10 @@ class UserProfileImpl implements UserProfile
*-------------------------------------------------------------------------------- *--------------------------------------------------------------------------------
*/ */
UserProfileImpl(EnvUser env, Connection conn, String username, boolean override) UserProfileImpl(EnvUser env, Connection conn, String username) throws DataException, SQLException
throws DataException, SQLException
{ {
if (logger.isDebugEnabled()) if (logger.isDebugEnabled())
logger.debug("load UserProfileImpl by name: " + username + " (" + override + ")"); logger.debug("load UserProfileImpl by name: " + username);
this.env = env; this.env = env;
// first retrieve from the users table // first retrieve from the users table
@ -101,15 +100,14 @@ class UserProfileImpl implements UserProfile
descr = rs.getString(6); descr = rs.getString(6);
is_anon = rs.getBoolean(7); is_anon = rs.getBoolean(7);
loadContact(conn,contact_id,override); loadContact(conn,contact_id);
} // end constructor } // end constructor
UserProfileImpl(EnvUser env, Connection conn, int uid, boolean override) UserProfileImpl(EnvUser env, Connection conn, int uid) throws DataException, SQLException
throws DataException, SQLException
{ {
if (logger.isDebugEnabled()) if (logger.isDebugEnabled())
logger.debug("load UserProfileImpl by UID: " + uid + " (" + override + ")"); logger.debug("load UserProfileImpl by UID: " + uid);
this.env = env; this.env = env;
// first retrieve from the users table // first retrieve from the users table
@ -134,7 +132,7 @@ class UserProfileImpl implements UserProfile
descr = rs.getString(6); descr = rs.getString(6);
is_anon = rs.getBoolean(7); is_anon = rs.getBoolean(7);
loadContact(conn,contact_id,override); loadContact(conn,contact_id);
} // end constructor } // end constructor
@ -143,10 +141,11 @@ class UserProfileImpl implements UserProfile
*-------------------------------------------------------------------------------- *--------------------------------------------------------------------------------
*/ */
private void loadContact(Connection conn, int contact_id, boolean override) throws SQLException private void loadContact(Connection conn, int contact_id) throws SQLException
{ {
if (logger.isDebugEnabled()) if (logger.isDebugEnabled())
logger.debug("loadContact for contact ID " + contact_id + " (" + override + ")"); logger.debug("loadContact for contact ID " + contact_id);
boolean override = env.testPermission(EnvUser.PERM_SEEHIDDENCONTACTINFO);
Statement stmt = conn.createStatement(); Statement stmt = conn.createStatement();
StringBuffer sql = new StringBuffer("SELECT * FROM contacts WHERE contactid = "); StringBuffer sql = new StringBuffer("SELECT * FROM contacts WHERE contactid = ");

View File

@ -30,10 +30,7 @@ import com.silverwrist.venice.db.*;
import com.silverwrist.venice.htmlcheck.*; import com.silverwrist.venice.htmlcheck.*;
import com.silverwrist.venice.htmlcheck.dict.*; import com.silverwrist.venice.htmlcheck.dict.*;
import com.silverwrist.venice.htmlcheck.filters.*; import com.silverwrist.venice.htmlcheck.filters.*;
import com.silverwrist.venice.security.AuditRecord; import com.silverwrist.venice.security.*;
import com.silverwrist.venice.security.PasswordGenerator;
import com.silverwrist.venice.security.PasswordHash;
import com.silverwrist.venice.security.DefaultLevels;
public class VeniceEngineImpl implements VeniceEngine, EngineBackend public class VeniceEngineImpl implements VeniceEngine, EngineBackend
{ {
@ -411,6 +408,8 @@ public class VeniceEngineImpl implements VeniceEngine, EngineBackend
private HashSet no_compress_types = new HashSet(); // the file types that can't be compressed private HashSet no_compress_types = new HashSet(); // the file types that can't be compressed
private HashMap password_changes = new HashMap(); // current password change requests private HashMap password_changes = new HashMap(); // current password change requests
private OptionSet global_flags = new OptionSet(); // global option flags private OptionSet global_flags = new OptionSet(); // global option flags
private SecurityMonitor global_security; // the global security monitor
private SecurityMonitor community_security; // the community security monitor
/*-------------------------------------------------------------------------------- /*--------------------------------------------------------------------------------
* Constructor * Constructor
@ -711,7 +710,7 @@ public class VeniceEngineImpl implements VeniceEngine, EngineBackend
// store the real master sidebox table as an array // store the real master sidebox table as an array
sideboxes = (MasterSideBox[])(sidebox_tmp.toArray(new MasterSideBox[0])); sideboxes = (MasterSideBox[])(sidebox_tmp.toArray(new MasterSideBox[0]));
if (logger.isDebugEnabled()) if (logger.isDebugEnabled())
logger.debug(sideboxes.length + " sidebox definitions loaded from database"); logger.debug(sideboxes.length + " sidebox definitions loaded from XML");
// Get the <database/> section. // Get the <database/> section.
Element db_sect = root_h.getSubElement("database"); Element db_sect = root_h.getSubElement("database");
@ -734,6 +733,30 @@ public class VeniceEngineImpl implements VeniceEngine, EngineBackend
} // end catch } // end catch
Element security_sect = root_h.getSubElement("security");
if (security_sect==null)
{ // no "security" section...bad!
logger.fatal("config document has no <security/> section");
throw new ConfigException("no <security/> section found in config file",root);
} // end if
NodeList sec_nodes = security_sect.getChildNodes();
for (i=0; i<sec_nodes.getLength(); i++)
{ // scan through and find security monitors to initialize
Node n = sec_nodes.item(i);
if ((n.getNodeType()==Node.ELEMENT_NODE) && (n.getNodeName().equals("security-definition")))
{ // initial security definition
SecurityMonitor sm = new StaticSecurityMonitor((Element)n);
if (sm.getID().equals("Global"))
global_security = sm;
else if (sm.getID().equals("Community"))
community_security = sm;
} // end if
} // end for
Element email_sect = root_h.getSubElement("email"); Element email_sect = root_h.getSubElement("email");
if (email_sect==null) if (email_sect==null)
{ // unable to find the database section { // unable to find the database section
@ -1218,6 +1241,7 @@ public class VeniceEngineImpl implements VeniceEngine, EngineBackend
Connection conn = null; Connection conn = null;
AuditRecord ar = null; AuditRecord ar = null;
String encode_username = SQLUtil.encodeString(username); String encode_username = SQLUtil.encodeString(username);
Role new_role = global_security.getDefaultRole("Global.NewUser");
// email confirmation # is between 1000000 and 9999999 // email confirmation # is between 1000000 and 9999999
int confirm_num = getNewConfirmationNumber(); int confirm_num = getNewConfirmationNumber();
int new_uid; int new_uid;
@ -1247,7 +1271,7 @@ public class VeniceEngineImpl implements VeniceEngine, EngineBackend
StringBuffer sql = new StringBuffer("INSERT INTO users (username, passhash, email_confnum, " StringBuffer sql = new StringBuffer("INSERT INTO users (username, passhash, email_confnum, "
+ "base_lvl, created, lastaccess, passreminder) VALUES ('"); + "base_lvl, created, lastaccess, passreminder) VALUES ('");
sql.append(encode_username).append("', '").append(phash.toString()).append("', "); sql.append(encode_username).append("', '").append(phash.toString()).append("', ");
sql.append(confirm_num).append(", ").append(DefaultLevels.newUser()).append(", '"); sql.append(confirm_num).append(", ").append(new_role.getLevel()).append(", '");
created = new java.util.Date(); created = new java.util.Date();
sql.append(SQLUtil.encodeDate(created)).append("', '").append(SQLUtil.encodeDate(created)); sql.append(SQLUtil.encodeDate(created)).append("', '").append(SQLUtil.encodeDate(created));
sql.append("', ").append(SQLUtil.encodeStringArg(reminder)).append(");"); sql.append("', ").append(SQLUtil.encodeStringArg(reminder)).append(");");
@ -1387,7 +1411,7 @@ public class VeniceEngineImpl implements VeniceEngine, EngineBackend
// create a new context for the user (they're now effectively logged in) // create a new context for the user (they're now effectively logged in)
UserContextImpl rc = new UserContextImpl(env); UserContextImpl rc = new UserContextImpl(env);
rc.loadNewUser(remote_addr,new_uid,DefaultLevels.newUser(),username,confirm_num,created,created); rc.loadNewUser(remote_addr,new_uid,new_role.getLevel(),username,confirm_num,created,created);
rc.autoJoinCommunities(); // EJB 4/14/2001 rc.autoJoinCommunities(); // EJB 4/14/2001
if (logger.isDebugEnabled()) if (logger.isDebugEnabled())
logger.debug("...created new user context"); logger.debug("...created new user context");
@ -1819,11 +1843,23 @@ public class VeniceEngineImpl implements VeniceEngine, EngineBackend
} // end getCommunityLogoSize } // end getCommunityLogoSize
public SecurityInfo getSecurityInfo()
{
return new SecurityInfoWrapper(global_security);
} // end getSecurityInfo
/*-------------------------------------------------------------------------------- /*--------------------------------------------------------------------------------
* Implementations from interface EngineBackend * Implementations from interface EngineBackend
*-------------------------------------------------------------------------------- *--------------------------------------------------------------------------------
*/ */
public VeniceEngine getSelf()
{
return this;
} // end getSelf
public Emailer createEmailer() public Emailer createEmailer()
{ {
checkInitialized(); checkInitialized();
@ -2078,6 +2114,14 @@ public class VeniceEngineImpl implements VeniceEngine, EngineBackend
} // end getParamBoolean } // end getParamBoolean
public Role getParamRole(int selector)
{
if (selector==ROLEP_CREATECOMMUNITY)
return global_security.getRoleForLevel(gp_ints[IP_CREATECOMMUNITYLVL]);
return null;
} // end getParamRole
public void forceParamReload() throws DataException public void forceParamReload() throws DataException
{ {
Connection conn = null; // data pooled connection Connection conn = null; // data pooled connection
@ -2217,6 +2261,16 @@ public class VeniceEngineImpl implements VeniceEngine, EngineBackend
} // end setProperties } // end setProperties
public SecurityMonitor env_getSecurityMonitor(int selector)
{
if (selector==SM_GLOBAL)
return global_security;
if (selector==SM_COMMUNITY)
return community_security;
return null;
} // end env_getSecurityMonitor
/*-------------------------------------------------------------------------------- /*--------------------------------------------------------------------------------
* Static initializer * Static initializer
*-------------------------------------------------------------------------------- *--------------------------------------------------------------------------------

View File

@ -42,4 +42,6 @@ public interface CommunityBackend
public abstract CommunityDataBackend getDataBackend() throws DataException; public abstract CommunityDataBackend getDataBackend() throws DataException;
public abstract boolean env_testPermission(String symbol);
} // end interface CommunityBackend } // end interface CommunityBackend

View File

@ -20,11 +20,14 @@ package com.silverwrist.venice.core.internals;
import java.util.BitSet; import java.util.BitSet;
import java.util.List; import java.util.List;
import com.silverwrist.venice.security.AuditRecord; import com.silverwrist.venice.security.AuditRecord;
import com.silverwrist.venice.security.Role;
import com.silverwrist.venice.security.SecurityMonitor;
import com.silverwrist.venice.htmlcheck.HTMLChecker; import com.silverwrist.venice.htmlcheck.HTMLChecker;
import com.silverwrist.venice.core.DataException; import com.silverwrist.venice.core.DataException;
import com.silverwrist.venice.core.GlobalProperties; import com.silverwrist.venice.core.GlobalProperties;
import com.silverwrist.venice.core.SideBoxDescriptor; import com.silverwrist.venice.core.SideBoxDescriptor;
import com.silverwrist.venice.core.TopicMessageContext; import com.silverwrist.venice.core.TopicMessageContext;
import com.silverwrist.venice.core.VeniceEngine;
public interface EngineBackend public interface EngineBackend
{ {
@ -48,6 +51,15 @@ public interface EngineBackend
// Boolean parameter indexes // Boolean parameter indexes
public static final int BP_POSTPICTURES = 0; public static final int BP_POSTPICTURES = 0;
// role parameter indexes
public static final int ROLEP_CREATECOMMUNITY = 0;
// Selectors for security monitors
public static final int SM_GLOBAL = 0;
public static final int SM_COMMUNITY = 1;
public abstract VeniceEngine getSelf();
public abstract Emailer createEmailer(); public abstract Emailer createEmailer();
public abstract String getStockMessage(String key); public abstract String getStockMessage(String key);
@ -88,6 +100,8 @@ public interface EngineBackend
public abstract boolean getParamBoolean(int selector); public abstract boolean getParamBoolean(int selector);
public abstract Role getParamRole(int selector);
public abstract void forceParamReload() throws DataException; public abstract void forceParamReload() throws DataException;
public abstract SideBoxDescriptor getMasterSideBoxDescriptor(int id); public abstract SideBoxDescriptor getMasterSideBoxDescriptor(int id);
@ -108,4 +122,6 @@ public interface EngineBackend
public abstract void setProperties(GlobalProperties props) throws DataException; public abstract void setProperties(GlobalProperties props) throws DataException;
public abstract SecurityMonitor env_getSecurityMonitor(int selector);
} // end interface EngineBackend } // end interface EngineBackend

View File

@ -17,10 +17,28 @@
*/ */
package com.silverwrist.venice.core.internals; package com.silverwrist.venice.core.internals;
import com.silverwrist.venice.core.AccessError;
import com.silverwrist.venice.security.AuditRecord; import com.silverwrist.venice.security.AuditRecord;
import com.silverwrist.venice.security.Role;
import com.silverwrist.venice.security.SecurityMonitor;
public class EnvCommunity extends EnvUser public class EnvCommunity extends EnvUser
{ {
/*--------------------------------------------------------------------------------
* Static data members
*--------------------------------------------------------------------------------
*/
public static final String PERM_SHOWADMIN = "Community.ShowAdmin";
public static final String PERM_NOKEYREQUIRED = "Community.NoKeyRequired";
public static final String PERM_SHOWHIDDENMEMBERS = "Community.ShowHiddenMembers";
public static final String PERM_SHOWHIDDENOBJECTS = "Community.ShowHiddenObjects";
public static final String PERM_READ = "Community.Read";
public static final String PERM_WRITE = "Community.Write";
public static final String PERM_CREATE = "Community.Create";
public static final String PERM_DELETE = "Community.Delete";
public static final String PERM_JOIN = "Community.Join";
/*-------------------------------------------------------------------------------- /*--------------------------------------------------------------------------------
* Attributes * Attributes
*-------------------------------------------------------------------------------- *--------------------------------------------------------------------------------
@ -47,6 +65,17 @@ public class EnvCommunity extends EnvUser
} // end constructor } // end constructor
/*--------------------------------------------------------------------------------
* Overrides from class EnvEngine
*--------------------------------------------------------------------------------
*/
protected SecurityMonitor getStaticMonitor()
{
return getEngine().env_getSecurityMonitor(EngineBackend.SM_COMMUNITY);
} // end getStaticMonitor
/*-------------------------------------------------------------------------------- /*--------------------------------------------------------------------------------
* Overrides from class EnvUser * Overrides from class EnvUser
*-------------------------------------------------------------------------------- *--------------------------------------------------------------------------------
@ -85,6 +114,38 @@ public class EnvCommunity extends EnvUser
} // end newAudit } // end newAudit
public boolean testPermission(String symbol, String errormsg) throws AccessError
{
SecurityMonitor sm = getStaticMonitor();
if ( symbol.equals(PERM_READ) || symbol.equals(PERM_WRITE) || symbol.equals(PERM_CREATE)
|| symbol.equals(PERM_DELETE) || symbol.equals(PERM_JOIN))
{ // fall back to the backend object to test this
if (comm.env_testPermission(symbol))
return true;
if (errormsg==null)
errormsg = "Permission denied.";
throw new AccessError(errormsg);
} // end if
if (sm.testPermission(symbol,comm.realCommunityLevel(),errormsg))
return true;
return super.testPermission(symbol,errormsg);
} // end testPermission
public boolean testPermission(String symbol)
{
SecurityMonitor sm = getStaticMonitor();
if ( symbol.equals(PERM_READ) || symbol.equals(PERM_WRITE) || symbol.equals(PERM_CREATE)
|| symbol.equals(PERM_DELETE) || symbol.equals(PERM_JOIN))
return comm.env_testPermission(symbol);
if (sm.testPermission(symbol,comm.realCommunityLevel()))
return true;
return super.testPermission(symbol);
} // end testPermission
/*-------------------------------------------------------------------------------- /*--------------------------------------------------------------------------------
* External operations * External operations
*-------------------------------------------------------------------------------- *--------------------------------------------------------------------------------
@ -102,4 +163,10 @@ public class EnvCommunity extends EnvUser
} // end getCommunityID() } // end getCommunityID()
public final boolean isLevelAdmin(int level)
{
return getStaticMonitor().testPermission(PERM_SHOWADMIN,level);
} // end isLevelAdmin
} // end class EnvCommunity } // end class EnvCommunity

View File

@ -17,8 +17,18 @@
*/ */
package com.silverwrist.venice.core.internals; package com.silverwrist.venice.core.internals;
import com.silverwrist.venice.core.AccessError;
import com.silverwrist.venice.security.SecurityMonitor;
public class EnvCommunityData extends EnvEngine public class EnvCommunityData extends EnvEngine
{ {
/*--------------------------------------------------------------------------------
* Static data members
*--------------------------------------------------------------------------------
*/
public static final String PERM_NOJOINREQUIRED = "Community.NoJoinRequired";
/*-------------------------------------------------------------------------------- /*--------------------------------------------------------------------------------
* Attributes * Attributes
*-------------------------------------------------------------------------------- *--------------------------------------------------------------------------------
@ -45,6 +55,17 @@ public class EnvCommunityData extends EnvEngine
} // end EnvCommunityData } // end EnvCommunityData
/*--------------------------------------------------------------------------------
* Overrides from class EnvEngine
*--------------------------------------------------------------------------------
*/
protected SecurityMonitor getStaticMonitor()
{
return getEngine().env_getSecurityMonitor(EngineBackend.SM_COMMUNITY);
} // end getStaticMonitor
/*-------------------------------------------------------------------------------- /*--------------------------------------------------------------------------------
* External operations * External operations
*-------------------------------------------------------------------------------- *--------------------------------------------------------------------------------
@ -62,4 +83,16 @@ public class EnvCommunityData extends EnvEngine
} // end getCommunityID } // end getCommunityID
public final boolean testPermission(String symbol, int level, String errormsg) throws AccessError
{
return getStaticMonitor().testPermission(symbol,level,errormsg);
} // end testPermission
public final boolean testPermission(String symbol, int level)
{
return getStaticMonitor().testPermission(symbol,level);
} // end testPermission
} // end class EnvCommunityData } // end class EnvCommunityData

View File

@ -19,7 +19,11 @@ package com.silverwrist.venice.core.internals;
import java.sql.Connection; import java.sql.Connection;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.List;
import com.silverwrist.venice.core.AccessError;
import com.silverwrist.venice.core.SecurityInfo;
import com.silverwrist.venice.db.*; import com.silverwrist.venice.db.*;
import com.silverwrist.venice.security.*;
public class EnvEngine public class EnvEngine
{ {
@ -50,6 +54,17 @@ public class EnvEngine
} // end constructor } // end constructor
/*--------------------------------------------------------------------------------
* Internal operations
*--------------------------------------------------------------------------------
*/
protected SecurityMonitor getStaticMonitor()
{
return engine.env_getSecurityMonitor(EngineBackend.SM_GLOBAL);
} // end getStaticMonitor
/*-------------------------------------------------------------------------------- /*--------------------------------------------------------------------------------
* External operations * External operations
*-------------------------------------------------------------------------------- *--------------------------------------------------------------------------------
@ -80,4 +95,40 @@ public class EnvEngine
} // end releaseConnection } // end releaseConnection
public final boolean permissionDefined(String symbol, boolean no_follow)
{
return getStaticMonitor().permissionDefined(symbol,no_follow);
} // end permissionDefined
public final List getRoleList(String symbol)
{
return getStaticMonitor().getRoleList(symbol);
} // end getRoleList
public final Role getRole(String symbol)
{
return getStaticMonitor().getRole(symbol);
} // end getRole
public final Role getRoleForLevel(int level)
{
return getStaticMonitor().getRoleForLevel(level);
} // end getRoleForLevel
public final Role getDefaultRole(String symbol)
{
return getStaticMonitor().getDefaultRole(symbol);
} // end getDefaultRole
public final SecurityInfo getSecurityInfo()
{
return new SecurityInfoWrapper(getStaticMonitor());
} // end getSecurityInfo
} // end class EnvEngine } // end class EnvEngine

View File

@ -17,10 +17,31 @@
*/ */
package com.silverwrist.venice.core.internals; package com.silverwrist.venice.core.internals;
import org.apache.log4j.*;
import com.silverwrist.venice.core.AccessError;
import com.silverwrist.venice.security.AuditRecord; import com.silverwrist.venice.security.AuditRecord;
import com.silverwrist.venice.security.Role;
public class EnvUser extends EnvEngine public class EnvUser extends EnvEngine
{ {
/*--------------------------------------------------------------------------------
* Static data members
*--------------------------------------------------------------------------------
*/
private static Category logger = Category.getInstance(EnvUser.class);
public static final String PERM_SHOWHIDDENCATS = "Global.ShowHiddenCategories";
public static final String PERM_NOEMAILVERIFY = "Global.NoEmailVerify";
public static final String PERM_SEEHIDDENCONTACTINFO = "Global.SeeHiddenContactInfo";
public static final String PERM_SEARCHHIDDENCOMMUNITIES = "Global.SearchHiddenCommunities";
public static final String PERM_SHOWHIDDENCOMMUNITIES = "Global.ShowHiddenCommunities";
public static final String PERM_SEARCHHIDDENCATS = "Global.SearchHiddenCategories";
public static final String PERM_SYSADMINACCESS = "Global.SysAdminAccess";
public static final String PERM_PUBLISH_FP = "Global.PublishFP";
public static final String PERM_DESIGNATEPFY = "Global.DesignatePFY";
public static final String PERM_CREATECOMMUNITY = "Global.CreateCommunity";
/*-------------------------------------------------------------------------------- /*--------------------------------------------------------------------------------
* Attributes * Attributes
*-------------------------------------------------------------------------------- *--------------------------------------------------------------------------------
@ -52,18 +73,6 @@ public class EnvUser extends EnvEngine
*-------------------------------------------------------------------------------- *--------------------------------------------------------------------------------
*/ */
public final UserBackend getUser()
{
return user;
} // end getUser
public final int getUserID()
{
return user.realUID();
} // end getUserID
public AuditRecord newAudit(int type, String data1, String data2, String data3, String data4) public AuditRecord newAudit(int type, String data1, String data2, String data3, String data4)
{ {
return new AuditRecord(type,getUserID(),user.userRemoteAddress(),data1,data2,data3,data4); return new AuditRecord(type,getUserID(),user.userRemoteAddress(),data1,data2,data3,data4);
@ -94,4 +103,59 @@ public class EnvUser extends EnvEngine
} // end newAudit } // end newAudit
public boolean testPermission(String symbol, String errormsg) throws AccessError
{
if (symbol.equals(PERM_CREATECOMMUNITY))
{ // the Create Community permission test
Role r = getEngine().getParamRole(EngineBackend.ROLEP_CREATECOMMUNITY);
if (r.isSatisfiedBy(user.realBaseLevel()))
return true;
logger.error("testPermission() fail for permission " + PERM_CREATECOMMUNITY);
if (errormsg==null)
errormsg = "You are not authorized to create new communities.";
throw new AccessError(errormsg);
} // end if
return getStaticMonitor().testPermission(symbol,user.realBaseLevel(),errormsg);
} // end testPermission
public boolean testPermission(String symbol)
{
if (symbol.equals(PERM_CREATECOMMUNITY))
{ // do the "Create Community" test here
Role r = getEngine().getParamRole(EngineBackend.ROLEP_CREATECOMMUNITY);
return r.isSatisfiedBy(user.realBaseLevel());
} // end if
return getStaticMonitor().testPermission(symbol,user.realBaseLevel());
} // end testPermission
public final UserBackend getUser()
{
return user;
} // end getUser
public final int getUserID()
{
return user.realUID();
} // end getUserID
public final int getUserBaseLevel()
{
return user.realBaseLevel();
} // end getUserBaseLevel
public final Role getCommunityDefaultRole(String symbol)
{
return getEngine().env_getSecurityMonitor(EngineBackend.SM_COMMUNITY).getDefaultRole(symbol);
} // end getCommunityDefaultRole
} // end class EnvUser } // end class EnvUser

View File

@ -0,0 +1,80 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Communities System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.core.internals;
import java.util.List;
import com.silverwrist.venice.core.SecurityInfo;
import com.silverwrist.venice.security.Role;
import com.silverwrist.venice.security.SecurityMonitor;
public class SecurityInfoWrapper implements SecurityInfo
{
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private SecurityMonitor sm; // we call through to this
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
public SecurityInfoWrapper(SecurityMonitor sm)
{
this.sm = sm;
} // end constructor
/*--------------------------------------------------------------------------------
* Implementations from interface SecurityInfo
*--------------------------------------------------------------------------------
*/
public List getRoleList(String symbol)
{
return sm.getRoleList(symbol);
} // end getRoleList
public Role getRole(String symbol)
{
return sm.getRole(symbol);
} // end getRole
public Role getRoleForLevel(int level)
{
return sm.getRoleForLevel(level);
} // end getRoleForLevel
public Role getDefaultRole(String symbol)
{
return sm.getDefaultRole(symbol);
} // end getDefaultRole
public String getID()
{
return sm.getID();
} // end getID
} // end class SecurityInfoWrapper

View File

@ -1,106 +0,0 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Communities System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.security;
public class Capability implements SecLevels
{
public static boolean canDesignatePFYs(int level)
{
return (level>=GLOBAL_BOFH);
} // end canDesignatePFYs
public static boolean isCommunityAdmin(int level)
{
return (level>=COMM_ANYADMIN);
} // end isCommunityAdmin
public static boolean hideHiddenCategories(int level)
{
return (level<GLOBAL_ANYADMIN);
} // end hideHiddenCategories
public static boolean exemptFromEmailVerification(int level)
{
return (level>=GLOBAL_ANYADMIN);
} // end exemptFromEmailVerification
public static boolean canSeeHiddenContactFields(int level)
{
return (level>=GLOBAL_ANYADMIN);
} // end canSeeHiddenContactFields
public static boolean exemptFromMembershipRequirement(int level)
{
return (level>=GLOBAL_ANYADMIN);
} // end exemptFromMembershipRequirement
public static boolean hideHiddenSearchCommunities(int level)
{
return (level<GLOBAL_ANYADMIN);
} // end hideHiddenSearchCommunities
public static boolean hideHiddenDirectoryCommunities(int level)
{
return (level<GLOBAL_ANYADMIN);
} // end hideHiddenSearchCommunities
public static boolean canJoinPrivateCommunityWithoutKey(int level)
{
return (level>=GLOBAL_ANYADMIN);
} // end canJoinPrivateCommunityWithoutKey
public static boolean showHiddenSearchCategories(int level)
{
return (level>=GLOBAL_ANYADMIN);
} // end showHioddenSearchCategories
public static boolean showHiddenCommunityMembers(int level)
{
return (level>=COMM_ANYADMIN);
} // end showHiddenCommunityMembers
public static boolean hideHiddenConferences(int level)
{
return (level<COMM_ANYADMIN);
} // end hideHiddenConferences
public static boolean canAdministerSystem(int level)
{
return (level>=GLOBAL_ANYADMIN);
} // end canAdministerSystem
public static boolean canPublishToFrontPage(int level)
{
return (level>=GLOBAL_ANYADMIN);
} // end canPublishToFrontPage
} // end class Capability

View File

@ -19,72 +19,6 @@ package com.silverwrist.venice.security;
public class DefaultLevels implements SecLevels public class DefaultLevels implements SecLevels
{ {
public static int newUser()
{
return GLOBAL_UNVERIFIED;
} // end newUser
public static int memberCommunity()
{
return COMM_MEMBER;
} // end memberCommunity
public static int PFY()
{
return GLOBAL_PFY;
} // end PFY
public static int afterEmailVerification()
{
return GLOBAL_NORMAL;
} // end afterEmailVerification
public static int afterEmailAddressChange()
{
return GLOBAL_UNVERIFIED;
} // end afterEmailAddressChange
public static int newCommunityRead()
{
return COMM_MEMBER;
} // end newCommunityRead
public static int newCommunityWrite()
{
return COMM_COHOST;
} // end newCommunityWrite
public static int newCommunityCreate()
{
return COMM_COHOST;
} // end newCommunityCreate
public static int newCommunityDelete()
{
return COMM_HOST;
} // end newCommunityDelete
public static int newCommunityJoin()
{
return GLOBAL_NORMAL;
} // end newCommunityJoin
public static int creatorCommunity()
{
return COMM_HOST;
} // end creatorCommunity
public static int hostPrivsConference() public static int hostPrivsConference()
{ {
return CONFERENCE_ANYADMIN; return CONFERENCE_ANYADMIN;

View File

@ -0,0 +1,187 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Communities System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.security;
import java.io.IOException;
import java.util.*;
import org.apache.log4j.*;
import com.silverwrist.venice.core.AccessError;
public class PrimordialSecurityMonitor implements SecurityMonitor
{
/*--------------------------------------------------------------------------------
* Static data members
*--------------------------------------------------------------------------------
*/
private static PrimordialSecurityMonitor self = null;
private static Category logger = Category.getInstance(PrimordialSecurityMonitor.class);
public static final String SYM_NOT_IN_LIST = "NotInList";
public static final String SYM_NO_ACCESS = "NoAccess";
public static final String SYM_UNRESTRICTED = "UnrestrictedUser";
private static final String NAME_NOT_IN_LIST = "(not in list)";
private static final String NAME_NO_ACCESS = "No Access";
private static final String NAME_UNRESTRICTED = "'Unrestricted' User";
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private Role not_in_list; // the "not in list" role
private Role no_access; // the "no access" role
private Role unrestricted_user; // the "unrestricted user" role
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
private PrimordialSecurityMonitor()
{
String name_not_in_list = null, name_no_access = null, name_unrestricted_user = null;
try
{ // load the three initial role names
Properties init_props = new Properties();
init_props.load(getClass().getResourceAsStream("sm.properties"));
name_not_in_list = init_props.getProperty("role.NotInList.name",NAME_NOT_IN_LIST);
name_no_access = init_props.getProperty("role.NoAccess.name",NAME_NO_ACCESS);
name_unrestricted_user = init_props.getProperty("role.UnrestrictedUser.name",NAME_UNRESTRICTED);
} // end try
catch (IOException e)
{ // on error, revert to the internal names
logger.warn("Error loading default names",e);
name_not_in_list = NAME_NOT_IN_LIST;
name_no_access = NAME_NO_ACCESS;
name_unrestricted_user = NAME_UNRESTRICTED;
} // end catch
// Create the actual roles.
this.not_in_list = Role.create(ScopeInfo.L_NOT_THERE,name_not_in_list,SYM_NOT_IN_LIST);
this.no_access = Role.create(ScopeInfo.L_NO_ACCESS,name_no_access,SYM_NO_ACCESS);
this.unrestricted_user = Role.create(ScopeInfo.L_UNRESTRICTED,name_unrestricted_user,SYM_UNRESTRICTED);
} // end constructor
/*--------------------------------------------------------------------------------
* Implementations from interface SecurityMonitor
*--------------------------------------------------------------------------------
*/
public boolean testPermission(String symbol, int level, String errormsg) throws AccessError
{
if (symbol==null)
throw new NullPointerException("testPermission() got null symbol");
logger.error("testPermission: symbol \"" + symbol + "\" is not a defined permission test");
throw new AccessError("Undefined internal permission test \"" + symbol + "\"");
} // end testPermission
public boolean testPermission(String symbol, int level)
{
if (symbol==null)
throw new NullPointerException("testPermission() got null symbol");
logger.error("testPermission: symbol \"" + symbol + "\" is not a defined permission test");
return false;
} // end testPermission
public boolean permissionDefined(String symbol, boolean no_follow)
{
if (symbol==null)
throw new NullPointerException("permissionDefined() got null symbol");
return false; // primordial monitor defines no permissions
} // end permissionDefined
public List getRoleList(String symbol)
{
if (symbol==null)
throw new NullPointerException("getRoleList() got null symbol");
logger.error("getRoleList: symbol \"" + symbol + "\" is not a defined role list");
return null;
} // end getRoleList
public Role getRole(String symbol)
{
if (symbol==null)
throw new NullPointerException("getRole() got null symbol");
if (symbol.equals(SYM_NOT_IN_LIST))
return not_in_list;
if (symbol.equals(SYM_NO_ACCESS))
return no_access;
if (symbol.equals(SYM_UNRESTRICTED))
return unrestricted_user;
logger.error("getRole: symbol \"" + symbol + "\" is not a defined role");
return null;
} // end getRole
public Role getRoleForLevel(int level)
{
if (level==ScopeInfo.L_NOT_THERE)
return not_in_list;
if (level==ScopeInfo.L_NO_ACCESS)
return no_access;
if (level==ScopeInfo.L_UNRESTRICTED)
return unrestricted_user;
logger.error("getRoleForLevel: no role for level " + level);
return null;
} // end getRoleForLevel
public Role getDefaultRole(String symbol)
{
logger.error("getDefaultRole: symbol \"" + symbol + "\" has no default role");
return null;
} // end getDefaultRole
public ScopeInfo getScopeInfo()
{
return null; // this security monitor HAS no scope
} // end getScopeInfo
public String getID()
{
return null; // this security monitor HAS no ID
} // end getID
/*--------------------------------------------------------------------------------
* External static operations
*--------------------------------------------------------------------------------
*/
public static synchronized SecurityMonitor get()
{
if (self==null)
self = new PrimordialSecurityMonitor();
return self;
} // end get
} // end class PrimordialSecurityMonitor

View File

@ -19,7 +19,7 @@ package com.silverwrist.venice.security;
import java.util.*; import java.util.*;
public class Role implements Comparable, SecLevels public final class Role implements Comparable, Cloneable, SecLevels
{ {
/*-------------------------------------------------------------------------------- /*--------------------------------------------------------------------------------
* Static data members * Static data members
@ -37,22 +37,12 @@ public class Role implements Comparable, SecLevels
private static ArrayList comm_high; private static ArrayList comm_high;
private static ArrayList conf_low; private static ArrayList conf_low;
private static ArrayList conf_high; private static ArrayList conf_high;
private static HashMap all_roles;
private static List base_levels = null;
private static List base_levels_2 = null;
private static List commreadlist_rc = null;
private static List commwritelist_rc = null;
private static List commcreatelist_rc = null;
private static List commdeletelist_rc = null;
private static List commjoinlist_rc = null;
private static List comm_member_levels = null;
private static List confreadlist_rc = null; private static List confreadlist_rc = null;
private static List confpostlist_rc = null; private static List confpostlist_rc = null;
private static List confhidelist_rc = null; private static List confhidelist_rc = null;
private static List confdeletelist_rc = null; private static List confdeletelist_rc = null;
private static List conf_member_levels = null; private static List conf_member_levels = null;
private static List new_comm_list_rc = null;
/*-------------------------------------------------------------------------------- /*--------------------------------------------------------------------------------
* Attributes * Attributes
@ -61,9 +51,10 @@ public class Role implements Comparable, SecLevels
private int level; private int level;
private String name; private String name;
private String symbol;
/*-------------------------------------------------------------------------------- /*--------------------------------------------------------------------------------
* Constructor * Constructors
*-------------------------------------------------------------------------------- *--------------------------------------------------------------------------------
*/ */
@ -71,34 +62,23 @@ public class Role implements Comparable, SecLevels
{ {
this.level = level; this.level = level;
this.name = name; this.name = name;
this.symbol = null;
} // end constructor
protected Role(int level, String name, String symbol)
{
this.level = level;
this.name = name;
this.symbol = symbol;
} // end constructor } // end constructor
/*-------------------------------------------------------------------------------- /*--------------------------------------------------------------------------------
* External operations * Overrides from class Object
*-------------------------------------------------------------------------------- *--------------------------------------------------------------------------------
*/ */
public int getLevel()
{
return level;
} // end getLevel
public String getName()
{
return name;
} // end getName
public String toString()
{
StringBuffer buf = new StringBuffer(name);
buf.append('[').append(level).append(']');
return buf.toString();
} // end toString
public boolean equals(Object obj) public boolean equals(Object obj)
{ {
if (obj==null) if (obj==null)
@ -108,7 +88,7 @@ public class Role implements Comparable, SecLevels
if (obj instanceof Role) if (obj instanceof Role)
{ // compare levels { // compare levels
Role other = (Role)obj; Role other = (Role)obj;
return (level==other.getLevel()); return (level==other.level);
} // end if } // end if
@ -122,174 +102,77 @@ public class Role implements Comparable, SecLevels
} // end hashCode } // end hashCode
public String toString()
{
StringBuffer buf = new StringBuffer(name);
buf.append('[').append(level).append(']');
if (symbol!=null)
buf.append('{').append(symbol).append('}');
return buf.toString();
} // end toString
/*--------------------------------------------------------------------------------
* Implementations from interface Comparable
*--------------------------------------------------------------------------------
*/
public int compareTo(Object obj) public int compareTo(Object obj)
{ {
if (obj==null)
throw new NullPointerException("comparing a NULL object");
if (!(obj instanceof Role)) if (!(obj instanceof Role))
throw new ClassCastException("comparing non-Role to Role"); throw new ClassCastException("comparing non-Role to Role");
Role other = (Role)obj; Role other = (Role)obj;
return level - other.getLevel(); return level - other.level;
} // end compareTo } // end compareTo
/*--------------------------------------------------------------------------------
* External operations
*--------------------------------------------------------------------------------
*/
public final int getLevel()
{
return level;
} // end getLevel
public final String getName()
{
return name;
} // end getName
public final String getSymbol()
{
return symbol;
} // end getSymbol
public final boolean isSatisfiedBy(int l)
{
return (l>=level);
} // end isSatisfiedBy
/*--------------------------------------------------------------------------------
* External static operations
*--------------------------------------------------------------------------------
*/
public static final Role create(int level, String name, String symbol)
{
return new Role(level,name,symbol);
} // end create
/*-------------------------------------------------------------------------------- /*--------------------------------------------------------------------------------
* External static operations which generate lists of roles * External static operations which generate lists of roles
*-------------------------------------------------------------------------------- *--------------------------------------------------------------------------------
*/ */
public static Role getRoleForLevel(int level)
{
Role rc = (Role)(all_roles.get(new Integer(level)));
if (rc!=null)
return rc;
return new Role(level,"(Level " + level + ")");
} // end getRoleForLevel
public static List getBaseLevelChoices()
{
if (base_levels==null)
{ // create the returned list
ArrayList rc = new ArrayList();
rc.addAll(global_low);
rc.add(unrestricted_user);
rc.addAll(global_high);
rc.remove(rc.size()-1);
rc.trimToSize();
base_levels = Collections.unmodifiableList(rc);
} // end if
return base_levels;
} // end getBaseLevelChoices
public static List getBaseLevelChoices2()
{
if (base_levels_2==null)
{ // create the returned list
ArrayList rc = new ArrayList();
rc.addAll(global_low);
rc.add(unrestricted_user);
rc.trimToSize();
base_levels_2 = Collections.unmodifiableList(rc);
} // end if
return base_levels_2;
} // end getBaseLevelChoices2
public static Role getGlobalAdmin()
{
return global_admin;
} // end getGlobalAdmin
public static List getCommunityReadList()
{
if (commreadlist_rc==null)
{ // create the returned list
ArrayList rc = new ArrayList();
rc.addAll(global_low);
rc.addAll(comm_low);
rc.add(unrestricted_user);
rc.addAll(comm_high);
rc.add(global_high.get(0));
rc.trimToSize();
commreadlist_rc = Collections.unmodifiableList(rc);
} // end if
return commreadlist_rc;
} // end getCommunityReadList
public static List getCommunityWriteList()
{
if (commwritelist_rc==null)
{ // build the return value
ArrayList rc = new ArrayList();
rc.addAll(comm_high);
rc.addAll(global_high);
rc.trimToSize();
commwritelist_rc = Collections.unmodifiableList(rc);
} // end if
return commwritelist_rc;
} // end getCommunityWriteList
public static List getCommunityCreateList()
{
if (commcreatelist_rc==null)
{ // create the return list
ArrayList rc = new ArrayList();
rc.add(global_low.get(global_low.size()-1));
rc.addAll(comm_low);
rc.add(unrestricted_user);
rc.addAll(comm_high);
rc.add(global_high.get(0));
rc.trimToSize();
commcreatelist_rc = Collections.unmodifiableList(rc);
} // end if
return commcreatelist_rc;
} // end getCommunityCreateList
public static List getCommunityDeleteList()
{
if (commdeletelist_rc==null)
{ // create the return list
ArrayList rc = new ArrayList();
rc.addAll(comm_high);
rc.addAll(global_high);
rc.add(no_access);
rc.trimToSize();
commdeletelist_rc = Collections.unmodifiableList(rc);
} // end if
return commdeletelist_rc;
} // end getCommunityDeleteList
public static List getCommunityJoinList()
{
if (commjoinlist_rc==null)
commjoinlist_rc = Collections.unmodifiableList(global_low);
return commjoinlist_rc;
} // end getCommunityJoinList
public static List getCommunityMemberLevelChoices()
{
if (comm_member_levels==null)
{ // figure out the member levels list
ArrayList rc = new ArrayList();
rc.add(not_in_list);
rc.addAll(global_low);
rc.addAll(comm_low);
rc.add(unrestricted_user);
rc.addAll(comm_high);
rc.remove(rc.size()-1);
rc.trimToSize();
comm_member_levels = Collections.unmodifiableList(rc);
} // end if
return comm_member_levels;
} // end getCommunityMemberLevelChoices
public static Role getCommunityHostRole()
{
return comm_host;
} // end getCommunityHostRole
public static List getConferenceReadList() public static List getConferenceReadList()
{ {
if (confreadlist_rc==null) if (confreadlist_rc==null)
@ -399,23 +282,6 @@ public class Role implements Comparable, SecLevels
} // end getConferenceMemberLevelChoices } // end getConferenceMemberLevelChoices
public static List getNewCommunityLevelChoices()
{
if (new_comm_list_rc==null)
{ // precalculate the list
ArrayList rc = new ArrayList();
rc.add(global_low.get(global_low.size()-1));
rc.add(unrestricted_user);
rc.addAll(global_high);
rc.trimToSize();
new_comm_list_rc = Collections.unmodifiableList(rc);
} // end if
return new_comm_list_rc;
} // end getNewCommunityLevelChoices
/*-------------------------------------------------------------------------------- /*--------------------------------------------------------------------------------
* Static initializer * Static initializer
*-------------------------------------------------------------------------------- *--------------------------------------------------------------------------------
@ -423,13 +289,9 @@ public class Role implements Comparable, SecLevels
static static
{ // begin initializing the "all roles" map { // begin initializing the "all roles" map
all_roles = new HashMap();
not_in_list = new Role(0,"(not in list)"); not_in_list = new Role(0,"(not in list)");
all_roles.put(new Integer(0),not_in_list);
no_access = new Role(NO_ACCESS,"No Access"); no_access = new Role(NO_ACCESS,"No Access");
all_roles.put(new Integer(NO_ACCESS),no_access);
unrestricted_user = new Role(UNRESTRICTED_USER,"'Unrestricted' User"); unrestricted_user = new Role(UNRESTRICTED_USER,"'Unrestricted' User");
all_roles.put(new Integer(UNRESTRICTED_USER),unrestricted_user);
Role tmp; Role tmp;
@ -437,63 +299,50 @@ public class Role implements Comparable, SecLevels
global_low = new ArrayList(3); global_low = new ArrayList(3);
tmp = new Role(GLOBAL_ANONYMOUS,"Anonymous User"); tmp = new Role(GLOBAL_ANONYMOUS,"Anonymous User");
global_low.add(tmp); global_low.add(tmp);
all_roles.put(new Integer(GLOBAL_ANONYMOUS),tmp);
tmp = new Role(GLOBAL_UNVERIFIED,"Unauthenticated User"); tmp = new Role(GLOBAL_UNVERIFIED,"Unauthenticated User");
global_low.add(tmp); global_low.add(tmp);
all_roles.put(new Integer(GLOBAL_UNVERIFIED),tmp);
tmp = new Role(GLOBAL_NORMAL,"Normal User"); tmp = new Role(GLOBAL_NORMAL,"Normal User");
global_low.add(tmp); global_low.add(tmp);
all_roles.put(new Integer(GLOBAL_NORMAL),tmp);
global_low.trimToSize(); global_low.trimToSize();
// initialize the "global highband" vector // initialize the "global highband" vector
global_high = new ArrayList(3); global_high = new ArrayList(3);
tmp = new Role(GLOBAL_ANYADMIN,"Any System Administrator"); tmp = new Role(GLOBAL_ANYADMIN,"Any System Administrator");
global_high.add(tmp); global_high.add(tmp);
all_roles.put(new Integer(GLOBAL_ANYADMIN),tmp);
tmp = new Role(GLOBAL_PFY,"System Assistant Administrator"); tmp = new Role(GLOBAL_PFY,"System Assistant Administrator");
global_high.add(tmp); global_high.add(tmp);
all_roles.put(new Integer(GLOBAL_PFY),tmp);
global_admin = new Role(GLOBAL_BOFH,"Global System Administrator"); global_admin = new Role(GLOBAL_BOFH,"Global System Administrator");
global_high.add(global_admin); global_high.add(global_admin);
all_roles.put(new Integer(GLOBAL_BOFH),global_admin);
global_high.trimToSize(); global_high.trimToSize();
// initialize the "community lowband" vector // initialize the "community lowband" vector
comm_low = new ArrayList(1); comm_low = new ArrayList(1);
tmp = new Role(COMM_MEMBER,"Community Member"); tmp = new Role(COMM_MEMBER,"Community Member");
comm_low.add(tmp); comm_low.add(tmp);
all_roles.put(new Integer(COMM_MEMBER),tmp);
comm_low.trimToSize(); comm_low.trimToSize();
// initialize the "communtiy highband" vector // initialize the "communtiy highband" vector
comm_high = new ArrayList(3); comm_high = new ArrayList(3);
tmp = new Role(COMM_ANYADMIN,"Any Community Administrator"); tmp = new Role(COMM_ANYADMIN,"Any Community Administrator");
comm_high.add(tmp); comm_high.add(tmp);
all_roles.put(new Integer(COMM_ANYADMIN),tmp);
tmp = new Role(COMM_COHOST,"Community Co-Host"); tmp = new Role(COMM_COHOST,"Community Co-Host");
comm_high.add(tmp); comm_high.add(tmp);
all_roles.put(new Integer(COMM_COHOST),tmp);
comm_host = new Role(COMM_HOST,"Community Host"); comm_host = new Role(COMM_HOST,"Community Host");
comm_high.add(comm_host); comm_high.add(comm_host);
all_roles.put(new Integer(COMM_HOST),comm_host);
comm_high.trimToSize(); comm_high.trimToSize();
// initialize the "conference lowband" vector // initialize the "conference lowband" vector
conf_low = new ArrayList(1); conf_low = new ArrayList(1);
tmp = new Role(CONFERENCE_MEMBER,"Conference Member"); tmp = new Role(CONFERENCE_MEMBER,"Conference Member");
conf_low.add(tmp); conf_low.add(tmp);
all_roles.put(new Integer(CONFERENCE_MEMBER),tmp);
conf_low.trimToSize(); conf_low.trimToSize();
// initialize the "conference highband" vector // initialize the "conference highband" vector
conf_high = new ArrayList(2); conf_high = new ArrayList(2);
tmp = new Role(CONFERENCE_ANYADMIN,"Any Conference Administrator"); tmp = new Role(CONFERENCE_ANYADMIN,"Any Conference Administrator");
conf_high.add(tmp); conf_high.add(tmp);
all_roles.put(new Integer(CONFERENCE_ANYADMIN),tmp);
tmp = new Role(CONFERENCE_HOST,"Conference Host"); tmp = new Role(CONFERENCE_HOST,"Conference Host");
conf_high.add(tmp); conf_high.add(tmp);
all_roles.put(new Integer(CONFERENCE_HOST),tmp);
conf_high.trimToSize(); conf_high.trimToSize();
} // end static initializer } // end static initializer

View File

@ -0,0 +1,225 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Communities System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.security;
public final class ScopeInfo implements Cloneable, Comparable
{
/*--------------------------------------------------------------------------------
* Static data members
*--------------------------------------------------------------------------------
*/
private static final int[] LB_LOW = // Scope values, lowband, low end of range
{ 0, 2000, 4000, 6000, 8000, 10000, 12000, 14000, 16000, 18000, 20000, 22000, 24000, 26000, 28000,
30000 };
private static final int[] LB_HIGH = // Scope values, lowband, high end of range
{ 1999, 3999, 5999, 7999, 9999, 11999, 13999, 15999, 17999, 19999, 21999, 23999, 25999, 27999, 29999,
31999 };
private static final int[] HB_LOW = // Scope values, highband, low end of range
{ 63000, 61000, 59000, 57000, 55000, 53000, 51000, 49000, 47000, 45000, 43000, 41000, 39000, 37000,
35000, 33000 };
private static final int[] HB_HIGH = // Scope values, highband, high end of range
{ 64999, 62999, 60999, 58999, 56999, 54999, 52999, 50999, 48999, 46999, 44999, 42999, 40999, 38999,
36999, 34999 };
public static final int L_NOT_THERE = -1; // global "not there" constant
public static final int L_UNRESTRICTED = 32500; // global "unrestricted user" constant
public static final int L_NO_ACCESS = 65500; // global "no access" constant
public static final int BAND_WIDTH = 1999; // offset between "high and low" values within a band
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
int scope; // the scope value
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
public ScopeInfo(int scope)
{
if ((scope<0) || (scope>=LB_LOW.length))
throw new IndexOutOfBoundsException("invalid scope value");
this.scope = scope;
} // end constructor
/*--------------------------------------------------------------------------------
* Overrides from class Object
*--------------------------------------------------------------------------------
*/
public boolean equals(Object o)
{
if ((o==null) || !(o instanceof ScopeInfo))
return false;
ScopeInfo other = (ScopeInfo)o;
return (scope==other.scope);
} // end equals
public int hashCode()
{
return scope;
} // end hashCode
public String toString()
{
StringBuffer buf = new StringBuffer("{ScopeInfo(");
buf.append(scope).append("): ranges [").append(LB_LOW[scope]).append('-').append(LB_HIGH[scope]);
buf.append("], [").append(HB_LOW[scope]).append('-').append(HB_HIGH[scope]).append("]}");
return buf.toString();
} // end toString
/*--------------------------------------------------------------------------------
* Implementations from interface Comparable
*--------------------------------------------------------------------------------
*/
public int compareTo(Object o)
{
if (o==null)
throw new NullPointerException("can't compare to a null object");
ScopeInfo other = (ScopeInfo)o; // may throw ClassCastException - that's OK
return scope - other.scope;
} // end compareTo
/*--------------------------------------------------------------------------------
* External operations
*--------------------------------------------------------------------------------
*/
public final int getScope()
{
return scope;
} // end getScope
public final int getLowBandLow()
{
return LB_LOW[scope];
} // end getLowBandLow
public final int getLowBandHigh()
{
return LB_HIGH[scope];
} // end getLowBandHigh
public final int getHighBandLow()
{
return HB_LOW[scope];
} // end getHighBandLow
public final int getHighBandHigh()
{
return HB_HIGH[scope];
} // end getHighBandHigh
public final int getLevel(boolean highband, int offset)
{
int rc;
if (highband)
{ // it's in the highband
if (offset<0)
{ // negative offset from high end of highband
rc = HB_HIGH[scope] + offset;
if (rc<HB_LOW[scope])
throw new IllegalArgumentException("value out of scope");
} // end if
else
{ // positive offset from low end of highband
rc = HB_LOW[scope] + offset;
if (rc>HB_HIGH[scope])
throw new IllegalArgumentException("value out of scope");
} // end else
} // end if (highband)
else
{ // it's in the lowband
if (offset<0)
{ // negative offset from high end of lowband
rc = LB_HIGH[scope] + offset;
if (rc<LB_LOW[scope])
throw new IllegalArgumentException("value out of scope");
} // end if
else
{ // positive offset from low end of lowband
rc = LB_LOW[scope] + offset;
if (rc>LB_HIGH[scope])
throw new IllegalArgumentException("value out of scope");
} // end else
} // end else (lowband)
return rc;
} // end getLevel
public final boolean isInScope(int value)
{
if ((value>=LB_LOW[scope]) && (value<=LB_HIGH[scope]))
return true;
if ((value>=HB_LOW[scope]) && (value<=HB_HIGH[scope]))
return true;
return false;
} // end isInScope
/*--------------------------------------------------------------------------------
* External static operations
*--------------------------------------------------------------------------------
*/
public static final boolean isValidScope(int s)
{
return ((s>=0) && (s<LB_LOW.length));
} // end isValidScope
public static final int getScopeOf(int value)
{
if ((value<LB_LOW[0]) || (value>HB_HIGH[0]))
return -1; // quick test to eliminate most of the range
for (int i=0; i<LB_LOW.length; i++)
{ // look in each scope in turn
if ((value<=LB_HIGH[i]) || (value>=HB_LOW[i]))
return i;
} // end for
return -1; // not in a scope
} // end getScopeOf
} // end class ScopeInfo

View File

@ -0,0 +1,43 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Communities System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.security;
import java.util.List;
import com.silverwrist.venice.core.AccessError;
public interface SecurityMonitor
{
public abstract boolean testPermission(String symbol, int level, String errormsg) throws AccessError;
public abstract boolean testPermission(String symbol, int level);
public abstract boolean permissionDefined(String symbol, boolean no_follow);
public abstract List getRoleList(String symbol);
public abstract Role getRole(String symbol);
public abstract Role getRoleForLevel(int level);
public abstract Role getDefaultRole(String symbol);
public abstract ScopeInfo getScopeInfo();
public abstract String getID();
} // end interface SecurityMonitor

View File

@ -0,0 +1,713 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Communities System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.security;
import java.util.*;
import org.apache.log4j.*;
import org.w3c.dom.*;
import com.silverwrist.util.DOMElementHelper;
import com.silverwrist.venice.core.AccessError;
import com.silverwrist.venice.core.ConfigException;
public class StaticSecurityMonitor implements SecurityMonitor
{
/*--------------------------------------------------------------------------------
* Internal class for evaluating static permissions
*--------------------------------------------------------------------------------
*/
final class StaticPermission
{
private Role role;
private String message;
StaticPermission(Role role, String message)
{
this.role = role;
this.message = message;
} // end constructor
final void test(int level, String errormessage) throws AccessError
{
if (!(role.isSatisfiedBy(level)))
{ // the static permission test failed!
logger.warn("Static permission test (level " + level + " vs. role " + role + ") failed");
if (errormessage==null)
errormessage = message;
if (errormessage==null)
errormessage = "Operation not permitted.";
throw new AccessError(errormessage);
} // end if
} // end test
final boolean test(int level)
{
return role.isSatisfiedBy(level);
} // end test
} // end class StaticPermission
/*--------------------------------------------------------------------------------
* Static data members
*--------------------------------------------------------------------------------
*/
private static Category logger = Category.getInstance(StaticSecurityMonitor.class);
private static SecurityMonitor root_monitor = null;
private static Map known_monitors = Collections.synchronizedMap(new HashMap());
private static int DEFAULT_SCOPE_OFFSET = 3;
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private String id; // the identity of this security monitor
private ScopeInfo scope; // the scope of this security monitor
private SecurityMonitor parent; // the parent of this security monitor
private Map sym_to_role; // mapping of role symbols to roles
private Map level_to_role; // mapping of role levels to roles
private Map lists; // mapping of list symbols to lists
private Map default_roles; // mapping of symbols to default values
private Map static_permissions; // mapping of symbols to static permissions
private Set dynamic_permissions; // set of defined dynamic permission names
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
public StaticSecurityMonitor(Element cfg) throws ConfigException
{
boolean set_root_monitor = false;
if (!(cfg.getTagName().equals("security-definition")))
{ // not the right kind of element!
logger.fatal("security monitor config is not a <security-definition/> element");
throw new ConfigException("configuration must be a <security-definition/>",cfg);
} // end if
DOMElementHelper root_h = new DOMElementHelper(cfg);
if (root_h.hasAttribute("id"))
id = cfg.getAttribute("id");
else
{ // no id= attribute? that's bad!
logger.fatal("security monitor has no id= attribute");
throw new ConfigException("<security-definition/> must have an id= attribute",cfg);
} // end else
if (logger.isDebugEnabled())
logger.debug("defining new StaticSecurityMonitor with id=" + id);
if (known_monitors.containsKey(id))
{ // the monitor with this ID has already been defined!
logger.fatal("security monitor with id=" + id + " is already defined!");
throw new ConfigException("security monitor id=" + id + " is already defined!");
} // end if
if (root_h.hasAttribute("parent"))
{ // find our parent
String parent_id = cfg.getAttribute("parent");
parent = (SecurityMonitor)(known_monitors.get(parent_id));
if (parent==null)
{ // no parent! that's bogus!
logger.fatal("parent security monitor with id=" + parent_id + " does not exist!");
throw new ConfigException("parent security monitor with id=" + parent_id + " does not exist!");
} // end if
int my_scope = parent.getScopeInfo().getScope();
int my_offset = DEFAULT_SCOPE_OFFSET;
if (root_h.hasAttribute("offset"))
{ // get the offset value and compare it
Integer tmp = root_h.getAttributeInt("offset");
if (tmp==null)
{ // the offset was not an integer value - bye now!
logger.fatal("offset= value was not an integer");
throw new ConfigException("offset= attribute of <security-definition/> must be an integer");
} // end if
my_offset = tmp.intValue();
if (my_offset<1)
{ // the offset must be greater than or equal to 1!
logger.fatal("offset= value (" + my_offset + ") was out of range");
throw new ConfigException("offset= attribute of <security-definition/> must be >= 1");
} // end if
} // end if
my_scope += my_offset;
if (!(ScopeInfo.isValidScope(my_scope)))
{ // resulting scope is out of range!
logger.fatal("scope for id=" + id + " comes out to " + my_scope + ", and that's not in range");
throw new ConfigException("scope for security monitor id=" + id + " is out of range!");
} // end if
// allocate a scope info object with the new scope
scope = new ScopeInfo(my_scope);
} // end if
else
{ // this must be the root security monitor!
if (root_monitor!=null)
{ // but we already have a root - can't be two roots!
logger.fatal("trying to define root security monitor but we already have one");
throw new ConfigException("root security monitor is already defined!");
} // end if
// we are the root security monitor...we live at scope 0, our parent is the primordial monitor
set_root_monitor = true;
scope = new ScopeInfo(0);
parent = PrimordialSecurityMonitor.get();
} // end else
// get the defined roles
Element sect = root_h.getSubElement("defined-roles");
NodeList nl;
int i;
if (sect!=null)
{ // we need to define some roles here...
HashMap tmp_sym_to_role = new HashMap();
HashMap tmp_level_to_role = new HashMap();
nl = sect.getChildNodes();
for (i=0; i<nl.getLength(); i++)
{ // get each child node, see if it's a <role/>
Node n = nl.item(i);
if ((n.getNodeType()==Node.ELEMENT_NODE) && (n.getNodeName().equals("role")))
{ // create the role and add it to the temporary
Role r = createRole((Element)n);
tmp_sym_to_role.put(r.getSymbol(),r);
tmp_level_to_role.put(new Integer(r.getLevel()),r);
} // end if
} // end for
if (tmp_sym_to_role.size()>0)
{ // save these off as unmodifiable maps
sym_to_role = Collections.unmodifiableMap(tmp_sym_to_role);
level_to_role = Collections.unmodifiableMap(tmp_level_to_role);
} // end if
else
{ // nothing defined here!
sym_to_role = Collections.EMPTY_MAP;
level_to_role = Collections.EMPTY_MAP;
} // end else
} // end if
else
{ // I guess we don't define any roles!
sym_to_role = Collections.EMPTY_MAP;
level_to_role = Collections.EMPTY_MAP;
} // end else
// since lists may indirectly define default roles and permissions, create storage space for them
HashMap tmp_default_roles = new HashMap();
HashMap tmp_static_permissions = new HashMap();
HashSet tmp_dynamic_permissions = new HashSet();
// get the defined role lists
sect = root_h.getSubElement("defined-lists");
if (sect!=null)
{ // we need to define some role lists here!
HashMap tmp_lists = new HashMap();
nl = sect.getChildNodes();
for (i=0; i<nl.getLength(); i++)
{ // get each child node, see if it's a <list/>
Node n = nl.item(i);
if ((n.getNodeType()==Node.ELEMENT_NODE) && (n.getNodeName().equals("list")))
{ // create the role list and add it to the temporary map
// but first, get the ID
DOMElementHelper hn = new DOMElementHelper((Element)n);
String list_id;
if (hn.hasAttribute("id"))
list_id = id + "." + hn.getElement().getAttribute("id");
else
{ // no id= attribute - can't do anything with this
logger.fatal("<list/> element found with no id= attribute!");
throw new ConfigException("no id= attribute on defined <list/> element",hn.getElement());
} // end else
// now actually build the list and insert it
List rlist = buildList(hn.getElement(),list_id,tmp_default_roles,tmp_static_permissions,
tmp_dynamic_permissions);
tmp_lists.put(list_id,rlist);
} // end if
} // end for
if (tmp_lists.size()>0)
lists = Collections.unmodifiableMap(tmp_lists);
else
lists = Collections.EMPTY_MAP;
} // end if
else // no lists defined here!
lists = Collections.EMPTY_MAP;
// Get the additional defined default roles.
sect = root_h.getSubElement("defaults");
if (sect!=null)
{ // get the nodes in the defaults section
nl = sect.getChildNodes();
for (i=0; i<nl.getLength(); i++)
{ // pick out each one and process it if it's a <default/>
Node n = nl.item(i);
if ((n.getNodeType()==Node.ELEMENT_NODE) && (n.getNodeName().equals("default")))
processDefault((Element)n,tmp_default_roles);
} // end for
} // end if
// else no more defined defaults
// Since that's it for the defaults, freeze the defaults list.
if (tmp_default_roles.size()>0)
default_roles = Collections.unmodifiableMap(tmp_default_roles);
else
default_roles = Collections.EMPTY_MAP;
// Get the defined permissions.
sect = root_h.getSubElement("permissions");
if (sect!=null)
{ // get the nodes in the permissions section
nl = sect.getChildNodes();
for (i=0; i<nl.getLength(); i++)
{ // pick out each one and process it if it's a <permission/>
Node n = nl.item(i);
if ((n.getNodeType()==Node.ELEMENT_NODE) && (n.getNodeName().equals("permission")))
processPermission((Element)n,tmp_static_permissions,tmp_dynamic_permissions);
} // end for
} // end if
// else no more defined permissions
// That's now it for the permissions, so freeze those elements.
if (tmp_static_permissions.size()>0)
static_permissions = Collections.unmodifiableMap(tmp_static_permissions);
else
static_permissions = Collections.EMPTY_MAP;
if (tmp_dynamic_permissions.size()>0)
dynamic_permissions = Collections.unmodifiableSet(tmp_dynamic_permissions);
else
dynamic_permissions = Collections.EMPTY_SET;
// Finish up by adding ourselves to the known monitors list.
known_monitors.put(id,this);
if (set_root_monitor)
root_monitor = this;
} // end constructor
/*--------------------------------------------------------------------------------
* Internal operations
*--------------------------------------------------------------------------------
*/
private Role createRole(Element e) throws ConfigException
{
String symbol, text;
int level;
DOMElementHelper h = new DOMElementHelper(e);
if (h.hasAttribute("id"))
symbol = id + "." + e.getAttribute("id"); // symbols get automagically scoped
else
{ // no role defined
logger.fatal("<role/> defined with no id= attribute!");
throw new ConfigException("no id= attribute for a <role/>",e);
} // end else
if (h.hasAttribute("value"))
{ // get the value and parse it out
String value_str = e.getAttribute("value").trim().toUpperCase();
if (value_str.equals("LMIN"))
level = scope.getLowBandLow();
else if (value_str.equals("LMAX"))
level = scope.getLowBandHigh();
else if (value_str.equals("HMIN"))
level = scope.getHighBandLow();
else if (value_str.equals("HMAX"))
level = scope.getHighBandHigh();
else if ( value_str.startsWith("L+") || value_str.startsWith("L-") || value_str.startsWith("H+")
|| value_str.startsWith("H-"))
{ // take the characters following the 2-character prefix and convert them to an integer
int offset;
try
{ // convert the value and make sure it's not less than 0
offset = Integer.parseInt(value_str.substring(2));
if (offset<0)
{ // don't want it less than zero here!
logger.fatal("offset value " + offset + " was out of range");
throw new ConfigException("offset value= attribute for <role/> was out of range",e);
} // end if
} // end try
catch (NumberFormatException nfe)
{ // not a numeric offset value
logger.fatal("offset value \"" + value_str + "\" was not numeric");
throw new ConfigException("offset value= attribute for <role/> was not properly numeric",e);
} // end catch
if (value_str.charAt(1)=='-')
offset = -offset; // compute as negative offset
try
{ // now use the scope to compute the level!
level = scope.getLevel((value_str.charAt(0)=='H'),offset);
} // end try
catch (IllegalArgumentException iae)
{ // we landed with a value outside the scope!
logger.fatal("offset value \"" + value_str + "\" was not in the scope");
throw new ConfigException("offset value= attribute for <role/> was not within the scope",e);
} // end catch
} // end else if
else
{ // just a straight numeric level
try
{ // parse it out and give it a scope check
level = Integer.parseInt(value_str);
if (!(scope.isInScope(level)))
{ // not in the right scope - can't help you, pal!
logger.fatal("level value \"" + level + "\" was not in the scope");
throw new ConfigException("level value= attribute for <role/> was not within the scope",e);
} // end if
} // end try
catch (NumberFormatException nfe)
{ // the level was not numeric
logger.fatal("level value \"" + value_str + "\" was not numeric");
throw new ConfigException("level value= attribute for <role/> was not properly numeric",e);
} // end catch
} // end else
} // end if
else
{ // no value defined for this role!
logger.fatal("<role/> defined with no value= attribute!");
throw new ConfigException("no value= attribute for a <role/>",e);
} // end else
// Get the text; default to the symbol name if it doesn't exist.
text = h.getElementText();
if (text==null)
text = symbol;
// create the resulting role!
return Role.create(level,text,symbol);
} // end createRole
private List buildList(Element elem, String listid, Map defaultrole, Map static_perm, Set dynamic_perm)
throws ConfigException
{
DOMElementHelper h = new DOMElementHelper(elem);
Element perm = h.getSubElement("permission");
if (perm!=null)
{ // there's a permission associated with this list, find out what it is
DOMElementHelper ph = new DOMElementHelper(perm);
if (ph.hasAttribute("role"))
{ // look up the role and make sure it corresponds to one we know
Role role = this.getRole(perm.getAttribute("role"));
if (role==null)
{ // role not present!
logger.fatal("list <permission/> role (" + perm.getAttribute("role") + ") not defined");
throw new ConfigException("<permission/> inside of <list/> did not use defined role!",perm);
} // end if
// create a new StaticPermission and add it to the mapping
StaticPermission sp = new StaticPermission(role,ph.getElementText());
static_perm.put(listid,sp);
} // end if
else // this is a dynamic permission, add it to the set
dynamic_perm.add(listid);
} // end if
// else there's no problem
NodeList nl = elem.getChildNodes();
ArrayList rc = new ArrayList(nl.getLength());
boolean have_default = false;
for (int i=0; i<nl.getLength(); i++)
{ // look for list elements
Node n = nl.item(i);
if ((n.getNodeType()==Node.ELEMENT_NODE) && (n.getNodeName().equals("element")))
{ // look at the attributes of this element node
DOMElementHelper itmh = new DOMElementHelper((Element)n);
Role r = null;
if (itmh.hasAttribute("role"))
{ // convert the string into a role
r = this.getRole(itmh.getElement().getAttribute("role"));
if (r==null)
{ // the role is not defined!
logger.fatal("list <element/> role (" + itmh.getElement().getAttribute("role") + ") not defined");
throw new ConfigException("<element/> inside of <list/> did not use defined role!",
itmh.getElement());
} // end if
} // end if
else
{ // no attribute present
logger.fatal("<element/> defined with no role= attribute!");
throw new ConfigException("no role= attribute for a list <element/>",itmh.getElement());
} // end else
rc.add(r); // add element to defining list
if (itmh.hasAttribute("default"))
{ // this is a default item...
if (have_default)
{ // but there can't be two defaults!
logger.fatal("duplicate default= attributes in list <element/> nodes!");
throw new ConfigException("duplicate default= attribute in list <element/>",itmh.getElement());
} // end if
else
{ // we have a default for the list now!
defaultrole.put(listid,r);
have_default = true;
} // end else
} // end if
} // end if
} // end for
// Final prep on the list prior to returning it.
Collections.sort(rc);
rc.trimToSize();
return Collections.unmodifiableList(rc);
} // end buildlist
private void processDefault(Element elem, Map defaultrole) throws ConfigException
{
// Start by getting the default ID.
DOMElementHelper h = new DOMElementHelper(elem);
String def_id = null;
if (h.hasAttribute("id"))
def_id = id + "." + elem.getAttribute("id");
else
{ // no id defined!
logger.fatal("<default/> defined with no id= attribute!");
throw new ConfigException("no id= attribute for a <default/>",elem);
} // end else
Role r = null;
if (h.hasAttribute("role"))
{ // get the role associated with the item
r = this.getRole(elem.getAttribute("role"));
if (r==null)
{ // no role found - this is an error!
logger.fatal("<default/> role (" + elem.getAttribute("role") + ") not defined");
throw new ConfigException("<default/> did not use defined role!",elem);
} // end if
} // end if
else
{ // no role defined!
logger.fatal("<default/> defined with no id= attribute!");
throw new ConfigException("no id= attribute for a <default/>",elem);
} // end else
defaultrole.put(def_id,r);
} // end processDefault
private void processPermission(Element elem, Map static_perm, Set dynamic_perm) throws ConfigException
{
// Start by getting the permission ID.
DOMElementHelper h = new DOMElementHelper(elem);
String perm_id = null;
if (h.hasAttribute("id"))
perm_id = id + "." + elem.getAttribute("id");
else
{ // no id defined!
logger.fatal("<permission/> defined with no id= attribute!");
throw new ConfigException("no id= attribute for a <permission/>",elem);
} // end else
if (h.hasAttribute("role"))
{ // this is a static permission; try and get the associated role
Role r = this.getRole(elem.getAttribute("role"));
if (r==null)
{ // no role found - this is an error!
logger.fatal("<permission/> role (" + elem.getAttribute("role") + ") not defined");
throw new ConfigException("<permission/> did not use defined role!",elem);
} // end if
// create static permission and add it
StaticPermission sp = new StaticPermission(r,h.getElementText());
static_perm.put(perm_id,sp);
} // end if
else // this is a dynamic permission; just add to our set
dynamic_perm.add(perm_id);
} // end processPermission
/*--------------------------------------------------------------------------------
* Implementations from interface SecurityMonitor
*--------------------------------------------------------------------------------
*/
public boolean testPermission(String symbol, int level, String errormsg) throws AccessError
{
if (symbol==null)
throw new NullPointerException("testPermission() got null symbol");
StaticPermission sp = (StaticPermission)(static_permissions.get(symbol));
if (sp==null)
{ // permission not found here - NOTE! Do not call to parent unless we are at the root level, as
// permission tests always follow the DYNAMIC chain, not the static one!
if (scope.getScope()==0)
return parent.testPermission(symbol,level,errormsg);
else
return false;
} // end if
sp.test(level,errormsg); // will throw AccessError on failure
return true;
} // end testPermission
public boolean testPermission(String symbol, int level)
{
if (symbol==null)
throw new NullPointerException("testPermission() got null symbol");
StaticPermission sp = (StaticPermission)(static_permissions.get(symbol));
if (sp==null)
{ // permission not found here - NOTE! Do not call to parent unless we are at the root level, as
// permission tests always follow the DYNAMIC chain, not the static one!
if (scope.getScope()==0)
return parent.testPermission(symbol,level);
else
return false;
} // end if
return sp.test(level);
} // end testPermission
public boolean permissionDefined(String symbol, boolean no_follow)
{
if (symbol==null)
throw new NullPointerException("permissionDefined() got null symbol");
if (static_permissions.containsKey(symbol) || dynamic_permissions.contains(symbol))
return true;
if (no_follow)
return false;
return parent.permissionDefined(symbol,false);
} // end permissionDefined
public List getRoleList(String symbol)
{
if (symbol==null)
throw new NullPointerException("getRoleList() got null symbol");
List rc = (List)(lists.get(symbol));
if (rc==null)
rc = parent.getRoleList(symbol);
return rc;
} // end getRoleList
public Role getRole(String symbol)
{
if (symbol==null)
throw new NullPointerException("getRole() got null symbol");
Role rc = (Role)(sym_to_role.get(symbol));
if (rc==null)
rc = parent.getRole(symbol);
return rc;
} // end getRole
public Role getRoleForLevel(int level)
{
Role rc = (Role)(level_to_role.get(new Integer(level)));
if (rc==null)
rc = parent.getRoleForLevel(level);
return rc;
} // end getRoleForLevel
public Role getDefaultRole(String symbol)
{
if (symbol==null)
throw new NullPointerException("getRole() got null symbol");
Role rc = (Role)(default_roles.get(symbol));
if (rc==null)
rc = parent.getDefaultRole(symbol);
return rc;
} // end getDefaultRole
public ScopeInfo getScopeInfo()
{
return scope;
} // end getScopeInfo
public String getID()
{
return id;
} // end getID
} // end class StaticSecurityMonitor

View File

@ -0,0 +1,21 @@
# The contents of this file are subject to the Mozilla Public License Version 1.1
# (the "License"); you may not use this file except in compliance with the License.
# You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
#
# Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
# WARRANTY OF ANY KIND, either express or implied. See the License for the specific
# language governing rights and limitations under the License.
#
# The Original Code is the Venice Web Communities System.
#
# The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
# for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
# Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
#
# Contributor(s):
# -------------------------------------------------------------------------------------
# Names for the roles initialized by the primordial security monitor
role.NoAccess.name=No Access
role.NotInList.name=(not in list)
role.UnrestrictedUser.name='Unrestricted' User

View File

@ -61,14 +61,14 @@ public class CommunityAdmin extends VeniceServlet
} // end makeCommunityAdminTop } // end makeCommunityAdminTop
private EditCommunityProfileDialog makeEditCommunityProfileDialog() throws ServletException private EditCommunityProfileDialog makeEditCommunityProfileDialog(SecurityInfo sinf) throws ServletException
{ {
final String desired_name = "EditCommunityProfileDialog"; final String desired_name = "EditCommunityProfileDialog";
DialogCache cache = DialogCache.getDialogCache(getServletContext()); DialogCache cache = DialogCache.getDialogCache(getServletContext());
if (!(cache.isCached(desired_name))) if (!(cache.isCached(desired_name)))
{ // create a template and save it off { // create a template and save it off
EditCommunityProfileDialog template = new EditCommunityProfileDialog(); EditCommunityProfileDialog template = new EditCommunityProfileDialog(sinf);
cache.saveTemplate(template); cache.saveTemplate(template);
} // end if } // end if
@ -126,7 +126,7 @@ public class CommunityAdmin extends VeniceServlet
} // end if } // end if
// construct the edit profile dialog and load it up for use // construct the edit profile dialog and load it up for use
EditCommunityProfileDialog dlg = makeEditCommunityProfileDialog(); EditCommunityProfileDialog dlg = makeEditCommunityProfileDialog(comm.getSecurityInfo());
try try
{ // load the values for this dialog { // load the values for this dialog
@ -393,7 +393,7 @@ public class CommunityAdmin extends VeniceServlet
} // end if } // end if
// construct the edit profile dialog and load it up for use // construct the edit profile dialog and load it up for use
EditCommunityProfileDialog dlg = makeEditCommunityProfileDialog(); EditCommunityProfileDialog dlg = makeEditCommunityProfileDialog(comm.getSecurityInfo());
dlg.setupDialogBasic(engine,comm); dlg.setupDialogBasic(engine,comm);
if (dlg.isButtonClicked(request,"cancel")) if (dlg.isButtonClicked(request,"cancel"))

View File

@ -75,14 +75,14 @@ public class SystemAdmin extends VeniceServlet
} // end makeAdminModifyUserDialog } // end makeAdminModifyUserDialog
private EditGlobalPropertiesDialog makeGlobalPropertiesDialog() throws ServletException private EditGlobalPropertiesDialog makeGlobalPropertiesDialog(SecurityInfo sinf) throws ServletException
{ {
final String desired_name = "EditGlobalPropertiesDialog"; final String desired_name = "EditGlobalPropertiesDialog";
DialogCache cache = DialogCache.getDialogCache(getServletContext()); DialogCache cache = DialogCache.getDialogCache(getServletContext());
if (!(cache.isCached(desired_name))) if (!(cache.isCached(desired_name)))
{ // create a template and save it off { // create a template and save it off
EditGlobalPropertiesDialog template = new EditGlobalPropertiesDialog(); EditGlobalPropertiesDialog template = new EditGlobalPropertiesDialog(sinf);
cache.saveTemplate(template); cache.saveTemplate(template);
} // end if } // end if
@ -186,7 +186,7 @@ public class SystemAdmin extends VeniceServlet
AdminUserContext admuser = adm.getUserContext(Integer.parseInt(s_uid)); AdminUserContext admuser = adm.getUserContext(Integer.parseInt(s_uid));
AdminModifyUserDialog dlg = makeAdminModifyUserDialog(); AdminModifyUserDialog dlg = makeAdminModifyUserDialog();
dlg.setupDialog(adm.isGlobalAdmin(),admuser); dlg.setupDialog(adm,admuser);
setMyLocation(request,"sysadmin?cmd=UM"); setMyLocation(request,"sysadmin?cmd=UM");
return dlg; return dlg;
@ -215,7 +215,7 @@ public class SystemAdmin extends VeniceServlet
try try
{ // get the global properties { // get the global properties
AdminOperations adm = user.getAdminInterface(); AdminOperations adm = user.getAdminInterface();
EditGlobalPropertiesDialog dlg = makeGlobalPropertiesDialog(); EditGlobalPropertiesDialog dlg = makeGlobalPropertiesDialog(adm.getSecurityInfo());
dlg.setupDialog(adm); dlg.setupDialog(adm);
setMyLocation(request,"sysadmin?cmd=G"); setMyLocation(request,"sysadmin?cmd=G");
return dlg; return dlg;
@ -301,7 +301,7 @@ public class SystemAdmin extends VeniceServlet
} // end try } // end try
catch (ValidationException ve) catch (ValidationException ve)
{ // this is a simple error { // this is a simple error
dlg.resetOnError(adm.isGlobalAdmin(),admuser,ve.getMessage() + " Please try again."); dlg.resetOnError(adm,admuser,ve.getMessage() + " Please try again.");
setMyLocation(request,"sysadmin?cmd=UM"); setMyLocation(request,"sysadmin?cmd=UM");
return dlg; return dlg;
@ -339,7 +339,7 @@ public class SystemAdmin extends VeniceServlet
{ // "G" - Edit Global Properties { // "G" - Edit Global Properties
try try
{ // get the dialog box { // get the dialog box
EditGlobalPropertiesDialog dlg = makeGlobalPropertiesDialog(); EditGlobalPropertiesDialog dlg = makeGlobalPropertiesDialog(engine.getSecurityInfo());
if (dlg.isButtonClicked(request,"cancel")) if (dlg.isButtonClicked(request,"cancel"))
throw new RedirectResult("sysadmin"); // we decided not to bother - go back throw new RedirectResult("sysadmin"); // we decided not to bother - go back

View File

@ -42,7 +42,7 @@ public class AdminModifyUserDialog extends ContentDialog
addFormField(new CDPasswordFormField("pass2","Password","(retype)",false,32,128)); addFormField(new CDPasswordFormField("pass2","Password","(retype)",false,32,128));
addFormField(new CDTextFormField("remind","Password reminder phrase",null,false,32,255)); addFormField(new CDTextFormField("remind","Password reminder phrase",null,false,32,255));
addFormField(new CDRoleListFormField("base_lvl","Base security level",null,true, addFormField(new CDRoleListFormField("base_lvl","Base security level",null,true,
Role.getBaseLevelChoices())); Collections.EMPTY_LIST));
addFormField(new CDCheckBoxFormField("verify_email","E-mail address verified",null,"Y")); addFormField(new CDCheckBoxFormField("verify_email","E-mail address verified",null,"Y"));
addFormField(new CDCheckBoxFormField("lockout","Account locked out",null,"Y")); addFormField(new CDCheckBoxFormField("lockout","Account locked out",null,"Y"));
addFormField(new CDFormCategoryHeader("Name")); addFormField(new CDFormCategoryHeader("Name"));
@ -91,29 +91,23 @@ public class AdminModifyUserDialog extends ContentDialog
*-------------------------------------------------------------------------------- *--------------------------------------------------------------------------------
*/ */
private void coreSetup(boolean is_global_admin, AdminUserContext admuser) private void coreSetup(AdminOperations ops, AdminUserContext admuser)
{ {
setSubtitle("User: " + admuser.getUserName()); setSubtitle("User: " + admuser.getUserName());
setHiddenField("uid",String.valueOf(admuser.getUID())); setHiddenField("uid",String.valueOf(admuser.getUID()));
CDPickListFormField level_field = (CDPickListFormField)modifyField("base_lvl"); CDPickListFormField level_field = (CDPickListFormField)modifyField("base_lvl");
List role_list; List role_list = ops.getAllowedRoleList();
if (is_global_admin)
role_list = level_field.getChoicesList();
else
{ // not a global admin - deny user the right to select assistant admin choices
role_list = Role.getBaseLevelChoices2();
level_field.setChoicesList(role_list); level_field.setChoicesList(role_list);
} // end else
// See if this level was found on the list. // See if this level was found on the list.
Role my_role = admuser.getBaseRole();
boolean found = false; boolean found = false;
Iterator it = role_list.iterator(); Iterator it = role_list.iterator();
while (it.hasNext()) while (it.hasNext())
{ // seek each role in turn { // seek each role in turn
Role r = (Role)(it.next()); Role r = (Role)(it.next());
if (r.getLevel()==admuser.getBaseLevel()) if (r.equals(my_role))
{ // found it! { // found it!
found = true; found = true;
break; break;
@ -124,7 +118,7 @@ public class AdminModifyUserDialog extends ContentDialog
if (!found) if (!found)
{ // not in the list - set the defined "role list" to be a singleton of our current level { // not in the list - set the defined "role list" to be a singleton of our current level
role_list = Collections.singletonList(Role.getRoleForLevel(admuser.getBaseLevel())); role_list = Collections.singletonList(my_role);
level_field.setChoicesList(role_list); level_field.setChoicesList(role_list);
} // end if } // end if
@ -172,9 +166,9 @@ public class AdminModifyUserDialog extends ContentDialog
*-------------------------------------------------------------------------------- *--------------------------------------------------------------------------------
*/ */
public void setupDialog(boolean is_global_admin, AdminUserContext admuser) throws DataException public void setupDialog(AdminOperations ops, AdminUserContext admuser) throws DataException
{ {
coreSetup(is_global_admin,admuser); coreSetup(ops,admuser);
setFieldValue("base_lvl",String.valueOf(admuser.getBaseLevel())); setFieldValue("base_lvl",String.valueOf(admuser.getBaseLevel()));
if (admuser.isEmailVerified()) if (admuser.isEmailVerified())
@ -281,9 +275,9 @@ public class AdminModifyUserDialog extends ContentDialog
} // end doDialog } // end doDialog
public void resetOnError(boolean is_global_admin, AdminUserContext admuser, String message) public void resetOnError(AdminOperations ops, AdminUserContext admuser, String message)
{ {
coreSetup(is_global_admin,admuser); coreSetup(ops,admuser);
setErrorMessage(message); setErrorMessage(message);
setFieldValue("pass1",null); setFieldValue("pass1",null);
setFieldValue("pass2",null); setFieldValue("pass2",null);

View File

@ -62,8 +62,9 @@ public class CommunityMembership implements JSPRender, SearchMode
{ {
this.engine = engine; this.engine = engine;
this.comm = comm; this.comm = comm;
this.role_choices = Role.getCommunityMemberLevelChoices(); SecurityInfo sinf = comm.getSecurityInfo();
this.role_comm_host = Role.getCommunityHostRole(); this.role_choices = sinf.getRoleList("Community.UserLevels");
this.role_comm_host = sinf.getRole("Community.Host");
} // end constructor } // end constructor

View File

@ -101,7 +101,7 @@ public class EditCommunityProfileDialog extends ContentDialog
*-------------------------------------------------------------------------------- *--------------------------------------------------------------------------------
*/ */
public EditCommunityProfileDialog() public EditCommunityProfileDialog(SecurityInfo sinf)
{ {
super("Edit Community Profile:",null,"commprofform","sigadmin"); super("Edit Community Profile:",null,"commprofform","sigadmin");
setHiddenField("cmd","P"); setHiddenField("cmd","P");
@ -145,15 +145,15 @@ public class EditCommunityProfileDialog extends ContentDialog
null,YES)); null,YES));
addFormField(new CDSimplePickListFormField("hidemode","Community visibility",null,true,vec_hidemode,'|')); addFormField(new CDSimplePickListFormField("hidemode","Community visibility",null,true,vec_hidemode,'|'));
addFormField(new CDRoleListFormField("read_lvl","Security level required to read contents",null,true, addFormField(new CDRoleListFormField("read_lvl","Security level required to read contents",null,true,
Role.getCommunityReadList())); sinf.getRoleList("Community.Read")));
addFormField(new CDRoleListFormField("write_lvl","Security level required to update profile",null,true, addFormField(new CDRoleListFormField("write_lvl","Security level required to update profile",null,true,
Role.getCommunityWriteList())); sinf.getRoleList("Community.Write")));
addFormField(new CDRoleListFormField("create_lvl","Security level required to create new subobjects", addFormField(new CDRoleListFormField("create_lvl","Security level required to create new subobjects",
null,true,Role.getCommunityCreateList())); null,true,sinf.getRoleList("Community.Create")));
addFormField(new CDRoleListFormField("delete_lvl","Security level required to delete community",null,true, addFormField(new CDRoleListFormField("delete_lvl","Security level required to delete community",null,true,
Role.getCommunityDeleteList())); sinf.getRoleList("Community.Delete")));
addFormField(new CDRoleListFormField("join_lvl","Security level required to join community",null,true, addFormField(new CDRoleListFormField("join_lvl","Security level required to join community",null,true,
Role.getCommunityJoinList())); sinf.getRoleList("Community.Join")));
addFormField(new CDFormCategoryHeader("Conferencing Options")); addFormField(new CDFormCategoryHeader("Conferencing Options"));
addFormField(new CDCheckBoxFormField("pic_in_post","Display user pictures next to posts in conferences", addFormField(new CDCheckBoxFormField("pic_in_post","Display user pictures next to posts in conferences",

View File

@ -31,7 +31,7 @@ public class EditGlobalPropertiesDialog extends ContentDialog
*-------------------------------------------------------------------------------- *--------------------------------------------------------------------------------
*/ */
public EditGlobalPropertiesDialog() public EditGlobalPropertiesDialog(SecurityInfo sinf)
{ {
super("Edit Global Properties",null,"globpropform","sysadmin"); super("Edit Global Properties",null,"globpropform","sysadmin");
setHiddenField("cmd","G"); setHiddenField("cmd","G");
@ -44,7 +44,7 @@ public class EditGlobalPropertiesDialog extends ContentDialog
addFormField(new CDIntegerFormField("audit_recs","Number of audit records to display per page", addFormField(new CDIntegerFormField("audit_recs","Number of audit records to display per page",
null,10,500)); null,10,500));
addFormField(new CDRoleListFormField("create_lvl","Security level required to create a new community", addFormField(new CDRoleListFormField("create_lvl","Security level required to create a new community",
null,true,Role.getNewCommunityLevelChoices())); null,true,sinf.getRoleList("Global.CreateCommunity")));
addFormField(new CDFormCategoryHeader("Community Properties")); addFormField(new CDFormCategoryHeader("Community Properties"));
addFormField(new CDIntegerFormField("comm_mbrs","Number of community members to display per page", addFormField(new CDIntegerFormField("comm_mbrs","Number of community members to display per page",