001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing,
013 * software distributed under the License is distributed on an
014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 * KIND, either express or implied.  See the License for the
016 * specific language governing permissions and limitations
017 * under the License.
018 */
019package org.apache.shiro.guice;
020
021import com.google.inject.Key;
022import com.google.inject.OutOfScopeException;
023import com.google.inject.Provider;
024import com.google.inject.Scope;
025import org.apache.shiro.session.Session;
026import org.apache.shiro.subject.Subject;
027import org.apache.shiro.util.ThreadContext;
028
029/**
030 * Guice scope for Shiro sessions.  Not bound by default.
031 */
032public class ShiroSessionScope implements Scope {
033    public <T> Provider<T> scope(final Key<T> key, final Provider<T> unscoped) {
034        return new Provider<T>() {
035            public T get() {
036                Subject subject = ThreadContext.getSubject();
037                if (subject == null) {
038                    throw new OutOfScopeException("There is no Shiro Session currently in scope.");
039                }
040                Session session = subject.getSession();
041                T scoped = castSessionAttribute(session);
042                if (scoped == null) {
043                    scoped = unscoped.get();
044                }
045                return scoped;
046            }
047
048            @SuppressWarnings({"unchecked"})
049            private T castSessionAttribute(Session session) {
050                return (T) session.getAttribute(key);
051            }
052
053            @Override
054            public String toString() {
055                return unscoped.toString();
056            }
057        };
058    }
059
060    @Override
061    public String toString() {
062        return "ShiroSessionScope";
063    }
064}