View Javadoc
1   /*
2    * Copyright 2012-2025 CodeLibs Project and the Others.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://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,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
13   * either express or implied. See the License for the specific language
14   * governing permissions and limitations under the License.
15   */
16  package org.codelibs.fess.app.service;
17  
18  import static org.codelibs.core.stream.StreamUtil.stream;
19  
20  import java.util.HashSet;
21  import java.util.List;
22  import java.util.Set;
23  
24  import org.codelibs.core.beans.util.BeanUtil;
25  import org.codelibs.core.lang.StringUtil;
26  import org.codelibs.fess.Constants;
27  import org.codelibs.fess.app.pager.AccessTokenPager;
28  import org.codelibs.fess.exception.InvalidAccessTokenException;
29  import org.codelibs.fess.mylasta.direction.FessConfig;
30  import org.codelibs.fess.opensearch.config.cbean.AccessTokenCB;
31  import org.codelibs.fess.opensearch.config.exbhv.AccessTokenBhv;
32  import org.codelibs.fess.opensearch.config.exentity.AccessToken;
33  import org.codelibs.fess.taglib.FessFunctions;
34  import org.codelibs.fess.util.ComponentUtil;
35  import org.dbflute.cbean.result.PagingResultBean;
36  import org.dbflute.optional.OptionalEntity;
37  
38  import jakarta.annotation.Resource;
39  import jakarta.servlet.http.HttpServletRequest;
40  
41  /**
42   * The service for access token.
43   */
44  public class AccessTokenService {
45  
46      /**
47       * Default constructor.
48       */
49      public AccessTokenService() {
50          // nothing
51      }
52  
53      /**
54       * The behavior of access token.
55       */
56      @Resource
57      protected AccessTokenBhv accessTokenBhv;
58  
59      /**
60       * The Fess configuration.
61       */
62      @Resource
63      protected FessConfig fessConfig;
64  
65      /**
66       * Get the list of access tokens.
67       * @param accessTokenPager The pager for access token.
68       * @return The list of access tokens.
69       */
70      public List<AccessToken> getAccessTokenList(final AccessTokenPager accessTokenPager) {
71  
72          final PagingResultBean<AccessToken> accessTokenList = accessTokenBhv.selectPage(cb -> {
73              cb.paging(accessTokenPager.getPageSize(), accessTokenPager.getCurrentPageNumber());
74              setupListCondition(cb, accessTokenPager);
75          });
76  
77          // update pager
78          BeanUtil.copyBeanToBean(accessTokenList, accessTokenPager, option -> option.include(Constants.PAGER_CONVERSION_RULE));
79          accessTokenPager.setPageNumberList(
80                  accessTokenList.pageRange(op -> op.rangeSize(fessConfig.getPagingPageRangeSizeAsInteger())).createPageNumberList());
81  
82          return accessTokenList;
83      }
84  
85      /**
86       * Get the access token.
87       * @param id The ID of the access token.
88       * @return The access token.
89       */
90      public OptionalEntity<AccessToken> getAccessToken(final String id) {
91          return accessTokenBhv.selectByPK(id);
92      }
93  
94      /**
95       * Store the access token.
96       * @param accessToken The access token.
97       */
98      public void store(final AccessToken accessToken) {
99  
100         accessTokenBhv.insertOrUpdate(accessToken, op -> op.setRefreshPolicy(Constants.TRUE));
101 
102     }
103 
104     /**
105      * Delete the access token.
106      * @param accessToken The access token.
107      */
108     public void delete(final AccessToken accessToken) {
109 
110         accessTokenBhv.delete(accessToken, op -> op.setRefreshPolicy(Constants.TRUE));
111 
112     }
113 
114     /**
115      * Set up the list condition.
116      * @param cb The callback.
117      * @param accessTokenPager The pager for access token.
118      */
119     protected void setupListCondition(final AccessTokenCB cb, final AccessTokenPager accessTokenPager) {
120         if (accessTokenPager.id != null) {
121             cb.query().docMeta().setId_Equal(accessTokenPager.id);
122         }
123         // TODO Long, Integer, String supported only.
124 
125         // setup condition
126         cb.query().addOrderBy_Name_Asc();
127         cb.query().addOrderBy_CreatedTime_Asc();
128 
129         // search
130 
131     }
132 
133     /**
134      * Get the permissions.
135      * @param request The request.
136      * @return The permissions.
137      */
138     public OptionalEntity<Set<String>> getPermissions(final HttpServletRequest request) {
139         final String token = ComponentUtil.getAccessTokenHelper().getAccessTokenFromRequest(request);
140         if (StringUtil.isNotBlank(token)) {
141             return accessTokenBhv.selectEntity(cb -> {
142                 cb.query().setToken_Term(token);
143             }).map(accessToken -> {
144                 final Set<String> permissionSet = new HashSet<>();
145                 final Long expiredTime = accessToken.getExpiredTime();
146                 if (expiredTime != null && expiredTime.longValue() > 0
147                         && expiredTime.longValue() < ComponentUtil.getSystemHelper().getCurrentTimeAsLong()) {
148                     throw new InvalidAccessTokenException("invalid_token",
149                             "The token is expired(" + FessFunctions.formatDate(FessFunctions.date(expiredTime)) + ").");
150                 }
151                 stream(accessToken.getPermissions()).of(stream -> stream.forEach(permissionSet::add));
152                 final String name = accessToken.getParameterName();
153                 stream(request.getParameterValues(name)).of(stream -> stream.filter(StringUtil::isNotBlank).forEach(permissionSet::add));
154                 return OptionalEntity.of(permissionSet);
155             }).orElseThrow(() -> new InvalidAccessTokenException("invalid_token", "Invalid token: " + token));
156         }
157         return OptionalEntity.empty();
158     }
159 }