<commit_before>package com.cnpc.framework.base.controller;

import com.cnpc.framework.constant.RedisConstant;
import com.cnpc.framework.base.entity.User;
import com.cnpc.framework.base.dao.RedisDao;
import com.cnpc.framework.base.pojo.ResultCode;
import com.cnpc.framework.base.service.FunctionService;
import com.cnpc.framework.base.service.RoleService;
import com.cnpc.framework.base.service.UserRoleService;
import com.cnpc.framework.base.service.UserService;
import com.cnpc.framework.oauth.common.CustomOAuthService;
import com.cnpc.framework.oauth.entity.OAuthUser;
import com.cnpc.framework.oauth.service.OAuthServices;
import com.cnpc.framework.oauth.service.OAuthUserService;
import com.cnpc.framework.utils.EncryptUtil;
import com.cnpc.framework.utils.PropertiesUtil;
import com.cnpc.framework.utils.StrUtil;
import com.cnpc.framework.utils.AccessToken;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.subject.Subject;
import org.scribe.model.Token;
import org.scribe.model.Verifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import com.openparts.common.utils.KaliumKeyPair;
import com.openparts.common.CommonConstants;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Controller
public class LoginController {

    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Resource
    private RoleService roleService;

    @Resource
    private UserService userService;

    @Autowired
    OAuthServices oAuthServices;

    @Resource
    OAuthUserService oAuthUserService;

    @Resource
    private FunctionService functionService;

    @Resource
    private UserRoleService userRoleService;

    @Resource
    private RedisDao redisDao;

    private final static String MAIN_PAGE = PropertiesUtil.getValue("page.main");
    private final static String LOGIN_PAGE = PropertiesUtil.getValue("page.login");
    private final static String REGISTER_PAGE = PropertiesUtil.getValue("page.register");

    private String tryLogin(Subject subject, Model model, UsernamePasswordToken token) {
        String msg = null;

        try {
            subject.login(token);
            //通过认证
            if (subject.isAuthenticated()) {
                String userId = subject.getPrincipal().toString();
                Set<String> roles = roleService.getRoleCodeSet(userId);
                Set<String> functions = functionService.getFunctionCodeSet(roles, userId);
                //---------调用realm doGetAuthorizationInfo----------
                boolean isPermitted = subject.isPermitted("user");
                if (!roles.isEmpty()) {
                    subject.getSession().setAttribute("isAuthorized", true);
                    return MAIN_PAGE;
                } else {//没有授权
                    msg = "您没有得到相应的授权！ [subject.isAuthenticated() == true]";
                    if (model != null) {
                        model.addAttribute("message", new ResultCode("1", msg));
                    }
                    subject.getSession().setAttribute("isAuthorized", false);
                    logger.error(msg);
                    return LOGIN_PAGE;
                }
            } else {
                return LOGIN_PAGE;
            }
        //0 未授权 1 账号问题 2 密码错误  3 账号密码错误
        } catch (IncorrectCredentialsException e) {
            msg = "登录密码错误. Password for account " + token.getPrincipal() + " was incorrect";
            if (model != null) {
                model.addAttribute("message", new ResultCode("2", msg));
            }
        } catch (ExcessiveAttemptsException e) {
            msg = "登录失败次数过多";
            if (model != null) {
                model.addAttribute("message", new ResultCode("3", msg));
            }
        } catch (LockedAccountException e) {
            msg = "帐号已被锁定. The account for username " + token.getPrincipal() + " was locked.";
            if (model != null) {
                model.addAttribute("message", new ResultCode("1", msg));
            }
        } catch (DisabledAccountException e) {
            msg = "帐号已被禁用. The account for username " + token.getPrincipal() + " was disabled.";
            if (model != null) {
                model.addAttribute("message", new ResultCode("1", msg));
            }
        } catch (ExpiredCredentialsException e) {
            msg = "帐号已过期. the account for username " + token.getPrincipal() + "  was expired.";
            if (model != null) {
                model.addAttribute("message", new ResultCode("1", msg));
            }
        } catch (UnknownAccountException e) {
            msg = "帐号不存在. There is no user with username of " + token.getPrincipal();
            if (model != null) {
                model.addAttribute("message", new ResultCode("1", msg));
            }
        } catch (UnauthorizedException e) {
            msg = "您没有得到相应的授权！" + e.getMessage();
            if (model != null) {
                model.addAttribute("message", new ResultCode("1", msg));
            }
        }

        if (msg != null) {
            logger.error(msg);
        }

        return LOGIN_PAGE;
    }

    @RequestMapping(value = "/login")
    private String doLogin(HttpServletRequest request, Model model) {
        model.addAttribute("oAuthServices", oAuthServices.getAllOAuthServices());
        //已经登录过，直接进入主页
        Subject subject = SecurityUtils.getSubject();
        if (subject != null && subject.isAuthenticated()) {
            Object authorized = subject.getSession().getAttribute("isAuthorized");
            //boolean isAuthorized = Boolean.valueOf(subject.getSession().getAttribute("isAuthorized").toString());
            if (authorized != null && Boolean.valueOf(authorized.toString()))
                return MAIN_PAGE;
        }
        String userName = request.getParameter("userName");
        //默认首页，第一次进来
        if (StrUtil.isEmpty(userName)) {
            return LOGIN_PAGE;
        }
        String password = request.getParameter("password");
        //密码加密+加盐
        password = EncryptUtil.getPassword(password, userName);
        UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
        token.setRememberMe(true);
        subject = SecurityUtils.getSubject();

        return tryLogin(subject, model, token);
    }

 /*   @RequestMapping(value = "/logout")
    private String doLogout(HttpServletRequest request) {
        request.setAttribute("oAuthServices", oAuthServices.getAllOAuthServices());
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return LOGIN_PAGE;
    }*/

    /**
     * 注销调用此方法，需要注释request.setAttribute，因为会话删除后会出现问题，必须使用redirect:/login代替 LOGIN_PAGE
     * 还有可以使用SystemLogoutFilter进行重定向
     * 具体使用哪种方式，详见spring-shiro.xml的配置，本项目没使用SystemLogoutFilter
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/logout")
    private String doLogout(HttpServletRequest request) {
        //request.setAttribute("oAuthServices", oAuthServices.getAllOAuthServices());
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/login";
    }

    @RequestMapping(value = "/register", method = RequestMethod.GET)<commit_msg>remove superfluous code<commit_after>package com.cnpc.framework.base.controller;

import com.cnpc.framework.constant.RedisConstant;
import com.cnpc.framework.base.entity.User;
import com.cnpc.framework.base.dao.RedisDao;
import com.cnpc.framework.base.pojo.ResultCode;
import com.cnpc.framework.base.service.FunctionService;
import com.cnpc.framework.base.service.RoleService;
import com.cnpc.framework.base.service.UserRoleService;
import com.cnpc.framework.base.service.UserService;
import com.cnpc.framework.oauth.common.CustomOAuthService;
import com.cnpc.framework.oauth.entity.OAuthUser;
import com.cnpc.framework.oauth.service.OAuthServices;
import com.cnpc.framework.oauth.service.OAuthUserService;
import com.cnpc.framework.utils.EncryptUtil;
import com.cnpc.framework.utils.PropertiesUtil;
import com.cnpc.framework.utils.StrUtil;
import com.cnpc.framework.utils.AccessToken;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.subject.Subject;
import org.scribe.model.Token;
import org.scribe.model.Verifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import com.openparts.common.utils.KaliumKeyPair;
import com.openparts.common.CommonConstants;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Controller
public class LoginController {

    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Resource
    private RoleService roleService;

    @Resource
    private UserService userService;

    @Autowired
    OAuthServices oAuthServices;

    @Resource
    OAuthUserService oAuthUserService;

    @Resource
    private FunctionService functionService;

    @Resource
    private UserRoleService userRoleService;

    @Resource
    private RedisDao redisDao;

    private final static String MAIN_PAGE = PropertiesUtil.getValue("page.main");
    private final static String LOGIN_PAGE = PropertiesUtil.getValue("page.login");
    private final static String REGISTER_PAGE = PropertiesUtil.getValue("page.register");

    private String tryLogin(Subject subject, Model model, UsernamePasswordToken token) {
        String msg = null;

        try {
            subject.login(token);
            //通过认证
            if (subject.isAuthenticated()) {
                String userId = subject.getPrincipal().toString();
                Set<String> roles = roleService.getRoleCodeSet(userId);
                Set<String> functions = functionService.getFunctionCodeSet(roles, userId);
                //---------调用realm doGetAuthorizationInfo----------
                boolean isPermitted = subject.isPermitted("user");
                if (!roles.isEmpty()) {
                    subject.getSession().setAttribute("isAuthorized", true);
                    return MAIN_PAGE;
                } else {//没有授权
                    msg = "您没有得到相应的授权！ [subject.isAuthenticated() == true]";
                    if (model != null) {
                        model.addAttribute("message", new ResultCode("1", msg));
                    }
                    subject.getSession().setAttribute("isAuthorized", false);
                    logger.error(msg);
                    return LOGIN_PAGE;
                }
            } else {
                return LOGIN_PAGE;
            }
        //0 未授权 1 账号问题 2 密码错误  3 账号密码错误
        } catch (IncorrectCredentialsException e) {
            msg = "登录密码错误. Password for account " + token.getPrincipal() + " was incorrect";
            if (model != null) {
                model.addAttribute("message", new ResultCode("2", msg));
            }
        } catch (ExcessiveAttemptsException e) {
            msg = "登录失败次数过多";
            if (model != null) {
                model.addAttribute("message", new ResultCode("3", msg));
            }
        } catch (LockedAccountException e) {
            msg = "帐号已被锁定. The account for username " + token.getPrincipal() + " was locked.";
            if (model != null) {
                model.addAttribute("message", new ResultCode("1", msg));
            }
        } catch (DisabledAccountException e) {
            msg = "帐号已被禁用. The account for username " + token.getPrincipal() + " was disabled.";
            if (model != null) {
                model.addAttribute("message", new ResultCode("1", msg));
            }
        } catch (ExpiredCredentialsException e) {
            msg = "帐号已过期. the account for username " + token.getPrincipal() + "  was expired.";
            if (model != null) {
                model.addAttribute("message", new ResultCode("1", msg));
            }
        } catch (UnknownAccountException e) {
            msg = "帐号不存在. There is no user with username of " + token.getPrincipal();
            if (model != null) {
                model.addAttribute("message", new ResultCode("1", msg));
            }
        } catch (UnauthorizedException e) {
            msg = "您没有得到相应的授权！" + e.getMessage();
            if (model != null) {
                model.addAttribute("message", new ResultCode("1", msg));
            }
        }

        if (msg != null) {
            logger.error(msg);
        }

        return LOGIN_PAGE;
    }

    @RequestMapping(value = "/login")
    private String doLogin(HttpServletRequest request, Model model) {
        model.addAttribute("oAuthServices", oAuthServices.getAllOAuthServices());
        //已经登录过，直接进入主页
        Subject subject = SecurityUtils.getSubject();
        if (subject != null && subject.isAuthenticated()) {
            Object authorized = subject.getSession().getAttribute("isAuthorized");
            //boolean isAuthorized = Boolean.valueOf(subject.getSession().getAttribute("isAuthorized").toString());
            if (authorized != null && Boolean.valueOf(authorized.toString()))
                return MAIN_PAGE;
        }
        String userName = request.getParameter("userName");
        //默认首页，第一次进来
        if (StrUtil.isEmpty(userName)) {
            return LOGIN_PAGE;
        }
        String password = request.getParameter("password");
        //密码加密+加盐
        password = EncryptUtil.getPassword(password, userName);
        UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
        token.setRememberMe(true);

        return tryLogin(subject, model, token);
    }

 /*   @RequestMapping(value = "/logout")
    private String doLogout(HttpServletRequest request) {
        request.setAttribute("oAuthServices", oAuthServices.getAllOAuthServices());
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return LOGIN_PAGE;
    }*/

    /**
     * 注销调用此方法，需要注释request.setAttribute，因为会话删除后会出现问题，必须使用redirect:/login代替 LOGIN_PAGE
     * 还有可以使用SystemLogoutFilter进行重定向
     * 具体使用哪种方式，详见spring-shiro.xml的配置，本项目没使用SystemLogoutFilter
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/logout")
    private String doLogout(HttpServletRequest request) {
        //request.setAttribute("oAuthServices", oAuthServices.getAllOAuthServices());
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/login";
    }

    @RequestMapping(value = "/register", method = RequestMethod.GET)
{'fraction_non_alphanumeric': 0.11201427438540841, 'fraction_numerical': 0.0018503832936822627, 'mean_word_length': 2.5885700735119754, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 2}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6443723', 'n_tokens_mistral': 4265, 'n_tokens_neox': 4303, 'n_words': 827}