All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.springframework.boxes.cookie.starter.captcha.BoxesCaptchaServices Maven / Gradle / Ivy

package com.springframework.boxes.cookie.starter.captcha;

import com.google.code.kaptcha.Producer;
import com.spring.boxes.dollar.$;
import com.springframework.boxes.cookie.starter.CaptchaServices;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.ServletRequestUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Data
@Slf4j
@NoArgsConstructor
@AllArgsConstructor
public class BoxesCaptchaServices extends BoxesCaptchaHandler implements CaptchaServices {

    // 存储Key名称
    private String cookieName;

    // 验证key名称
    private String requestName;

    // 验证码组件
    private Producer producer;


    @Override
    public String producerNumber(HttpServletRequest request, HttpServletResponse response) {
        String captchaVal = createCaptchaVal();
        String encodedVal = $.encode(captchaVal);
        log.info("Thread:{}, CaptchaVal:{}, EncodedVal:{}", Thread.currentThread().getName(), captchaVal, encodedVal);
        $.setCookie(response, this.getCookieName(), encodedVal);
        return captchaVal;
    }


    @Override
    public ResponseEntity producerImage(HttpServletRequest request, HttpServletResponse response) {
        String captchaVal = createCaptchaVal();
        String encodedVal = $.encode(captchaVal);
        log.info("Thread:{}, CaptchaVal:{}, EncodedVal:{}", Thread.currentThread().getName(), captchaVal, encodedVal);
        $.setCookie(response, this.getCookieName(), captchaVal);
        Resource resource = createImage(captchaVal);
        return new ResponseEntity<>(resource, $.getResponseHeaders(MediaType.IMAGE_JPEG), HttpStatus.OK);
    }


    @Override
    public boolean validate(HttpServletRequest request, HttpServletResponse response) {
        String cookieValue = $.getCookieVal(request, this.getCookieName());
        if (StringUtils.isBlank(cookieValue)) {
            return false;
        }
        String decodedVal = $.decode(cookieValue);
        String requestVal = ServletRequestUtils.getStringParameter(request, requestName, StringUtils.EMPTY);
        log.info("Thread:{}, CookieVal:{}, DecodedVal:{}, requestVal:{}", Thread.currentThread().getName(), cookieValue, decodedVal, requestVal);
        if(StringUtils.isBlank(requestVal)){
            return false;
        }
        return requestVal.equals(decodedVal);
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy