package org.ccpit.base.controller;

import org.apache.commons.lang.StringUtils;
import org.ccpit.base.utils.ValidateCode;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Date: 2015年10月08日 09:42
 *
 * @author 孙其鹏
 * @version 1.0
 */
@Controller
@RequestMapping("/validate")
public class ValidateCodeController {
    public static final String CODE="validate_code_in_session";

    @RequestMapping("/code")
    public void code(HttpServletRequest request,HttpServletResponse response){
        ValidateCode vCode = new ValidateCode(100,30,4,100);
        request.getSession().setAttribute(CODE, vCode.getCode().toLowerCase());
        try {
            vCode.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 验证验证码是否正确 (如果正确则删除session中的验证码)
     * @param request
     * @param input
     * @return
     */
    public static boolean validate(HttpServletRequest request,String input){
        Object code = request.getSession().getAttribute(CODE);
        String reqCode = input;
        if (code==null || StringUtils.isEmpty((String) code)||StringUtils.isEmpty(reqCode))
            return false;
        boolean success = ((String)code).trim().toLowerCase().equals(reqCode.trim().toLowerCase());
        if (success)
            request.getSession().setAttribute(CODE,"");
        return success;
    }
}
