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.seam21.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.Collections;
028    import java.util.List;
029    import java.util.Map;
030    
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.core.Events;
039    import org.jboss.seam.international.StatusMessage;
040    import org.jboss.seam.international.StatusMessages;
041    import org.jboss.seam.security.AuthorizationException;
042    import org.jboss.seam.security.Identity;
043    import org.jboss.seam.security.NotLoggedInException;
044    
045    /**
046     * @author Venkat DANDA
047     */
048    public class Seam21SecurityService extends AbstractSecurityService {
049    
050            private static final Logger log = Logger.getLogger(Seam21SecurityService.class);
051            
052        public void configure(Map<String, String> params) {
053        }
054    
055        public void login(Object credentials) throws SecurityServiceException {
056            String[] decoded = decodeBase64Credentials(credentials);
057            
058            Contexts.getSessionContext().set("org.granite.seam.login", Boolean.TRUE);
059            
060            Identity identity = Identity.instance();
061            
062            // Unauthenticate if username has changed (otherwise the previous session/principal is reused)
063            if (identity.isLoggedIn(false) && !decoded[0].equals(identity.getUsername())) {
064                    try {
065                            Method method = identity.getClass().getDeclaredMethod("unAuthenticate");
066                            method.setAccessible(true);
067                            method.invoke(identity);
068                    } catch (Exception e) {
069                            log.error(e, "Could not call unAuthenticate method on: %s", identity.getClass());
070                    }
071            }
072    
073            identity.setUsername(decoded[0]);
074            identity.setPassword(decoded[1]);
075            try {
076                identity.authenticate();
077            }
078            catch (LoginException e) {
079                    // Force add of login error messages
080                    try {
081                            Method method = identity.getClass().getMethod("getCredentials");
082                            Object cred = method.invoke(identity);
083                            method = cred.getClass().getMethod("invalidate");
084                            method.invoke(cred);
085                    } catch (Exception f) {
086                            log.error(f, "Could not call getCredentials().invalidate() method on: %s", identity.getClass());
087                    }
088                
089                if (Events.exists()) 
090                    Events.instance().raiseEvent("org.jboss.seam.security.loginFailed", e);
091                
092                throw SecurityServiceException.newInvalidCredentialsException("User authentication failed");
093            }
094        }
095    
096        public Object authorize(AbstractSecurityContext context) throws Exception {
097            startAuthorization(context);
098            
099            if (context.getDestination().isSecured()) {
100    
101                Identity identity = Identity.instance();
102                if (!identity.isLoggedIn()) {
103                    // TODO: Session expiration detection...
104                    // throw SecurityServiceException.newSessionExpiredException("Session expired");
105                    throw SecurityServiceException.newNotLoggedInException("User not logged in");
106                }
107    
108                boolean accessDenied = true;
109                for (String role : context.getDestination().getRoles()) {
110                    if (identity.hasRole(role)) {
111                        accessDenied = false;
112                        break;
113                    }
114                }
115                if (accessDenied)
116                    throw SecurityServiceException.newAccessDeniedException("User not in required role");
117            }
118    
119            try {
120                return endAuthorization(context);
121            } catch (InvocationTargetException e) {
122                for (Throwable t = e; t != null; t = t.getCause()) {
123                    // If destination is not secured...
124                    if (t instanceof NotLoggedInException)
125                        throw SecurityServiceException.newNotLoggedInException("User not logged in");
126                    // Don't create a dependency to javax.ejb in SecurityService...
127                    if (t instanceof SecurityException ||
128                        t instanceof AuthorizationException ||
129                        "javax.ejb.EJBAccessException".equals(t.getClass().getName()))
130                        throw SecurityServiceException.newAccessDeniedException(t.getMessage());
131                }
132                throw e;
133            }
134        }
135    
136        public void logout() throws SecurityServiceException {
137            // if (Identity.instance().isLoggedIn(false)) ?
138            Identity.instance().logout();
139        }
140        
141        
142        @Override
143        @SuppressWarnings("unchecked")
144        public void handleSecurityException(SecurityServiceException e) {
145            List<StatusMessage> messages = Collections.emptyList();
146            
147            try {
148                StatusMessages statusMessages = StatusMessages.instance();
149                if (statusMessages != null) {
150                    // Execute and get the messages (once again reflection hack to use protected methods) 
151                    Method m = StatusMessages.class.getDeclaredMethod("doRunTasks");
152                    m.setAccessible(true);
153                    m.invoke(statusMessages);
154                    
155                    Method m2 = StatusMessages.class.getDeclaredMethod("getMessages");
156                    m2.setAccessible(true);
157                    messages = (List<StatusMessage>)m2.invoke(statusMessages);
158                }
159            }
160            catch (Exception se) {
161                log.error("Could not get status messages", se);
162            }
163            
164            List<Object> tideMessages = new ArrayList<Object>(messages.size());
165            
166            try {
167                Class<?> c = Thread.currentThread().getContextClassLoader().loadClass("org.granite.tide.TideMessage");
168                Constructor<?> co = c.getConstructor(String.class, String.class, String.class);
169                
170                for (StatusMessage fm : messages) {
171                    String severity = null;
172                    if (fm.getSeverity() == StatusMessage.Severity.INFO)
173                        severity = "INFO";
174                    else if (fm.getSeverity() == StatusMessage.Severity.WARN)
175                        severity = "WARNING";
176                    else if (fm.getSeverity() == StatusMessage.Severity.ERROR)
177                        severity = "ERROR";
178                    else if (fm.getSeverity() == StatusMessage.Severity.FATAL)
179                        severity = "FATAL";
180                    
181                    tideMessages.add(co.newInstance(severity, fm.getSummary(), fm.getDetail()));
182                }
183                
184                e.getExtendedData().put("messages", tideMessages);
185            }
186            catch (Throwable t) {
187                e.getExtendedData().put("messages", tideMessages);
188            }
189        }
190    }