package cn.com.qmth.stmms.biz.api.auth.service.validator;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import cn.com.qmth.stmms.biz.api.auth.exception.ApiException;
import cn.com.qmth.stmms.biz.api.auth.interfaces.AuthValidator;
import cn.com.qmth.stmms.biz.api.auth.model.AuthInfo;
import cn.com.qmth.stmms.biz.api.auth.model.BasicAuthInfo;
import cn.com.qmth.stmms.biz.role.service.RoleAuthService;
import cn.com.qmth.stmms.biz.user.model.User;
import cn.com.qmth.stmms.biz.user.service.UserService;
import cn.com.qmth.stmms.biz.utils.RoleAuthUtil;
import cn.com.qmth.stmms.common.utils.Md5EncryptUtils;

@Component
public class DefaultValidator implements AuthValidator {

    @Autowired
    private AuthValidateService validateService;

    @Autowired
    private UserService userService;

    @Autowired
    private RoleAuthService roleService;

    @PostConstruct
    protected void init() {
        validateService.addValidator(this);
    }

    @Override
    public String getName() {
        return "default";
    }

    @Override
    public boolean validate(AuthInfo auth) {
        BasicAuthInfo info = (BasicAuthInfo) auth;
        User user = userService.findByLoginName(info.getLoginName());
        if (user != null) {
            if (user.getPassword().equals(Md5EncryptUtils.md5(info.getPassword()))) {
                info.setLoginUser(RoleAuthUtil.buildRoleAuthByUser(user, roleService));
                return true;
            } else {
                throw ApiException.USER_PASSWORD_ERROR;
            }
        } else {
            throw ApiException.USER_UNEXISTS;
        }
    }

}
