001/** 002 * Copyright (c) 2015-2022, Michael Yang 杨福海 (fuhai999@gmail.com). 003 * <p> 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 * <p> 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * <p> 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 io.jboot.web.validate.interceptor; 017 018import com.jfinal.aop.Interceptor; 019import com.jfinal.aop.Invocation; 020import com.jfinal.core.Controller; 021import com.jfinal.log.Log; 022import io.jboot.Jboot; 023import io.jboot.utils.AnnotationUtil; 024import io.jboot.utils.StrUtil; 025import io.jboot.web.validate.CaptchaValidate; 026 027/** 028 * 验证拦截器 029 */ 030public class CaptchaValidateInterceptor implements Interceptor { 031 032 private static final Log LOG = Log.getLog("Validate"); 033 034 @Override 035 public void intercept(Invocation inv) { 036 037 CaptchaValidate captchaValidate = inv.getMethod().getAnnotation(CaptchaValidate.class); 038 if (captchaValidate != null && !validateCaptache(inv, captchaValidate)) { 039 if (Jboot.isDevMode()){ 040 LOG.error(ValidateInterceptorUtil.buildErrorMessage(inv,"@CaptchaValidate")); 041 } 042 return; 043 } 044 045 inv.invoke(); 046 } 047 048 049 /** 050 * 对验证码进行验证 051 * 052 * @param inv 053 * @param captchaValidate 054 * @return 055 */ 056 private boolean validateCaptache(Invocation inv, CaptchaValidate captchaValidate) { 057 String formName = AnnotationUtil.get(captchaValidate.form()); 058 if (StrUtil.isBlank(formName)) { 059 throw new IllegalArgumentException("@CaptchaValidate.form must not be empty in " + inv.getController().getClass().getName() + "." + inv.getMethodName()); 060 } 061 062 063 Controller controller = inv.getController(); 064 if (controller.validateCaptcha(formName)) { 065 return true; 066 } 067 068 ValidateInterceptorUtil.renderValidException(inv.getController() 069 , AnnotationUtil.get(captchaValidate.renderType()) 070 , formName 071 , AnnotationUtil.get(captchaValidate.message()) 072 , AnnotationUtil.get(captchaValidate.redirectUrl()) 073 , AnnotationUtil.get(captchaValidate.htmlPath()) 074 , captchaValidate.errorCode() 075 ); 076 077 return false; 078 } 079 080 081 082 083}