| /** |
| * |
| * Copyright (c) 2011, 2016 - Loetz GmbH&Co.KG (69115 Heidelberg, Germany) |
| * |
| * All rights reserved. This program and the accompanying materials |
| * are made available under the terms of the Eclipse Public License 2.0 |
| * which accompanies this distribution, and is available at |
| * https://www.eclipse.org/legal/epl-2.0/ |
| * |
| * SPDX-License-Identifier: EPL-2.0 |
| * |
| * Contributors: |
| * Christophe Loetz (Loetz GmbH&Co.KG) - initial implementation |
| */ |
| package org.eclipse.osbp.authentication.vaadin; |
| |
| import com.google.inject.Provider; |
| import com.vaadin.server.VaadinSession; |
| |
| import org.apache.shiro.subject.Subject; |
| import org.slf4j.Logger; |
| import org.slf4j.LoggerFactory; |
| |
| /** |
| * Use this instead of using {@link org.apache.shiro.SecurityUtils#getSubject()} directly, to ensure that the Subject instance remains |
| * consistent for the duration of a Vaadin Session. |
| * |
| * depends on ideas of David Sowerby |
| */ |
| public class SubjectProvider implements Provider<Subject> { |
| |
| /** The log. */ |
| private static Logger log = LoggerFactory.getLogger(SubjectProvider.class); |
| |
| /** The session provider. */ |
| private final VaadinSessionProvider sessionProvider; |
| |
| /** |
| * Instantiates a new subject provider. |
| * |
| * @param sessionProvider the session provider |
| */ |
| public SubjectProvider(VaadinSessionProvider sessionProvider) { |
| super(); |
| this.sessionProvider = sessionProvider; |
| } |
| |
| /* (non-Javadoc) |
| * @see com.google.inject.Provider#get() |
| */ |
| @Override |
| public synchronized Subject get() { |
| Subject subject = null; |
| try { |
| VaadinSession session = sessionProvider.get(); |
| subject = session.getAttribute(Subject.class); |
| if (subject == null) { |
| log.debug("VaadinSession is valid, but does not have a stored Subject, creating a new Subject"); |
| subject = new Subject.Builder().buildSubject(); |
| log.debug("storing Subject instance in VaadinSession"); |
| session.setAttribute(Subject.class, subject); |
| } |
| return subject; |
| |
| } catch (IllegalStateException ise) { |
| // this may happen in background threads which are not using a session, or during testing |
| log.debug("There is no VaadinSession, creating a new Subject"); |
| subject = new Subject.Builder().buildSubject(); |
| return subject; |
| } |
| } |
| } |