001/*
002 * Copyright 2012 Atteo.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package org.atteo.moonshine.shiro.database;
017
018import javax.inject.Singleton;
019import javax.sql.DataSource;
020import javax.xml.bind.annotation.XmlIDREF;
021import javax.xml.bind.annotation.XmlRootElement;
022
023import org.apache.shiro.realm.Realm;
024import org.atteo.moonshine.database.DatabaseMigration;
025import org.atteo.moonshine.database.DatabaseService;
026import org.atteo.moonshine.jpa.JpaService;
027import org.atteo.moonshine.liquibase.LiquibaseFacade;
028import org.atteo.moonshine.services.ImportService;
029import org.atteo.moonshine.shiro.RealmService;
030import org.atteo.moonshine.springdata.RepositoryFactoryProvider;
031import org.atteo.moonshine.springdata.RepositoryProvider;
032import org.springframework.data.repository.core.support.RepositoryFactorySupport;
033
034import com.google.inject.Module;
035import com.google.inject.PrivateModule;
036
037/**
038 * Realm which keeps accounts in the database.
039 *
040 * <p>
041 * Binds {@link Realm} and {@link AccountRepository}.
042 * </p>
043 */
044@XmlRootElement(name = "database")
045public class DatabaseRealmService extends RealmService {
046    @ImportService
047    @XmlIDREF
048    private JpaService jpa;
049
050    @ImportService
051    private DatabaseService database;
052
053    @Override
054    public Module configure() {
055        // we need to use the same database as JPA which we are using
056        database = jpa.getDatabaseService();
057
058        database.registerMigration(new DatabaseMigration() {
059            @Override
060            public void execute(DataSource dataSource) {
061                new LiquibaseFacade(dataSource).migrate("liquibase/database-realm.xml");
062            }
063        });
064
065        return new PrivateModule() {
066            @Override
067            protected void configure() {
068                bind(RepositoryFactorySupport.class).toProvider(RepositoryFactoryProvider.class)
069                        .in(Singleton.class);
070                bind(AccountRepository.class).toProvider(new RepositoryProvider<>(AccountRepository.class))
071                        .in(Singleton.class);
072
073                bind(Realm.class).to(DatabaseRealm.class);
074
075                expose(AccountRepository.class);
076                expose(Realm.class);
077            }
078        };
079    }
080}