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                throw SecurityServiceException.newInvalidCredentialsException("User authentication failed");
080            }
081        }
082    
083        public Object authorize(AbstractSecurityContext context) throws Exception {
084            startAuthorization(context);
085            
086            if (context.getDestination().isSecured()) {
087    
088                Identity identity = Identity.instance();
089                if (!identity.isLoggedIn()) {
090                    // TODO: Session expiration detection...
091                    // throw SecurityServiceException.newSessionExpiredException("Session expired");
092                    throw SecurityServiceException.newNotLoggedInException("User not logged in");
093                }
094    
095                boolean accessDenied = true;
096                for (String role : context.getDestination().getRoles()) {
097                    if (identity.hasRole(role)) {
098                        accessDenied = false;
099                        break;
100                    }
101                }
102                if (accessDenied)
103                    throw SecurityServiceException.newAccessDeniedException("User not in required role");
104            }
105    
106            try {
107                return endAuthorization(context);
108            } catch (InvocationTargetException e) {
109                for (Throwable t = e; t != null; t = t.getCause()) {
110                    // If destination is not secured...
111                    if (t instanceof NotLoggedInException)
112                        throw SecurityServiceException.newNotLoggedInException("User not logged in");
113                    // Don't create a dependency to javax.ejb in SecurityService...
114                    if (t instanceof SecurityException ||
115                        t instanceof AuthorizationException ||
116                        "javax.ejb.EJBAccessException".equals(t.getClass().getName()))
117                        throw SecurityServiceException.newAccessDeniedException(t.getMessage());
118                }
119                throw e;
120            }
121        }
122    
123        public void logout() throws SecurityServiceException {
124            // if (Identity.instance().isLoggedIn(false)) ?
125            Identity.instance().logout();
126        }
127        
128        
129        @Override
130        public void handleSecurityException(SecurityServiceException e) {
131            // Add messages
132            //Prepare for the messages. First step is convert the tasks to Seam FacesMessages
133            FacesMessages.afterPhase();
134            //Second step is add the Seam FacesMessages to JSF FacesContext Messages
135            FacesMessages.instance().beforeRenderResponse();
136            
137            List<FacesMessage> facesMessages = FacesMessages.instance().getCurrentMessages();
138            
139            try {
140                Class<?> c = Thread.currentThread().getContextClassLoader().loadClass("org.granite.tide.TideMessage");
141                Constructor<?> co = c.getConstructor(String.class, String.class, String.class);
142                
143                List<Object> tideMessages = new ArrayList<Object>(facesMessages.size());
144                for (FacesMessage fm : facesMessages) {
145                    String severity = null;
146                    if (fm.getSeverity() == FacesMessage.SEVERITY_INFO)
147                        severity = "INFO";
148                    else if (fm.getSeverity() == FacesMessage.SEVERITY_WARN)
149                        severity = "WARNING";
150                    else if (fm.getSeverity() == FacesMessage.SEVERITY_ERROR)
151                        severity = "ERROR";
152                    else if (fm.getSeverity() == FacesMessage.SEVERITY_FATAL)
153                        severity = "FATAL";
154                    
155                    tideMessages.add(co.newInstance(severity, fm.getSummary(), fm.getDetail()));
156                }
157                
158                e.getExtendedData().put("messages", tideMessages);
159            }
160            catch (Throwable t) {
161                e.getExtendedData().put("messages", facesMessages);
162            }
163        }
164    }