Commit ffafba9b by Tuomas Riihimäki

base64 apache libeille, Role puljausta.

1 parent 7b45166f
Showing with 169 additions and 289 deletions
...@@ -4,9 +4,9 @@ ...@@ -4,9 +4,9 @@
<comment></comment> <comment></comment>
<projects> <projects>
<project>LanBortalBeans</project> <project>LanBortalBeans</project>
<project>LanBortalWeb</project>
<project>LanBortalBeansClient</project> <project>LanBortalBeansClient</project>
<project>LanBortalUtilities</project> <project>LanBortalUtilities</project>
<project>LanBortalWeb</project>
</projects> </projects>
<buildSpec> <buildSpec>
<buildCommand> <buildCommand>
......
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<classpath> <classpath>
<classpathentry kind="src" path="src"/> <classpathentry kind="src" path="src"/>
<classpathentry combineaccessrules="false" exported="true" kind="src" path="/LanBortalAuthModuleClient"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/> <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>
<classpathentry kind="con" path="org.eclipse.jst.server.core.container/com.sun.enterprise.jst.server.runtimeTarget/GlassFish v3 Java EE 6"/> <classpathentry kind="con" path="org.eclipse.jst.server.core.container/com.sun.enterprise.jst.server.runtimeTarget/GlassFish v3 Java EE 6"/>
<classpathentry combineaccessrules="false" kind="src" path="/LanBortalAuthModuleClient"/>
<classpathentry kind="lib" path="/Users/tuomari/bin/glassfishv31_0507_2/glassfish/lib/appserv-rt.jar"/> <classpathentry kind="lib" path="/Users/tuomari/bin/glassfishv31_0507_2/glassfish/lib/appserv-rt.jar"/>
<classpathentry kind="output" path="bin"/> <classpathentry kind="output" path="bin"/>
</classpath> </classpath>
package fi.insomnia.bortal;
import java.io.IOException;
import java.util.Map;
import javax.security.auth.Subject;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.auth.message.AuthException;
import javax.security.auth.message.AuthStatus;
import javax.security.auth.message.MessageInfo;
import javax.security.auth.message.MessagePolicy;
import javax.security.auth.message.callback.CallerPrincipalCallback;
import javax.security.auth.message.callback.GroupPrincipalCallback;
import javax.security.auth.message.callback.PasswordValidationCallback;
import javax.security.auth.message.module.ServerAuthModule;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.sun.jersey.core.util.Base64;
public class BortalServerAuthModule implements ServerAuthModule {
protected static final Class<?>[] supportedMessageTypes =
new Class[] {
HttpServletRequest.class,
HttpServletResponse.class
};
private MessagePolicy requestPolicy;
private MessagePolicy responsePolicy;
private CallbackHandler handler;
private Map<?, ?> options;
private String realmName = null;
private String defaultGroup[] = null;
private static final String REALM_PROPERTY_NAME = "realm.name";
private static final String GROUP_PROPERTY_NAME = "group.name";
private static final String BASIC = "Basic";
static final String AUTHORIZATION_HEADER = "authorization";
static final String AUTHENTICATION_HEADER = "WWW-Authenticate";
private static void log(String str) {
System.out.println(str);
}
public void initialize(MessagePolicy reqPolicy, MessagePolicy resPolicy,
CallbackHandler cBH, Map opts)
throws AuthException {
requestPolicy = reqPolicy;
responsePolicy = resPolicy;
handler = cBH;
options = opts;
if (options != null) {
realmName = (String) options.get(REALM_PROPERTY_NAME);
if (options.containsKey(GROUP_PROPERTY_NAME)) {
defaultGroup = new String[] { (String)
options.get(GROUP_PROPERTY_NAME) };
}
}
}
public Class<?>[] getSupportedMessageTypes() {
return supportedMessageTypes;
}
public AuthStatus validateRequest(MessageInfo msgInfo, Subject client, Subject server) throws AuthException {
try {
String username = processAuthorizationToken(msgInfo, client);
log("req pol mand: " + requestPolicy.isMandatory());
if (username == null && requestPolicy.isMandatory()) {
return sendAuthenticateChallenge(msgInfo);
}
setAuthenticationResult(username, client, msgInfo);
return AuthStatus.SUCCESS;
} catch (Exception e) {
AuthException ae = new AuthException();
ae.initCause(e);
throw ae;
}
}
private String processAuthorizationToken(MessageInfo msgInfo, Subject s) throws AuthException {
HttpServletRequest request = (HttpServletRequest) msgInfo.getRequestMessage();
String token = request.getHeader(AUTHORIZATION_HEADER);
log("Processing authentication: " + token);
if (token != null && token.startsWith(BASIC + " ")) {
token = token.substring(6).trim();
// Decode and parse the authorization token
String decoded = new String(Base64.decode(token.getBytes()));
int colon = decoded.indexOf(':');
if (colon <= 0 || colon == decoded.length() - 1) {
return (null);
}
String username = decoded.substring(0, colon);
log("Logging in as :" + username);
// use the callback to ask the container to
// validate the password
PasswordValidationCallback pVC = new PasswordValidationCallback(s, username,
decoded.substring(colon + 1).toCharArray());
try {
handler.handle(new Callback[] { pVC });
pVC.clearPassword();
} catch (Exception e) {
AuthException ae = new AuthException();
ae.initCause(e);
throw ae;
}
if (pVC.getResult()) {
return username;
}
}
return null;
}
private AuthStatus sendAuthenticateChallenge(MessageInfo msgInfo) {
log("Sending authenticate challenge!!!");
String realm = realmName;
// if the realm property is set use it,
// otherwise use the name of the server
// as the realm name.
if (realm == null) {
HttpServletRequest request = (HttpServletRequest) msgInfo.getRequestMessage();
realm = request.getServerName();
}
HttpServletResponse response = (HttpServletResponse) msgInfo.getResponseMessage();
String header = BASIC + " realm=\"" + realm + "\"";
response.setHeader(AUTHENTICATION_HEADER, header);
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return AuthStatus.SEND_CONTINUE;
}
public AuthStatus secureResponse(MessageInfo msgInfo, Subject service) throws AuthException {
log("Resp mand: " + responsePolicy.isMandatory());
if (responsePolicy.isMandatory()) {
return sendAuthenticateChallenge(msgInfo);
}
return AuthStatus.SEND_SUCCESS;
}
public void cleanSubject(MessageInfo msgInfo, Subject subject) throws AuthException {
if (subject != null) {
subject.getPrincipals().clear();
}
}
private static final String AUTH_TYPE_INFO_KEY = "javax.servlet.http.authType";
// distinguish the caller principal
// and assign default groups
private void setAuthenticationResult(String name, Subject s, MessageInfo m) throws IOException, UnsupportedCallbackException {
handler.handle(new Callback[] { new CallerPrincipalCallback(s, name) });
if (name != null) {
// add the default group if the property is set
if (defaultGroup != null) {
handler.handle(new Callback[] { new GroupPrincipalCallback(s, defaultGroup) });
}
m.getMap().put(AUTH_TYPE_INFO_KEY, "BortalSAM");
}
}
}
...@@ -19,7 +19,7 @@ public class PlaceBean implements PlaceBeanLocal { ...@@ -19,7 +19,7 @@ public class PlaceBean implements PlaceBeanLocal {
@EJB @EJB
private PlaceFacade placeFacade; private PlaceFacade placeFacade;
public void mergeChanges(Place place) { public Place mergeChanges(Place place) {
placeFacade.merge(place); return placeFacade.merge(place);
} }
} }
package fi.insomnia.bortal.beans; package fi.insomnia.bortal.beans;
import java.awt.Graphics;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
...@@ -14,16 +14,16 @@ import javax.imageio.ImageIO; ...@@ -14,16 +14,16 @@ import javax.imageio.ImageIO;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import fi.insomnia.bortal.enums.Permission;
import fi.insomnia.bortal.enums.RolePermission;
import fi.insomnia.bortal.exceptions.EjbPermissionDeniedException;
import fi.insomnia.bortal.facade.EventMapFacade; import fi.insomnia.bortal.facade.EventMapFacade;
import fi.insomnia.bortal.facade.PlaceFacade; import fi.insomnia.bortal.facade.PlaceFacade;
import fi.insomnia.bortal.facade.UserFacade;
import fi.insomnia.bortal.model.Event; import fi.insomnia.bortal.model.Event;
import fi.insomnia.bortal.model.EventMap; import fi.insomnia.bortal.model.EventMap;
import fi.insomnia.bortal.model.EventPk;
import fi.insomnia.bortal.model.Place; import fi.insomnia.bortal.model.Place;
import fi.insomnia.bortal.model.PlaceGroup; import fi.insomnia.bortal.model.PlaceGroup;
import fi.insomnia.bortal.model.User; import fi.insomnia.bortal.model.User;
import java.util.ArrayList;
/** /**
* Session Bean implementation class PlaceMapBean * Session Bean implementation class PlaceMapBean
...@@ -43,11 +43,20 @@ public class PlaceMapBean implements PlaceMapBeanLocal { ...@@ -43,11 +43,20 @@ public class PlaceMapBean implements PlaceMapBeanLocal {
@EJB @EJB
private PlaceFacade placeFacade; private PlaceFacade placeFacade;
@EJB @EJB
// private EventMapBean eventmapBean;
private EventMapFacade eventMapFacade; private EventMapFacade eventMapFacade;
@EJB @EJB
private UserFacade userFacade; private SecurityBeanLocal secubean;
@EJB
private UserBeanLocal userbean;
public void printPlaceMapToStream(OutputStream outputStream, String filetype, Event event, Integer mapId, List<Integer> placeIds) throws IOException, EjbPermissionDeniedException {
User user = userbean.getCurrentUser(event);
if (!userbean.hasPermission(Permission.TICKET_SALES, user, RolePermission.READ)) {
throw new EjbPermissionDeniedException(secubean, user, "User has no right to view placemap ( TICKET_SALES, READ )");
}
public void printPlaceMapToStream(OutputStream outputStream, String filetype, Event event, Integer mapId, Integer userId, List<Integer> placeIds) throws IOException {
long begin = new Date().getTime(); long begin = new Date().getTime();
Integer eventId = event.getId(); Integer eventId = event.getId();
...@@ -58,44 +67,48 @@ public class PlaceMapBean implements PlaceMapBeanLocal { ...@@ -58,44 +67,48 @@ public class PlaceMapBean implements PlaceMapBeanLocal {
for (Integer id : placeIds) { for (Integer id : placeIds) {
selectedPlaceList.add(placeFacade.find(eventId, id)); selectedPlaceList.add(placeFacade.find(eventId, id));
} }
logger.debug("Fetching map for event {}", event); if (logger.isDebugEnabled()) {
logger.info("Got mapid {}, time {}", mapId, new Date().getTime() - begin); logger.debug("Fetching map for event {}", event);
logger.debug("Got mapid {}, time {}", mapId, new Date().getTime() - begin);
}
logger.debug("SelectedPlaceList: {}, size {}", selectedPlaceList, selectedPlaceList.size()); logger.debug("SelectedPlaceList: {}, size {}", selectedPlaceList, selectedPlaceList.size());
if (selectedPlaceList.size() > 0) { if (selectedPlaceList.size() > 0) {
Place selPlace = selectedPlaceList.get(0); Place selPlace = selectedPlaceList.get(0);
logger.debug("Selected place: {}", selPlace); logger.debug("Selected place: {}", selPlace);
map = selPlace.getMap(); map = selPlace.getMap();
} else { } else {
logger.debug("Fetching from EventMapFacade with eventid {}, mapid {}", eventId,mapId); logger.debug("Fetching from EventMapFacade with eventid {}, mapid {}", eventId, mapId);
map = eventMapFacade.find(eventId, mapId); map = eventMapFacade.find(eventId, mapId);
} }
if (map == null) {
throw new EjbPermissionDeniedException(secubean, user, "Map not found with id: " + mapId + " and event id: " + event);
}
logger.debug("Got map object {}", map); logger.debug("Got map object {}", map);
List<Place> places = map.getPlaces(); List<Place> places = map.getPlaces();
logger.info("Places: from map {}, time {}", places.size(), new Date().getTime() - begin); logger.info("Places: from map {}, time {}", places.size(), new Date().getTime() - begin);
BufferedImage image = map.getMapWithPlaces(); BufferedImage image = map.getMapWithPlaces();
if (userId != null) { for (PlaceGroup uplacegroup : user.getPlaceGroups()) {
User user = userFacade.find(userId); for (Place uplace : uplacegroup.getPlaces()) {
if (uplace.getMap().equals(map)) {
if (user != null) { uplace.drawOwnedPlace(image);
for (PlaceGroup uplacegroup : user.getPlaceGroups()) {
for (Place uplace : uplacegroup.getPlaces()) {
if (uplace.getMap().equals(map)) {
uplace.drawOwnedPlace(image);
}
}
} }
} }
} }
logger.info("sometime {}", new Date().getTime() - begin);
logger.debug("sometime {}", new Date().getTime() - begin);
for (Place place : selectedPlaceList) { for (Place place : selectedPlaceList) {
place.drawSelectedPlace(image); place.drawSelectedPlace(image);
} }
logger.info("Prewrite {}", new Date().getTime() - begin);
logger.debug("Prewrite {}", new Date().getTime() - begin);
ImageIO.write(image, filetype, outputStream); ImageIO.write(image, filetype, outputStream);
logger.info("postwrite {}", new Date().getTime() - begin);
logger.debug("postwrite {}", new Date().getTime() - begin);
} }
...@@ -123,7 +136,6 @@ public class PlaceMapBean implements PlaceMapBeanLocal { ...@@ -123,7 +136,6 @@ public class PlaceMapBean implements PlaceMapBeanLocal {
} }
return "/PlaceMap" + parameters; return "/PlaceMap" + parameters;
// TODO: do something.
} }
public int selectablePlaceCount(User user, Event currentEvent) { public int selectablePlaceCount(User user, Event currentEvent) {
......
...@@ -40,9 +40,8 @@ public class RoleBean implements RoleBeanLocal { ...@@ -40,9 +40,8 @@ public class RoleBean implements RoleBeanLocal {
return roleFacade.findAll(); return roleFacade.findAll();
} }
public void mergeChanges(Role role) { public Role mergeChanges(Role role) {
return roleFacade.merge(role);
roleFacade.merge(role);
} }
public Role create(Role role) { public Role create(Role role) {
......
...@@ -70,8 +70,8 @@ public class UserBean implements UserBeanLocal { ...@@ -70,8 +70,8 @@ public class UserBean implements UserBeanLocal {
} }
@Override @Override
public void mergeChanges(User user) { public User mergeChanges(User user) {
userFacade.merge(user); return userFacade.merge(user);
} }
public User getUser(String nick) { public User getUser(String nick) {
...@@ -79,14 +79,18 @@ public class UserBean implements UserBeanLocal { ...@@ -79,14 +79,18 @@ public class UserBean implements UserBeanLocal {
} }
public boolean isCurrentUser(User user) { public boolean isCurrentUser(User user) {
return (context.getCallerPrincipal() == null || user == null) ? false: context.getCallerPrincipal().getName().equals(user.getNick()); return (context.getCallerPrincipal() == null || user == null) ? false : context.getCallerPrincipal().getName().equals(user.getNick());
} }
public User getLoggedInUserOrNull() {
@Override
public User getCurrentUser(Event event) {
Principal principal = context.getCallerPrincipal(); Principal principal = context.getCallerPrincipal();
User ret = getUser(principal.getName()); User ret = getUser(principal.getName());
return ret;
}
@Override
public User getCurrentUser(Event event) {
User ret = getLoggedInUserOrNull();
if (ret == null) { if (ret == null) {
ret = getDefaultUser(event); ret = getDefaultUser(event);
} }
...@@ -113,13 +117,12 @@ public class UserBean implements UserBeanLocal { ...@@ -113,13 +117,12 @@ public class UserBean implements UserBeanLocal {
if (user == null) { if (user == null) {
return false; return false;
} }
//TODO: FIX THIS!! really bad idea.... // TODO: FIX THIS!! really bad idea....
if(user.isSuperadmin()) if (user.isSuperadmin()) {
{
return true; return true;
} }
AccessRight expectedRight = accessRightBeanLocal.findOrCreate(target); AccessRight expectedRight = accessRightBeanLocal.findOrCreate(target);
User dbusr = userFacade.find(user.getId()); User dbusr = userFacade.find(user.getId());
...@@ -172,5 +175,4 @@ public class UserBean implements UserBeanLocal { ...@@ -172,5 +175,4 @@ public class UserBean implements UserBeanLocal {
} }
} }
...@@ -47,8 +47,8 @@ public abstract class GenericFacade<PK,T extends ModelInterface<PK>>{ ...@@ -47,8 +47,8 @@ public abstract class GenericFacade<PK,T extends ModelInterface<PK>>{
} }
public T find(PK id) { public T find(PK id) {
logger.debug("Fetching from em: {}, entityclass {}, id {}", new String[]{getEm().toString(), getEntityClass().toString(), id.toString()}); T ret = getEm().find(getEntityClass(), id);
return getEm().find(getEntityClass(), id); return ret;
} }
public List<T> findAll() { public List<T> findAll() {
......
...@@ -15,6 +15,6 @@ import javax.ejb.Local; ...@@ -15,6 +15,6 @@ import javax.ejb.Local;
@Local @Local
public interface PlaceBeanLocal { public interface PlaceBeanLocal {
public void mergeChanges(Place place); public Place mergeChanges(Place place);
} }
package fi.insomnia.bortal.beans; package fi.insomnia.bortal.beans;
import fi.insomnia.bortal.model.EventMap;
import fi.insomnia.bortal.model.Place;
import fi.insomnia.bortal.model.User;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
import java.util.List;
import javax.ejb.Local; import javax.ejb.Local;
import fi.insomnia.bortal.exceptions.EjbPermissionDeniedException;
import fi.insomnia.bortal.model.Event; import fi.insomnia.bortal.model.Event;
import java.util.List; import fi.insomnia.bortal.model.EventMap;
import fi.insomnia.bortal.model.Place;
import fi.insomnia.bortal.model.User;
@Local @Local
public interface PlaceMapBeanLocal { public interface PlaceMapBeanLocal {
void printPlaceMapToStream(OutputStream outputStream, String filetype, Event event, Integer mapId, Integer userId, List<Integer> placeIds) throws IOException; void printPlaceMapToStream(OutputStream outputStream, String filetype, Event event, Integer mapId, List<Integer> placeIds) throws EjbPermissionDeniedException,IOException;
public String getSelectPlaceMapUrl(EventMap activeMap, List<Place> selectedPlaces, User user); public String getSelectPlaceMapUrl(EventMap activeMap, List<Place> selectedPlaces, User user);
public int selectablePlaceCount(User user, Event currentEvent); public int selectablePlaceCount(User user, Event currentEvent);
......
...@@ -19,7 +19,7 @@ public interface RoleBeanLocal { ...@@ -19,7 +19,7 @@ public interface RoleBeanLocal {
public List<Role> listRoles(); public List<Role> listRoles();
public void mergeChanges(Role role); public Role mergeChanges(Role role);
public Role create(Role role); public Role create(Role role);
......
...@@ -19,7 +19,7 @@ public interface UserBeanLocal { ...@@ -19,7 +19,7 @@ public interface UserBeanLocal {
User getUser(String nick); User getUser(String nick);
void mergeChanges(User currentUser); User mergeChanges(User currentUser);
User getCurrentUser(Event event); User getCurrentUser(Event event);
......
...@@ -4,7 +4,6 @@ ...@@ -4,7 +4,6 @@
*/ */
package fi.insomnia.bortal.enums; package fi.insomnia.bortal.enums;
/** /**
* *
* @author tuukka * @author tuukka
...@@ -13,11 +12,14 @@ public enum Permission { ...@@ -13,11 +12,14 @@ public enum Permission {
PERMISSION("Description"), PERMISSION("Description"),
LOGIN("User can see loginbutton. (only defaultuser should have permission to that one)"), LOGIN("User can see loginbutton. (only defaultuser should have permission to that one)"),
USER_MANAGEMENT("User has right to manage users.... "); USER_MANAGEMENT("User has right to manage users.... "),
TICKET_SALES("User has right to view, and/or buy tickets"),
ROLE_MANAGEMENT("...");
private String description; private String description;
public static Permission getPermission(String name) { public static Permission getPermission(String name) {
if (name == null || name.isEmpty())
return null;
try { try {
return valueOf(name); return valueOf(name);
} catch (IllegalArgumentException x) { } catch (IllegalArgumentException x) {
......
...@@ -37,7 +37,7 @@ public class AccessRight implements ModelInterface<Integer> { ...@@ -37,7 +37,7 @@ public class AccessRight implements ModelInterface<Integer> {
*/ */
@Id @Id
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "access_right_id", nullable = false) @Column(name = "id", nullable = false)
private Integer id; private Integer id;
/** /**
......
...@@ -41,7 +41,7 @@ public class EventPk implements Serializable { ...@@ -41,7 +41,7 @@ public class EventPk implements Serializable {
} }
public int hashCode() { public int hashCode() {
return id.hashCode() + getEventId().hashCode(); return (id == null)?0:id.hashCode() + ((getEventId() == null)? 0:getEventId().hashCode());
} }
public boolean equals(Object obj) { public boolean equals(Object obj) {
......
...@@ -9,7 +9,6 @@ import static javax.persistence.TemporalType.TIMESTAMP; ...@@ -9,7 +9,6 @@ import static javax.persistence.TemporalType.TIMESTAMP;
import java.util.Calendar; import java.util.Calendar;
import javax.persistence.Column; import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.GeneratedValue; import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType; import javax.persistence.GenerationType;
......
...@@ -59,7 +59,7 @@ public class User implements ModelInterface<Integer> { ...@@ -59,7 +59,7 @@ public class User implements ModelInterface<Integer> {
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id; private Integer id;
@Column(name = "created", nullable = false, columnDefinition = "timestamptz default now()") @Column(name = "created", nullable = false) //, columnDefinition = "timestamptz default now()")
@Temporal(TemporalType.TIMESTAMP) @Temporal(TemporalType.TIMESTAMP)
private Calendar created = Calendar.getInstance(); private Calendar created = Calendar.getInstance();
......
...@@ -8,5 +8,6 @@ ...@@ -8,5 +8,6 @@
</attributes> </attributes>
</classpathentry> </classpathentry>
<classpathentry kind="con" path="org.eclipse.jst.server.core.container/com.sun.enterprise.jst.server.runtimeTarget/GlassFish v3 Java EE 6"/> <classpathentry kind="con" path="org.eclipse.jst.server.core.container/com.sun.enterprise.jst.server.runtimeTarget/GlassFish v3 Java EE 6"/>
<classpathentry exported="true" kind="lib" path="/LanBortal/EarContent/lib/commons-codec-1.4.jar" sourcepath="/Users/tuomari/Downloads/commons-codec-1.4/commons-codec-1.4-sources.jar"/>
<classpathentry kind="output" path="build/classes"/> <classpathentry kind="output" path="build/classes"/>
</classpath> </classpath>
#Sun Mar 21 07:07:17 EET 2010 #Sat Jun 12 05:34:28 EEST 2010
eclipse.preferences.version=1 eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=1.6 org.eclipse.jdt.core.compiler.compliance=1.6
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.source=1.6 org.eclipse.jdt.core.compiler.source=1.6
package fi.insomnia.bortal.utilities; package fi.insomnia.bortal.utilities;
import java.io.IOException;
import java.security.MessageDigest; import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.util.Random; import java.util.Random;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import com.sun.jersey.core.util.Base64;
...@@ -35,7 +34,8 @@ public class PasswordFunctions { ...@@ -35,7 +34,8 @@ public class PasswordFunctions {
String hashed = new String(algo.digest((password + salt).getBytes())); String hashed = new String(algo.digest((password + salt).getBytes()));
String both = hashed + salt; String both = hashed + salt;
String base64Str = Base64.encode(both.getBytes()).toString(); String base64Str = new String(new Base64().encode(both.getBytes()));
logger.debug("Encoded {} to {}", both, base64Str);
return base64Str; return base64Str;
} }
...@@ -45,7 +45,8 @@ public class PasswordFunctions { ...@@ -45,7 +45,8 @@ public class PasswordFunctions {
String oldBase64 = saltedPassword.substring("{SSHA}".length()); String oldBase64 = saltedPassword.substring("{SSHA}".length());
String decodedHashedAndSalt; String decodedHashedAndSalt;
decodedHashedAndSalt = new String(Base64.base64Decode(oldBase64)); decodedHashedAndSalt = new String(new Base64().decode(oldBase64.getBytes()));
logger.debug("Decoded Str {} to {}", oldBase64, decodedHashedAndSalt );
logger.debug("HashAndSalt: {}", decodedHashedAndSalt); logger.debug("HashAndSalt: {}", decodedHashedAndSalt);
String salt = decodedHashedAndSalt.substring(decodedHashedAndSalt.length() String salt = decodedHashedAndSalt.substring(decodedHashedAndSalt.length()
...@@ -74,8 +75,5 @@ public class PasswordFunctions { ...@@ -74,8 +75,5 @@ public class PasswordFunctions {
public static String createPassword(String password) {
// TODO Auto-generated method stub
return null;
}
} }
...@@ -41,6 +41,13 @@ ...@@ -41,6 +41,13 @@
</navigation-case> </navigation-case>
</navigation-rule> </navigation-rule>
<navigation-rule> <navigation-rule>
<from-view-id>/role/create.xhtml</from-view-id>
<navigation-case>
<from-outcome>roleCreated</from-outcome>
<to-view-id>/role/edit.xhtml</to-view-id>
</navigation-case>
</navigation-rule>
<navigation-rule>
<from-view-id>/resources/tools/user/list.xhtml</from-view-id> <from-view-id>/resources/tools/user/list.xhtml</from-view-id>
<navigation-case> <navigation-case>
<from-outcome>userEdit</from-outcome> <from-outcome>userEdit</from-outcome>
......
...@@ -18,7 +18,7 @@ ...@@ -18,7 +18,7 @@
<composite:implementation> <composite:implementation>
<h:form> <h:form>
<tools:canWrite target="roleManagement"> <tools:canWrite target="ROLE_MANAGEMENT">
<f:facet name="errorMessage"> <f:facet name="errorMessage">
<h:outputText value="#{i18n['nasty.user']}" /> <h:outputText value="#{i18n['nasty.user']}" />
</f:facet> </f:facet>
......
...@@ -19,7 +19,7 @@ ...@@ -19,7 +19,7 @@
<h:form> <h:form>
<tools:canWrite target="roleManagement"> <tools:canWrite target="ROLE_MANAGEMENT">
<f:facet name="errorMessage"> <f:facet name="errorMessage">
<h:outputText value="#{i18n['nasty.user']}" /> <h:outputText value="#{i18n['nasty.user']}" />
</f:facet> </f:facet>
......
...@@ -16,7 +16,7 @@ ...@@ -16,7 +16,7 @@
<h:outputText value="#{i18n['role.name']}" /><h:inputText value="#{roleView.role.name}" /> <h:outputText value="#{i18n['role.name']}" /><h:inputText value="#{roleView.role.name}" />
<h:selectManyListbox value="#{roleView.role.parents}"> <h:selectManyListbox value="#{roleView.role.parents}">
<f:selectItems value="#{roleView.possibleParents}" /> <f:selectItems var="par" itemLabel="${par.name}" value="#{roleView.possibleParents}" />
</h:selectManyListbox> </h:selectManyListbox>
</h:panelGrid> </h:panelGrid>
</ui:composition> </ui:composition>
......
...@@ -18,7 +18,7 @@ ...@@ -18,7 +18,7 @@
<h:form> <h:form>
<tools:canRead target="roleManagement"> <tools:canRead target="ROLE_MANAGEMENT">
<h:dataTable <h:dataTable
border="1" border="1"
id="user" id="user"
...@@ -36,7 +36,7 @@ ...@@ -36,7 +36,7 @@
</f:facet> </f:facet>
<h:outputText value="#{role.name}" /> <h:outputText value="#{role.name}" />
</h:column> </h:column>
<tools:canWrite target="roleManagement"> <tools:canWrite target="ROLE_MANAGEMENT">
<h:column> <h:column>
<f:facet name="header"> <f:facet name="header">
<h:outputText value="#{i18n['edit']}" /> <h:outputText value="#{i18n['edit']}" />
......
...@@ -33,7 +33,7 @@ import fi.insomnia.bortal.model.User; ...@@ -33,7 +33,7 @@ import fi.insomnia.bortal.model.User;
public class SessionHandler { public class SessionHandler {
private static final Logger logger = LoggerFactory.getLogger(SessionHandler.class); private static final Logger logger = LoggerFactory.getLogger(SessionHandler.class);
@EJB @EJB
private JaasBeanLocal handlerbean; private JaasBeanLocal handlerbean;
private User thisuser = null; private User thisuser = null;
...@@ -81,12 +81,20 @@ public class SessionHandler { ...@@ -81,12 +81,20 @@ public class SessionHandler {
return eventbean.getEventByHostname(hostname); return eventbean.getEventByHostname(hostname);
} }
public boolean hasPermission(String target, RolePermission permission) { public boolean hasPermission(Permission target, RolePermission permission) {
if (target == null || target.isEmpty()) { if (target == null) {
throw new RuntimeException("Empty target"); throw new RuntimeException("Empty target");
} }
return userbean.hasPermission(Permission.getPermission(target), getUser(), permission); return userbean.hasPermission(target, getUser(), permission);
}
public boolean hasPermission(String target, RolePermission permission) {
return hasPermission(Permission.getPermission(target), permission);
}
public boolean canWrite(Permission p) {
return hasPermission(p, RolePermission.WRITE);
} }
public boolean canWrite(String target) { public boolean canWrite(String target) {
...@@ -97,11 +105,20 @@ public class SessionHandler { ...@@ -97,11 +105,20 @@ public class SessionHandler {
return hasPermission(target, RolePermission.READ); return hasPermission(target, RolePermission.READ);
} }
public boolean canRead(Permission target) {
return hasPermission(target, RolePermission.READ);
}
public boolean canExecute(String target) { public boolean canExecute(String target) {
return hasPermission(target, RolePermission.EXECUTE); return hasPermission(target, RolePermission.EXECUTE);
} }
public boolean canExecute(Permission target) {
return hasPermission(target, RolePermission.EXECUTE);
}
private boolean impersonating = false; private boolean impersonating = false;
public void impersonateUser(User user) { public void impersonateUser(User user) {
if (user == null) { if (user == null) {
this.thisuser = getUser(); this.thisuser = getUser();
...@@ -118,11 +135,11 @@ public class SessionHandler { ...@@ -118,11 +135,11 @@ public class SessionHandler {
public User getUser() { public User getUser() {
boolean iscurruser = userbean.isCurrentUser(thisuser); boolean iscurruser = userbean.isCurrentUser(thisuser);
logger.debug("Current user {}", (thisuser == null)?"null":thisuser.getNick() ); logger.debug("Current user {}", (thisuser == null) ? "null" : thisuser.getNick());
if (thisuser == null || (!impersonating && !iscurruser)) { if (thisuser == null || (!impersonating && !iscurruser)) {
thisuser = userbean.getCurrentUser(getCurrentEvent()); thisuser = userbean.getCurrentUser(getCurrentEvent());
} }
return thisuser; return thisuser;
} }
......
...@@ -19,6 +19,8 @@ import org.slf4j.LoggerFactory; ...@@ -19,6 +19,8 @@ import org.slf4j.LoggerFactory;
import fi.insomnia.bortal.HostnameFilter; import fi.insomnia.bortal.HostnameFilter;
import fi.insomnia.bortal.beans.EventBeanLocal; import fi.insomnia.bortal.beans.EventBeanLocal;
import fi.insomnia.bortal.beans.PlaceMapBeanLocal; import fi.insomnia.bortal.beans.PlaceMapBeanLocal;
import fi.insomnia.bortal.exceptions.EjbPermissionDeniedException;
import fi.insomnia.bortal.exceptions.PermissionDeniedException;
import fi.insomnia.bortal.model.Event; import fi.insomnia.bortal.model.Event;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
...@@ -58,22 +60,23 @@ public class PlaceMap extends HttpServlet { ...@@ -58,22 +60,23 @@ public class PlaceMap extends HttpServlet {
*/ */
protected void processRequest(HttpServletRequest request, HttpServletResponse response) protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { throws ServletException, IOException {
logger.debug("Begin processing request"); logger.debug("Begin processing request");
response.setContentType("text/html;charset=UTF-8"); // response.setContentType("text/html;charset=UTF-8");
// PrintWriter out = response.getWriter(); // PrintWriter out = response.getWriter();
ServletOutputStream ostream = response.getOutputStream(); ServletOutputStream ostream = response.getOutputStream();
try { try {
//Integer placeId = getIntegerParameter(request, PARAMETER_SELECTED_PLACE_ID); // Integer placeId = getIntegerParameter(request,
// PARAMETER_SELECTED_PLACE_ID);
List<Integer> placeIds = getIntegerParameters(request, PARAMETER_SELECTED_PLACE_ID); List<Integer> placeIds = getIntegerParameters(request, PARAMETER_SELECTED_PLACE_ID);
Integer mapId = getIntegerParameter(request, PARAMETER_EVENT_MAP_ID); Integer mapId = getIntegerParameter(request, PARAMETER_EVENT_MAP_ID);
Integer userId = getIntegerParameter(request, PARAMETER_CURRENT_USER_ID); // Integer userId = getIntegerParameter(request,
// PARAMETER_CURRENT_USER_ID); Tämä saadaan beaneilta.
logger.debug("Mapid: {}", mapId); logger.debug("Mapid: {}", mapId);
response.setContentType("image/jpeg"); response.setContentType("image/jpeg");
placemapBean.printPlaceMapToStream(ostream, "jpeg", getEvent(request), mapId, userId, placeIds); placemapBean.printPlaceMapToStream(ostream, "jpeg", getEvent(request), mapId, placeIds);
/* /*
* TODO output your page here out.println("<html>"); * TODO output your page here out.println("<html>");
...@@ -83,6 +86,11 @@ public class PlaceMap extends HttpServlet { ...@@ -83,6 +86,11 @@ public class PlaceMap extends HttpServlet {
* out.println("<h1>Servlet PlaceMap at " + request.getContextPath * out.println("<h1>Servlet PlaceMap at " + request.getContextPath
* () + "</h1>"); out.println("</body>"); out.println("</html>"); * () + "</h1>"); out.println("</body>"); out.println("</html>");
*/ */
} catch (EjbPermissionDeniedException e) {
logger.debug("Permission deniedn. Returning SC_NOT_FOUND!");
response.setContentType("text/html;charset=UTF-8");
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
ostream.print("Permission denied!");
} finally { } finally {
ostream.close(); ostream.close();
} }
...@@ -115,7 +123,7 @@ public class PlaceMap extends HttpServlet { ...@@ -115,7 +123,7 @@ public class PlaceMap extends HttpServlet {
/*** /***
* Convert request parameter into integer * Convert request parameter into integer
* *
* @param request * @param request
* @param parameter * @param parameter
* @return * @return
...@@ -131,8 +139,6 @@ public class PlaceMap extends HttpServlet { ...@@ -131,8 +139,6 @@ public class PlaceMap extends HttpServlet {
String splitted[] = valueString.split(","); String splitted[] = valueString.split(",");
for (String value : splitted) { for (String value : splitted) {
try { try {
returnList.add(Integer.parseInt(value)); returnList.add(Integer.parseInt(value));
......
...@@ -23,7 +23,7 @@ import org.slf4j.Logger; ...@@ -23,7 +23,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
/** /**
* *
* @author tuukka * @author tuukka
*/ */
@ManagedBean(name = "mapView") @ManagedBean(name = "mapView")
...@@ -38,12 +38,12 @@ public class MapView { ...@@ -38,12 +38,12 @@ public class MapView {
@EJB @EJB
private PlaceBeanLocal placeBean; private PlaceBeanLocal placeBean;
@ManagedProperty("#{sessionHandler}") @ManagedProperty("#{sessionHandler}")
private SessionHandler sessionHandler; private SessionHandler sessionHandler;
private EventMap activeMap = null; private EventMap activeMap = null;
private List<Place> selectedPlaces = new ArrayList<Place>(); private List<Place> selectedPlaces = new ArrayList<Place>();
//private Place selectedPlace = null;
// private Place selectedPlace = null;
/** Creates a new instance of MapView */ /** Creates a new instance of MapView */
public MapView() { public MapView() {
...@@ -62,33 +62,33 @@ public class MapView { ...@@ -62,33 +62,33 @@ public class MapView {
if (selectedPlaces.contains(place)) { if (selectedPlaces.contains(place)) {
selectedPlaces.remove(place); selectedPlaces.remove(place);
place.setReserved(false); place.setReserved(false);
placeBean.mergeChanges(place);
} else { } else {
selectedPlaces.add(place); selectedPlaces.add(place);
place.setReserved(true); place.setReserved(true);
placeBean.mergeChanges(place);
} }
place = placeBean.mergeChanges(place);
} }
logger.debug("Done calling PlaceSelectActionListener"); logger.debug("Done calling PlaceSelectActionListener");
} }
public String getSelectPlaceMapUrl() { public String getSelectPlaceMapUrl() {
User user = sessionHandler.getUser(); User user = sessionHandler.getUser();
logger.debug("Select map got user: {}", user ); logger.debug("Select map got user: {}", user);
EventMap map = getActiveMap(); EventMap map = getActiveMap();
logger.debug("Select map got active map: {}", map ); logger.debug("Select map got active map: {}", map);
if (map == null) { if (map == null) {
return ""; return "";
} }
String ret = placeMapBean.getSelectPlaceMapUrl(getActiveMap(), selectedPlaces, user); String ret = placeMapBean.getSelectPlaceMapUrl(getActiveMap(), selectedPlaces, user);
logger.debug("Returning placemapUrl: {}", ret); logger.debug("Returning placemapUrl: {}", ret);
return ret; return ret;
} }
/** /**
* @return the activeMap, if it's not setted, return events first map. If this event does not have map, return null. * @return the activeMap, if it's not setted, return events first map. If
* this event does not have map, return null.
*/ */
public EventMap getActiveMap() { public EventMap getActiveMap() {
...@@ -103,7 +103,8 @@ public class MapView { ...@@ -103,7 +103,8 @@ public class MapView {
} }
/** /**
* @param activeMap the activeMap to set * @param activeMap
* the activeMap to set
*/ */
public void setActiveMap(EventMap activeMap) { public void setActiveMap(EventMap activeMap) {
this.activeMap = activeMap; this.activeMap = activeMap;
...@@ -117,7 +118,8 @@ public class MapView { ...@@ -117,7 +118,8 @@ public class MapView {
} }
/** /**
* @param sessionHandler the sessionHandler to set * @param sessionHandler
* the sessionHandler to set
*/ */
public void setSessionHandler(SessionHandler sessionHandler) { public void setSessionHandler(SessionHandler sessionHandler) {
this.sessionHandler = sessionHandler; this.sessionHandler = sessionHandler;
...@@ -126,6 +128,6 @@ public class MapView { ...@@ -126,6 +128,6 @@ public class MapView {
public String placeLeftToSelect() { public String placeLeftToSelect() {
int totalPlaces = placeMapBean.selectablePlaceCount(sessionHandler.getUser(), sessionHandler.getCurrentEvent()); int totalPlaces = placeMapBean.selectablePlaceCount(sessionHandler.getUser(), sessionHandler.getCurrentEvent());
return (totalPlaces - selectedPlaces.size())+""; return (totalPlaces - selectedPlaces.size()) + "";
} }
} }
...@@ -6,6 +6,7 @@ package fi.insomnia.bortal.view; ...@@ -6,6 +6,7 @@ package fi.insomnia.bortal.view;
import fi.insomnia.bortal.beans.RoleBeanLocal; import fi.insomnia.bortal.beans.RoleBeanLocal;
import fi.insomnia.bortal.beans.SecurityBeanLocal; import fi.insomnia.bortal.beans.SecurityBeanLocal;
import fi.insomnia.bortal.enums.Permission;
import fi.insomnia.bortal.exceptions.PermissionDeniedException; import fi.insomnia.bortal.exceptions.PermissionDeniedException;
import fi.insomnia.bortal.handler.SessionHandler; import fi.insomnia.bortal.handler.SessionHandler;
import fi.insomnia.bortal.model.Role; import fi.insomnia.bortal.model.Role;
...@@ -36,7 +37,7 @@ public class RoleView { ...@@ -36,7 +37,7 @@ public class RoleView {
@EJB @EJB
private SecurityBeanLocal securitybean; private SecurityBeanLocal securitybean;
private Role role = new Role(); private Role role;
DataModel<Role> items; DataModel<Role> items;
public DataModel<Role> getRoles() { public DataModel<Role> getRoles() {
...@@ -48,12 +49,12 @@ public class RoleView { ...@@ -48,12 +49,12 @@ public class RoleView {
public String save() { public String save() {
if (!sessionhandler.canWrite("roleManagement")) { if (!sessionhandler.canWrite(Permission.ROLE_MANAGEMENT)) {
// Give message to administration what happened here. // Give message to administration what happened here.
throw new PermissionDeniedException(securitybean, getSessionhandler().getUser(), "User " + getSessionhandler().getUser() + " does not have permission to modify role!"); throw new PermissionDeniedException(securitybean, getSessionhandler().getUser(), "User " + getSessionhandler().getUser() + " does not have permission to modify role!");
} }
roleBean.mergeChanges(role); role = roleBean.mergeChanges(getRole());
return "roleSaved"; return "roleSaved";
} }
...@@ -61,12 +62,15 @@ public class RoleView { ...@@ -61,12 +62,15 @@ public class RoleView {
public String create() { public String create() {
if (!sessionhandler.canWrite("roleManagement")) { if (!sessionhandler.canWrite(Permission.ROLE_MANAGEMENT)) {
// Give message to administration what happened here. // Give message to administration what happened here.
throw new PermissionDeniedException(securitybean, getSessionhandler().getUser(), "User " + getSessionhandler().getUser() + " does not have permission to create role!"); throw new PermissionDeniedException(securitybean, getSessionhandler().getUser(), "User " + getSessionhandler().getUser() + " does not have permission to create role!");
} }
if(getRole().getEvent() == null)
{
}
role = roleBean.create(role); role = roleBean.create(getRole());
return "roleCreated"; return "roleCreated";
} }
...@@ -85,6 +89,10 @@ public class RoleView { ...@@ -85,6 +89,10 @@ public class RoleView {
* @return the role * @return the role
*/ */
public Role getRole() { public Role getRole() {
if(role == null)
{
role = new Role(sessionhandler.getCurrentEvent());
}
return role; return role;
} }
...@@ -113,6 +121,6 @@ public class RoleView { ...@@ -113,6 +121,6 @@ public class RoleView {
* @return the possibleParents * @return the possibleParents
*/ */
public List<Role> getPossibleParents() { public List<Role> getPossibleParents() {
return roleBean.getPossibleParents(role); return roleBean.getPossibleParents(getRole());
} }
} }
...@@ -70,7 +70,7 @@ public class UserView { ...@@ -70,7 +70,7 @@ public class UserView {
} }
public String saveUser() { public String saveUser() {
userBean.mergeChanges(getUser()); setUser( userBean.mergeChanges(getUser()));
return "userSave"; return "userSave";
} }
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!