001/*
002 * Licensed under the Apache License, Version 2.0 (the "License");
003 * you may not use this file except in compliance with the License.
004 * You may obtain a copy of the License at
005 *
006 *      http://www.apache.org/licenses/LICENSE-2.0
007 *
008 * Unless required by applicable law or agreed to in writing, software
009 * distributed under the License is distributed on an "AS IS" BASIS,
010 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
011 * See the License for the specific language governing permissions and
012 * limitations under the License.
013 */
014package org.apache.shiro.ee.filters;
015
016import static org.apache.shiro.ee.filters.FormAuthenticationFilter.LOGIN_PREDICATE_ATTR_NAME;
017import static org.apache.shiro.ee.filters.FormAuthenticationFilter.LOGIN_WAITTIME_ATTR_NAME;
018import static org.apache.shiro.ee.filters.FormResubmitSupport.FORM_IS_RESUBMITTED;
019import static org.apache.shiro.ee.filters.FormResubmitSupport.SESSION_EXPIRED_PARAMETER;
020import static org.apache.shiro.ee.filters.LogoutFilter.LOGOUT_PREDICATE_ATTR_NAME;
021import static org.apache.shiro.ee.listeners.EnvironmentLoaderListener.isFormResubmitDisabled;
022import java.util.concurrent.TimeUnit;
023import javax.enterprise.context.ApplicationScoped;
024import javax.inject.Named;
025import javax.servlet.http.HttpServletRequest;
026import javax.servlet.http.HttpServletResponse;
027import lombok.AccessLevel;
028import lombok.NoArgsConstructor;
029import lombok.SneakyThrows;
030import lombok.extern.slf4j.Slf4j;
031import org.apache.shiro.SecurityUtils;
032import org.apache.shiro.authc.AuthenticationException;
033import org.apache.shiro.authc.UsernamePasswordToken;
034import static org.apache.shiro.web.filter.authc.FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME;
035import static org.omnifaces.exceptionhandler.ViewExpiredExceptionHandler.wasViewExpired;
036import org.omnifaces.util.Faces;
037
038/**
039 * Methods to redirect to saved requests upon logout
040 * functionality includes saving a previous form state and resubmitting
041 * if the form times out
042 */
043@Slf4j
044@NoArgsConstructor(access = AccessLevel.PRIVATE)
045@SuppressWarnings("HideUtilityClassConstructor")
046public class Forms {
047    /**
048     * JSF access points
049     */
050    @Named("authc")
051    @ApplicationScoped
052    public static class AuthenticationMethods {
053        /**
054         * let Shiro filter handle the login,
055         * this method should only get called if login fails
056         * login wait time is handled by Shiro configuration
057         */
058        public void login() {
059            if (isLoginFailure()) {
060                loginFailed();
061            } else if (!redirectIfLoggedIn()) {
062                throw new IllegalStateException("Not enough context to log in, need username / password");
063            }
064        }
065
066        /**
067         * manual login, zero wait time
068         *
069         * @param username
070         * @param password
071         */
072        public void login(String username, String password) {
073            login(username, password, false);
074        }
075
076        /**
077         * manual login with timeout
078         *
079         * @param username
080         * @param password
081         * @param rememberMe
082         */
083        public void login(String username, String password, boolean rememberMe) {
084            Forms.login(username, password, rememberMe);
085        }
086
087        public void logout() {
088            Forms.logout();
089        }
090
091        public boolean isLoggedIn() {
092            return Forms.isLoggedIn();
093        }
094
095        public boolean redirectIfLoggedIn() {
096            return redirectIfLoggedIn("/");
097        }
098
099        public boolean redirectIfLoggedIn(String view) {
100            if (isLoggedIn()) {
101                redirectToView(Faces.getRequestAttribute(LOGOUT_PREDICATE_ATTR_NAME), view);
102                return true;
103            } else {
104                return false;
105            }
106        }
107
108        public boolean isSessionExpired() {
109            return Forms.isSessionExpired();
110        }
111
112        public boolean isLoginFailure() {
113            return Faces.getRequestAttribute(DEFAULT_ERROR_KEY_ATTRIBUTE_NAME) != null
114                    || Faces.getFlashAttribute(DEFAULT_ERROR_KEY_ATTRIBUTE_NAME) != null;
115        }
116    }
117
118    @FunctionalInterface
119    public interface FallbackPredicate {
120        boolean useFallback(String path, HttpServletRequest request);
121    }
122
123    /**
124     * Jakarta Faces variant
125     * redirect to saved request, possibly resubmitting an existing form
126     * the saved request is via a cookie
127     *
128     * @param useFallbackPath
129     * @param fallbackPath
130     */
131    public static void redirectToSaved(FallbackPredicate useFallbackPath, String fallbackPath) {
132        FormResubmitSupport.redirectToSaved(Faces.getRequest(), Faces.getResponse(), useFallbackPath, fallbackPath,
133                !isFormResubmitDisabled(Faces.getRequest().getServletContext()));
134    }
135
136    /**
137     * Jakarta Faces variant
138     * redirects to current view after a form submit, or a logout, for example
139     */
140    public static void redirectToView() {
141        FormResubmitSupport.redirectToView(Faces.getRequest(), Faces.getResponse());
142    }
143
144    public static void redirectToView(FallbackPredicate useFallbackPath, String fallbackPath) {
145        FormResubmitSupport.redirectToView(Faces.getRequest(), Faces.getResponse(), useFallbackPath, fallbackPath);
146    }
147
148    /**
149     * manually login, used via {@link PassThruAuthenticationFilter}
150     * @param username
151     * @param password
152     * @param rememberMe
153     */
154    @SneakyThrows(InterruptedException.class)
155    public static void login(String username, String password, boolean rememberMe) {
156        try {
157            SecurityUtils.getSubject().login(new UsernamePasswordToken(username, password, rememberMe));
158            redirectToSaved(Faces.getRequestAttribute(LOGIN_PREDICATE_ATTR_NAME), "/");
159        } catch (AuthenticationException e) {
160            Faces.setFlashAttribute(DEFAULT_ERROR_KEY_ATTRIBUTE_NAME, e);
161            int loginFailedWaitTime = Faces.getRequestAttribute(LOGIN_WAITTIME_ATTR_NAME);
162            if (loginFailedWaitTime != 0) {
163                TimeUnit.SECONDS.sleep(loginFailedWaitTime);
164            }
165            redirectToView();
166        }
167    }
168
169    /**
170     * JSF login failure method
171     */
172    public static void loginFailed() {
173        Faces.setFlashAttribute(DEFAULT_ERROR_KEY_ATTRIBUTE_NAME, Faces.getRequestAttribute(DEFAULT_ERROR_KEY_ATTRIBUTE_NAME));
174        Faces.removeRequestAttribute(DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);
175        redirectToView();
176    }
177
178    public static void logout() {
179        Forms.logout(Faces.getRequestAttribute(LOGOUT_PREDICATE_ATTR_NAME), "");
180    }
181
182    /**
183     * Faces variant
184     * @param useFallback
185     * @param fallbackPath
186     */
187    public static void logout(FallbackPredicate useFallback, String fallbackPath) {
188        logout(Faces.getRequest(), Faces.getResponse(), useFallback, fallbackPath);
189    }
190
191    /**
192     * makes sure that there is no double-logout
193     *
194     * @param request
195     * @param response
196     * @param useFallback
197     * @param fallbackPath
198     */
199    public static void logout(HttpServletRequest request, HttpServletResponse response,
200            FallbackPredicate useFallback, String fallbackPath) {
201        if (!Boolean.TRUE.toString().equals(request.getHeader(FORM_IS_RESUBMITTED))) {
202            SecurityUtils.getSubject().logout();
203            FormResubmitSupport.redirectToView(request, response, useFallback, fallbackPath);
204        }
205    }
206
207    public static boolean isLoggedIn() {
208        var subject = SecurityUtils.getSubject();
209        return subject.isAuthenticated() || subject.isRemembered();
210    }
211
212    public static boolean isSessionExpired() {
213        return wasViewExpired() || Boolean.parseBoolean(Faces.getRequestParameter(SESSION_EXPIRED_PARAMETER));
214    }
215}