View Javadoc
1   /*
2    * Copyright 2012-2021 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.web.admin.webauth;
17  
18  import java.util.ArrayList;
19  import java.util.HashMap;
20  import java.util.List;
21  import java.util.Locale;
22  import java.util.Map;
23  
24  import javax.annotation.Resource;
25  
26  import org.codelibs.fess.Constants;
27  import org.codelibs.fess.annotation.Secured;
28  import org.codelibs.fess.app.pager.WebAuthPager;
29  import org.codelibs.fess.app.service.WebAuthenticationService;
30  import org.codelibs.fess.app.service.WebConfigService;
31  import org.codelibs.fess.app.web.CrudMode;
32  import org.codelibs.fess.app.web.base.FessAdminAction;
33  import org.codelibs.fess.es.config.exentity.WebAuthentication;
34  import org.codelibs.fess.es.config.exentity.WebConfig;
35  import org.codelibs.fess.helper.SystemHelper;
36  import org.codelibs.fess.util.ComponentUtil;
37  import org.codelibs.fess.util.RenderDataUtil;
38  import org.dbflute.optional.OptionalEntity;
39  import org.dbflute.optional.OptionalThing;
40  import org.lastaflute.web.Execute;
41  import org.lastaflute.web.response.HtmlResponse;
42  import org.lastaflute.web.response.render.RenderData;
43  import org.lastaflute.web.ruts.process.ActionRuntime;
44  
45  /**
46   * @author shinsuke
47   * @author Shunji Makino
48   */
49  public class AdminWebauthAction extends FessAdminAction {
50  
51      public static final String ROLE = "admin-webauth";
52  
53      // ===================================================================================
54      //                                                                           Attribute
55      //                                                                           =========
56      @Resource
57      private WebAuthenticationService webAuthenticationService;
58      @Resource
59      private WebAuthPager webAuthPager;
60      @Resource
61      protected WebConfigService webConfigService;
62  
63      // ===================================================================================
64      //                                                                               Hook
65      //                                                                              ======
66      @Override
67      protected void setupHtmlData(final ActionRuntime runtime) {
68          super.setupHtmlData(runtime);
69          runtime.registerData("helpLink", systemHelper.getHelpLink(fessConfig.getOnlineHelpNameWebauth()));
70      }
71  
72      @Override
73      protected String getActionRole() {
74          return ROLE;
75      }
76  
77      // ===================================================================================
78      //                                                                      Search Execute
79      //                                                                      ==============
80      @Execute
81      @Secured({ ROLE, ROLE + VIEW })
82      public HtmlResponse index(final SearchForm form) {
83          return asListHtml();
84      }
85  
86      @Execute
87      @Secured({ ROLE, ROLE + VIEW })
88      public HtmlResponse list(final OptionalThing<Integer> pageNumber, final SearchForm form) {
89          pageNumber.ifPresent(num -> {
90              webAuthPager.setCurrentPageNumber(pageNumber.get());
91          }).orElse(() -> {
92              webAuthPager.setCurrentPageNumber(0);
93          });
94          return asHtml(path_AdminWebauth_AdminWebauthJsp).renderWith(data -> {
95              searchPaging(data, form);
96          });
97      }
98  
99      @Execute
100     @Secured({ ROLE, ROLE + VIEW })
101     public HtmlResponse search(final SearchForm form) {
102         copyBeanToBean(form, webAuthPager, op -> op.exclude(Constants.PAGER_CONVERSION_RULE));
103         return asHtml(path_AdminWebauth_AdminWebauthJsp).renderWith(data -> {
104             searchPaging(data, form);
105         });
106     }
107 
108     @Execute
109     @Secured({ ROLE, ROLE + VIEW })
110     public HtmlResponse reset(final SearchForm form) {
111         webAuthPager.clear();
112         return asHtml(path_AdminWebauth_AdminWebauthJsp).renderWith(data -> {
113             searchPaging(data, form);
114         });
115     }
116 
117     protected void searchPaging(final RenderData data, final SearchForm form) {
118         RenderDataUtil.register(data, "webAuthenticationItems", webAuthenticationService.getWebAuthenticationList(webAuthPager)); // page navi
119         RenderDataUtil.register(data, "displayCreateLink", !crawlingConfigHelper.getAllWebConfigList(false, false, false, null).isEmpty());
120         // restore from pager
121         copyBeanToBean(webAuthPager, form, op -> op.include("id"));
122     }
123 
124     // ===================================================================================
125     //                                                                        Edit Execute
126     //                                                                        ============
127     // -----------------------------------------------------
128     //                                            Entry Page
129     //                                            ----------
130     @Execute
131     @Secured({ ROLE })
132     public HtmlResponse createnew() {
133         saveToken();
134         return asHtml(path_AdminWebauth_AdminWebauthEditJsp).useForm(CreateForm.class, op -> {
135             op.setup(form -> {
136                 form.initialize();
137                 form.crudMode = CrudMode.CREATE;
138             });
139         }).renderWith(data -> {
140             registerProtocolSchemeItems(data);
141             registerWebConfigItems(data);
142         });
143     }
144 
145     @Execute
146     @Secured({ ROLE })
147     public HtmlResponse edit(final EditForm form) {
148         validate(form, messages -> {}, this::asListHtml);
149         final String id = form.id;
150         webAuthenticationService.getWebAuthentication(id).ifPresent(entity -> {
151             copyBeanToBean(entity, form, op -> {});
152         }).orElse(() -> {
153             throwValidationError(messages -> messages.addErrorsCrudCouldNotFindCrudTable(GLOBAL, id), this::asListHtml);
154         });
155         saveToken();
156         if (form.crudMode.intValue() == CrudMode.EDIT) {
157             // back
158             form.crudMode = CrudMode.DETAILS;
159             return asDetailsHtml();
160         }
161         form.crudMode = CrudMode.EDIT;
162         return asEditHtml();
163     }
164 
165     // -----------------------------------------------------
166     //                                               Details
167     //                                               -------
168     @Execute
169     @Secured({ ROLE, ROLE + VIEW })
170     public HtmlResponse details(final int crudMode, final String id) {
171         verifyCrudMode(crudMode, CrudMode.DETAILS);
172         saveToken();
173         return asHtml(path_AdminWebauth_AdminWebauthDetailsJsp).useForm(EditForm.class, op -> {
174             op.setup(form -> {
175                 webAuthenticationService.getWebAuthentication(id).ifPresent(entity -> {
176                     copyBeanToBean(entity, form, copyOp -> {
177                         copyOp.excludeNull();
178                     });
179                     form.crudMode = crudMode;
180                 }).orElse(() -> {
181                     throwValidationError(messages -> messages.addErrorsCrudCouldNotFindCrudTable(GLOBAL, id), this::asListHtml);
182                 });
183             });
184         }).renderWith(data -> {
185             registerProtocolSchemeItems(data);
186             registerWebConfigItems(data);
187         });
188     }
189 
190     // -----------------------------------------------------
191     //                                         Actually Crud
192     //                                         -------------
193     @Execute
194     @Secured({ ROLE })
195     public HtmlResponse create(final CreateForm form) {
196         verifyCrudMode(form.crudMode, CrudMode.CREATE);
197         validate(form, messages -> {}, this::asEditHtml);
198         verifyToken(this::asEditHtml);
199         getWebAuthentication(form).ifPresent(entity -> {
200             try {
201                 webAuthenticationService.store(entity);
202                 saveInfo(messages -> messages.addSuccessCrudCreateCrudTable(GLOBAL));
203             } catch (final Exception e) {
204                 throwValidationError(messages -> messages.addErrorsCrudFailedToCreateCrudTable(GLOBAL, buildThrowableMessage(e)),
205                         this::asEditHtml);
206             }
207         }).orElse(() -> {
208             throwValidationError(messages -> messages.addErrorsCrudFailedToCreateInstance(GLOBAL), this::asEditHtml);
209         });
210         return redirect(getClass());
211     }
212 
213     @Execute
214     @Secured({ ROLE })
215     public HtmlResponse update(final EditForm form) {
216         verifyCrudMode(form.crudMode, CrudMode.EDIT);
217         validate(form, messages -> {}, this::asEditHtml);
218         verifyToken(this::asEditHtml);
219         getWebAuthentication(form).ifPresent(entity -> {
220             try {
221                 webAuthenticationService.store(entity);
222                 saveInfo(messages -> messages.addSuccessCrudUpdateCrudTable(GLOBAL));
223             } catch (final Exception e) {
224                 throwValidationError(messages -> messages.addErrorsCrudFailedToUpdateCrudTable(GLOBAL, buildThrowableMessage(e)),
225                         this::asEditHtml);
226             }
227         }).orElse(() -> {
228             throwValidationError(messages -> messages.addErrorsCrudCouldNotFindCrudTable(GLOBAL, form.id), this::asEditHtml);
229         });
230         return redirect(getClass());
231     }
232 
233     @Execute
234     @Secured({ ROLE })
235     public HtmlResponse delete(final EditForm form) {
236         verifyCrudMode(form.crudMode, CrudMode.DETAILS);
237         validate(form, messages -> {}, this::asDetailsHtml);
238         verifyToken(this::asDetailsHtml);
239         final String id = form.id;
240         webAuthenticationService.getWebAuthentication(id).ifPresent(entity -> {
241             try {
242                 webAuthenticationService.delete(entity);
243                 saveInfo(messages -> messages.addSuccessCrudDeleteCrudTable(GLOBAL));
244             } catch (final Exception e) {
245                 throwValidationError(messages -> messages.addErrorsCrudFailedToDeleteCrudTable(GLOBAL, buildThrowableMessage(e)),
246                         this::asEditHtml);
247             }
248         }).orElse(() -> {
249             throwValidationError(messages -> messages.addErrorsCrudCouldNotFindCrudTable(GLOBAL, id), this::asDetailsHtml);
250         });
251         return redirect(getClass());
252     }
253 
254     //===================================================================================
255     //                                                                        Assist Logic
256     //                                                                        ============
257     public static OptionalEntity<WebAuthentication> getEntity(final CreateForm form, final String username, final long currentTime) {
258         switch (form.crudMode) {
259         case CrudMode.CREATE:
260             return OptionalEntity.of(new WebAuthentication()).map(entity -> {
261                 entity.setCreatedBy(username);
262                 entity.setCreatedTime(currentTime);
263                 return entity;
264             });
265         case CrudMode.EDIT:
266             if (form instanceof EditForm) {
267                 return ComponentUtil.getComponent(WebAuthenticationService.class).getWebAuthentication(((EditForm) form).id);
268             }
269             break;
270         default:
271             break;
272         }
273         return OptionalEntity.empty();
274     }
275 
276     public static OptionalEntity<WebAuthentication> getWebAuthentication(final CreateForm form) {
277         final SystemHelper systemHelper = ComponentUtil.getSystemHelper();
278         final String username = systemHelper.getUsername();
279         final long currentTime = systemHelper.getCurrentTimeAsLong();
280         return getEntity(form, username, currentTime).map(entity -> {
281             entity.setUpdatedBy(username);
282             entity.setUpdatedTime(currentTime);
283             copyBeanToBean(form, entity, op -> op.exclude(Constants.COMMON_CONVERSION_RULE));
284             return entity;
285         });
286     }
287 
288     protected void registerProtocolSchemeItems(final RenderData data) {
289         final List<Map<String, String>> itemList = new ArrayList<>();
290         final Locale locale = ComponentUtil.getRequestManager().getUserLocale();
291         itemList.add(createItem(ComponentUtil.getMessageManager().getMessage(locale, "labels.webauth_scheme_basic"), Constants.BASIC));
292         itemList.add(createItem(ComponentUtil.getMessageManager().getMessage(locale, "labels.webauth_scheme_digest"), Constants.DIGEST));
293         itemList.add(createItem(ComponentUtil.getMessageManager().getMessage(locale, "labels.webauth_scheme_ntlm"), Constants.NTLM));
294         itemList.add(createItem(ComponentUtil.getMessageManager().getMessage(locale, "labels.webauth_scheme_form"), Constants.FORM));
295         RenderDataUtil.register(data, "protocolSchemeItems", itemList);
296     }
297 
298     protected void registerWebConfigItems(final RenderData data) {
299         final List<Map<String, String>> itemList = new ArrayList<>();
300         final List<WebConfig> webConfigList = crawlingConfigHelper.getAllWebConfigList(false, false, false, null);
301         for (final WebConfig webConfig : webConfigList) {
302             itemList.add(createItem(webConfig.getName(), webConfig.getId().toString()));
303         }
304         RenderDataUtil.register(data, "webConfigItems", itemList);
305     }
306 
307     protected Map<String, String> createItem(final String label, final String value) {
308         final Map<String, String> map = new HashMap<>(2);
309         map.put(Constants.ITEM_LABEL, label);
310         map.put(Constants.ITEM_VALUE, value);
311         return map;
312     }
313 
314     // ===================================================================================
315     //                                                                        Small Helper
316     //                                                                        ============
317     protected void verifyCrudMode(final int crudMode, final int expectedMode) {
318         if (crudMode != expectedMode) {
319             throwValidationError(messages -> {
320                 messages.addErrorsCrudInvalidMode(GLOBAL, String.valueOf(expectedMode), String.valueOf(crudMode));
321             }, this::asListHtml);
322         }
323     }
324 
325     // ===================================================================================
326     //                                                                              JSP
327     //                                                                           =========
328 
329     private HtmlResponse asListHtml() {
330         return asHtml(path_AdminWebauth_AdminWebauthJsp).renderWith(data -> {
331             RenderDataUtil.register(data, "webAuthenticationItems", webAuthenticationService.getWebAuthenticationList(webAuthPager)); // page navi
332             RenderDataUtil.register(data, "displayCreateLink",
333                     !crawlingConfigHelper.getAllWebConfigList(false, false, false, null).isEmpty());
334         }).useForm(SearchForm.class, setup -> {
335             setup.setup(form -> {
336                 copyBeanToBean(webAuthPager, form, op -> op.include("id"));
337             });
338         });
339     }
340 
341     private HtmlResponse asEditHtml() {
342         return asHtml(path_AdminWebauth_AdminWebauthEditJsp).renderWith(data -> {
343             registerProtocolSchemeItems(data);
344             registerWebConfigItems(data);
345         });
346     }
347 
348     private HtmlResponse asDetailsHtml() {
349         return asHtml(path_AdminWebauth_AdminWebauthDetailsJsp).renderWith(data -> {
350             registerProtocolSchemeItems(data);
351             registerWebConfigItems(data);
352         });
353     }
354 }