1   /*
2    * Copyright 2018 LINE Corporation
3    *
4    * LINE Corporation licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package com.linecorp.centraldogma.server.auth.shiro;
17  
18  import static java.util.Objects.requireNonNull;
19  
20  import java.util.function.Function;
21  
22  import org.apache.shiro.config.Ini;
23  
24  import com.linecorp.centraldogma.server.auth.AuthConfig;
25  import com.linecorp.centraldogma.server.auth.AuthProvider;
26  import com.linecorp.centraldogma.server.auth.AuthProviderFactory;
27  import com.linecorp.centraldogma.server.auth.AuthProviderParameters;
28  
29  /**
30   * A factory for creating an Apache Shiro based {@link AuthProvider}.
31   */
32  public final class ShiroAuthProviderFactory implements AuthProviderFactory {
33  
34      private final Function<AuthConfig, Ini> iniConfigResolver;
35  
36      /**
37       * Creates a new instance with the default {@link Ini} config resolver.
38       */
39      public ShiroAuthProviderFactory() {
40          this(ShiroAuthProviderFactory::fromConfig);
41      }
42  
43      /**
44       * Creates a new instance with the specified {@code iniConfigResolver}.
45       */
46      public ShiroAuthProviderFactory(Function<AuthConfig, Ini> iniConfigResolver) {
47          this.iniConfigResolver = requireNonNull(iniConfigResolver, "iniConfigResolver");
48      }
49  
50      @Override
51      public AuthProvider create(AuthProviderParameters parameters) {
52          requireNonNull(parameters, "parameters");
53          return new ShiroAuthProvider(parameters.authConfig(),
54                                       iniConfigResolver.apply(parameters.authConfig()),
55                                       parameters.sessionIdGenerator(),
56                                       parameters.loginSessionPropagator(),
57                                       parameters.logoutSessionPropagator());
58      }
59  
60      private static Ini fromConfig(AuthConfig cfg) {
61          try {
62              final String iniPath = cfg.properties(String.class);
63              return Ini.fromResourcePath(iniPath);
64          } catch (Exception e) {
65              throw new IllegalStateException("Failed to create " + Ini.class.getSimpleName(), e);
66          }
67      }
68  }