package com.njzscloud.common.security.module.password;

import com.njzscloud.common.core.ex.ExceptionMsg;
import com.njzscloud.common.core.jackson.Jackson;
import com.njzscloud.common.security.ex.UserLoginException;
import com.njzscloud.common.security.support.LoginForm;
import com.njzscloud.common.security.support.LoginPreparer;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;

/**
 * 账号密码登录，登录参数处理器
 */
public class PasswordLoginPreparer implements LoginPreparer {
    private static final AntPathRequestMatcher matcher = new AntPathRequestMatcher("/login", "POST");

    /**
     * 创建登录参数
     *
     * @param request 请求信息
     * @return 登录参数 {@link PasswordLoginForm}
     */
    @Override
    public LoginForm createLoginForm(HttpServletRequest request) {
        try (ServletInputStream inputStream = request.getInputStream()) {
            return Jackson.toBean(inputStream, PasswordLoginForm.class);
        } catch (Exception e) {
            throw new UserLoginException(e, ExceptionMsg.SYS_ERR_MSG, "登录表单解析失败");
        }
    }

    /**
     * 是否支持当前登录方式
     *
     * @param request 请求信息
     * @return 当请求方式为 POST 且路径为 /login 时返回 true
     */
    @Override
    public boolean support(HttpServletRequest request) {
        return matcher.matches(request);
    }

}
