001 /*
002 GRANITE DATA SERVICES
003 Copyright (C) 2011 GRANITE DATA SERVICES S.A.S.
004
005 This file is part of Granite Data Services.
006
007 Granite Data Services is free software; you can redistribute it and/or modify
008 it under the terms of the GNU Library General Public License as published by
009 the Free Software Foundation; either version 2 of the License, or (at your
010 option) any later version.
011
012 Granite Data Services is distributed in the hope that it will be useful, but
013 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
014 FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License
015 for more details.
016
017 You should have received a copy of the GNU Library General Public License
018 along with this library; if not, see <http://www.gnu.org/licenses/>.
019 */
020
021 package org.granite.seam.security;
022
023 import java.lang.reflect.Constructor;
024 import java.lang.reflect.InvocationTargetException;
025 import java.lang.reflect.Method;
026 import java.util.ArrayList;
027 import java.util.List;
028 import java.util.Map;
029
030 import javax.faces.application.FacesMessage;
031 import javax.security.auth.login.LoginException;
032
033 import org.granite.logging.Logger;
034 import org.granite.messaging.service.security.AbstractSecurityContext;
035 import org.granite.messaging.service.security.AbstractSecurityService;
036 import org.granite.messaging.service.security.SecurityServiceException;
037 import org.jboss.seam.contexts.Contexts;
038 import org.jboss.seam.faces.FacesMessages;
039 import org.jboss.seam.security.AuthorizationException;
040 import org.jboss.seam.security.Identity;
041 import org.jboss.seam.security.NotLoggedInException;
042
043 /**
044 * @author Venkat DANDA
045 */
046 public class SeamSecurityService extends AbstractSecurityService {
047
048 private static final Logger log = Logger.getLogger(SeamSecurityService.class);
049
050 public void configure(Map<String, String> params) {
051 }
052
053 public void login(Object credentials) throws SecurityServiceException {
054 String[] decoded = decodeBase64Credentials(credentials);
055
056 Contexts.getSessionContext().set("org.granite.seam.login", Boolean.TRUE);
057
058 Identity identity = Identity.instance();
059
060 // Unauthenticate if username has changed (otherwise the previous session/principal is reused)
061 if (identity.isLoggedIn(false) && !decoded[0].equals(identity.getUsername())) {
062 try {
063 Method method = identity.getClass().getDeclaredMethod("unAuthenticate");
064 method.setAccessible(true);
065 method.invoke(identity);
066 } catch (Exception e) {
067 log.error(e, "Could not call unAuthenticate method on: %s", identity.getClass());
068 }
069 }
070
071 identity.setUsername(decoded[0]);
072 identity.setPassword(decoded[1]);
073 try {
074 identity.authenticate();
075 }
076 catch (LoginException e) {
077 identity.login(); // Force add of login error messages
078
079 handleAuthenticationExceptions(e);
080 }
081 }
082
083 protected void handleAuthenticationExceptions(LoginException e) {
084 throw SecurityServiceException.newInvalidCredentialsException("User authentication failed", e.getMessage());
085 }
086
087 public Object authorize(AbstractSecurityContext context) throws Exception {
088 startAuthorization(context);
089
090 if (context.getDestination().isSecured()) {
091
092 Identity identity = Identity.instance();
093 if (!identity.isLoggedIn()) {
094 // TODO: Session expiration detection...
095 // throw SecurityServiceException.newSessionExpiredException("Session expired");
096 throw SecurityServiceException.newNotLoggedInException("User not logged in");
097 }
098
099 boolean accessDenied = true;
100 for (String role : context.getDestination().getRoles()) {
101 if (identity.hasRole(role)) {
102 accessDenied = false;
103 break;
104 }
105 }
106 if (accessDenied)
107 throw SecurityServiceException.newAccessDeniedException("User not in required role");
108 }
109
110 try {
111 return endAuthorization(context);
112 } catch (InvocationTargetException e) {
113 for (Throwable t = e; t != null; t = t.getCause()) {
114 // If destination is not secured...
115 if (t instanceof NotLoggedInException)
116 throw SecurityServiceException.newNotLoggedInException("User not logged in");
117 // Don't create a dependency to javax.ejb in SecurityService...
118 if (t instanceof SecurityException ||
119 t instanceof AuthorizationException ||
120 "javax.ejb.EJBAccessException".equals(t.getClass().getName()))
121 throw SecurityServiceException.newAccessDeniedException(t.getMessage());
122 }
123 throw e;
124 }
125 }
126
127 public void logout() throws SecurityServiceException {
128 // if (Identity.instance().isLoggedIn(false)) ?
129 Identity.instance().logout();
130 }
131
132
133 @Override
134 public void handleSecurityException(SecurityServiceException e) {
135 // Add messages
136 //Prepare for the messages. First step is convert the tasks to Seam FacesMessages
137 FacesMessages.afterPhase();
138 //Second step is add the Seam FacesMessages to JSF FacesContext Messages
139 FacesMessages.instance().beforeRenderResponse();
140
141 List<FacesMessage> facesMessages = FacesMessages.instance().getCurrentMessages();
142
143 try {
144 Class<?> c = Thread.currentThread().getContextClassLoader().loadClass("org.granite.tide.TideMessage");
145 Constructor<?> co = c.getConstructor(String.class, String.class, String.class);
146
147 List<Object> tideMessages = new ArrayList<Object>(facesMessages.size());
148 for (FacesMessage fm : facesMessages) {
149 String severity = null;
150 if (fm.getSeverity() == FacesMessage.SEVERITY_INFO)
151 severity = "INFO";
152 else if (fm.getSeverity() == FacesMessage.SEVERITY_WARN)
153 severity = "WARNING";
154 else if (fm.getSeverity() == FacesMessage.SEVERITY_ERROR)
155 severity = "ERROR";
156 else if (fm.getSeverity() == FacesMessage.SEVERITY_FATAL)
157 severity = "FATAL";
158
159 tideMessages.add(co.newInstance(severity, fm.getSummary(), fm.getDetail()));
160 }
161
162 e.getExtendedData().put("messages", tideMessages);
163 }
164 catch (Throwable t) {
165 e.getExtendedData().put("messages", facesMessages);
166 }
167 }
168 }