package com.sztzjy.linkCommerce.controller.stu; import cn.hutool.core.util.IdUtil; import cn.hutool.system.UserInfo; import com.sztzjy.linkCommerce.annotation.AnonymousAccess; import com.sztzjy.linkCommerce.config.Constant; import com.sztzjy.linkCommerce.config.exception.UnAuthorizedException; import com.sztzjy.linkCommerce.config.security.JwtUser; import com.sztzjy.linkCommerce.config.security.LoginResult; import com.sztzjy.linkCommerce.config.security.TokenProvider; import com.sztzjy.linkCommerce.entity.ExternalResourceMapping; import com.sztzjy.linkCommerce.entity.SchoolClass; import com.sztzjy.linkCommerce.entity.SchoolClassExample; import com.sztzjy.linkCommerce.entity.Userinfo; import com.sztzjy.linkCommerce.entity.UserinfoExample; import com.sztzjy.linkCommerce.mapper.ExternalResourceMappingMapper; import com.sztzjy.linkCommerce.mapper.SchoolClassMapper; import com.sztzjy.linkCommerce.mapper.UserinfoMapper; import com.sztzjy.linkCommerce.service.SchoolService; import com.sztzjy.linkCommerce.service.UserInfoService; import com.sztzjy.linkCommerce.util.ResultDataEntity; import com.sztzjy.linkCommerce.util.ResultEntity; import com.sztzjy.linkCommerce.util.RsaUtil; import com.sztzjy.linkCommerce.util.TzApi; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.util.CollectionUtils; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; @RestController @RequestMapping("/api/user") @Api(tags = "yz-登录相关") public class LoginController { static final String ZHIYUN_SOURCE_SYSTEM = "ZHIYUN"; static final String USER_RESOURCE_TYPE = "USER"; @Resource private AuthenticationManagerBuilder authenticationManagerBuilder; @Autowired UserinfoMapper userinfoMapper; @Autowired SchoolClassMapper schoolClassMapper; @Autowired ExternalResourceMappingMapper externalResourceMappingMapper; @PostMapping("/login") @ApiOperation("登录接口") @AnonymousAccess public ResultEntity login(@RequestParam(required = false) String passwordEncode, @RequestParam(required = false) String userName, HttpServletRequest request, @RequestParam(required = false) String TOKEN) { JwtUser jwtUser; String passWord; if (StringUtils.isBlank(TOKEN)) { try { passWord = RsaUtil.decryptByPrivateKey(passwordEncode); } catch (Exception e) { return new ResultEntity(HttpStatus.BAD_REQUEST, "密码错误"); } try{ UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userName, passWord); Authentication authentication = authenticationManagerBuilder.getObject().authenticate(authenticationToken); SecurityContextHolder.getContext().setAuthentication(authentication); jwtUser = (JwtUser) authentication.getPrincipal(); String token = TokenProvider.createToken(jwtUser); // 1、子系统直接登录 UserinfoExample stuUserExample = new UserinfoExample(); stuUserExample.createCriteria().andUsernameEqualTo(userName).andPasswordEqualTo(passWord); List userinfos = userinfoMapper.selectByExample(stuUserExample); //不存在返回错误,正确放行 if (userinfos.isEmpty()) { return new ResultEntity(HttpStatus.BAD_REQUEST, "密码错误"); } Userinfo user = userinfos.get(0); return new ResultEntity(HttpStatus.OK, buildLoginResultMap(user, token)); }catch (Exception e){ return new ResultEntity(HttpStatus.BAD_REQUEST, "账号不存在"); } }else { if (!org.springframework.util.StringUtils.hasText(userName) && !org.springframework.util.StringUtils.hasText(passwordEncode) && !org.springframework.util.StringUtils.hasText(TOKEN)) { throw new IllegalArgumentException("请提供登录凭据"); } if (org.springframework.util.StringUtils.hasText(TOKEN)) { JwtUser zhiYunTokenUser = TokenProvider.getJWTUserByZhiYun(TOKEN); if (zhiYunTokenUser == null) { throw new UnAuthorizedException("token 无效!"); } passWord = zhiYunTokenUser.getPassword(); userName = zhiYunTokenUser.getUsername(); if (StringUtils.isBlank(userName)){ userName = zhiYunTokenUser.getUsername(); } if (StringUtils.isBlank(userName)){ userName = zhiYunTokenUser.getName(); } if (!org.springframework.util.StringUtils.hasText(passWord)) { throw new UnAuthorizedException("token 中缺少用户密码信息!"); } try { jwtUser = TzApi.foreignExchangeTradingLogin(userName, passWord, Constant.SYSTEMNAME); if (jwtUser == null) { throw new UnAuthorizedException("登录失败,用户不存在!"); } if (jwtUser.getRoleId()==4) { Date authorizeTime = jwtUser.getAuthorizeTime(); Date authorizeEndTime = jwtUser.getAuthorizeEndTime(); if (authorizeTime == null || authorizeEndTime == null) { throw new UnAuthorizedException("系统未授权!"); } Date now = new Date(); if (now.before(authorizeTime) || now.after(authorizeEndTime)) { throw new UnAuthorizedException("系统授权已过期!"); } } Userinfo user = resolveZhiYunLocalUser(zhiYunTokenUser); if (user == null) { return new ResultEntity(HttpStatus.BAD_REQUEST, "密码错误"); } JwtUser localJwtUser = toJwtUser(user); Authentication authentication = new UsernamePasswordAuthenticationToken(localJwtUser, null, localJwtUser.getAuthorities()); SecurityContextHolder.getContext().setAuthentication(authentication); String token = TokenProvider.createToken(localJwtUser); return new ResultEntity(HttpStatus.OK, buildLoginResultMap(user, token)); } catch (UnAuthorizedException e) { throw e; // 抛出授权类异常,保留原语义 } catch (Exception e) { // 抛出其他登录异常,比如远程接口失败、系统错误等 throw new RuntimeException("系统登录校验失败", e); } } throw new RuntimeException("系统登录校验失败"); } } Userinfo resolveZhiYunLocalUser(JwtUser zhiYunUser) { if (zhiYunUser == null) { return null; } if (externalResourceMappingMapper != null && StringUtils.isNotBlank(zhiYunUser.getUserId())) { ExternalResourceMapping mapping = externalResourceMappingMapper.selectByExternal( ZHIYUN_SOURCE_SYSTEM, USER_RESOURCE_TYPE, zhiYunUser.getUserId()); if (mapping != null) { if (StringUtils.isBlank(mapping.getLocalId())) { return null; } return userinfoMapper.selectByPrimaryKey(mapping.getLocalId()); } } String username = StringUtils.defaultIfBlank(zhiYunUser.getUsername(), zhiYunUser.getName()); if (StringUtils.isBlank(username)) { return null; } UserinfoExample userExample = new UserinfoExample(); userExample.createCriteria().andUsernameEqualTo(username); List userinfos = userinfoMapper.selectByExample(userExample); if (CollectionUtils.isEmpty(userinfos)) { return null; } return userinfos.get(0); } Map buildLoginResultMap(Userinfo user, String token) { Map map = new HashMap<>(); map.put("name", user.getName()); map.put("username", user.getUsername()); map.put("roleId", String.valueOf(user.getRole())); map.put("teacherAdmin", Boolean.TRUE.equals(user.getTeacherAdmin())); map.put("schoolId", user.getSchoolId()); map.put("classId", user.getSchoolClassId()); if (Integer.valueOf(4).equals(user.getRole())) { SchoolClass schoolClass = schoolClassMapper.selectByPrimaryKey(user.getSchoolClassId()); if (schoolClass == null) { map.put("className", null); } else { map.put("className", schoolClass.getClassName()); } } map.put("userId", user.getUserId()); map.put("token", token); return map; } private JwtUser toJwtUser(Userinfo user) { JwtUser jwtUser = new JwtUser(); jwtUser.setUserId(user.getUserId()); jwtUser.setName(user.getName()); jwtUser.setUsername(user.getUsername()); jwtUser.setPassword(user.getPassword()); jwtUser.setRoleId(user.getRole() == null ? 0 : user.getRole()); jwtUser.setSchoolId(user.getSchoolId()); if (StringUtils.isNumeric(user.getSchoolClassId())) { jwtUser.setClassId(Integer.valueOf(user.getSchoolClassId())); } return jwtUser; } @PostMapping("/getClassList") @ApiOperation("获取班级列表") @AnonymousAccess public Map getClassList(@RequestParam String schoolMajorId){ Map map=new HashMap<>(); SchoolClassExample schoolClassExample = new SchoolClassExample(); schoolClassExample.createCriteria().andSchoolMajorIdEqualTo(schoolMajorId); List schoolClasses = schoolClassMapper.selectByExample(schoolClassExample); for (int i = 0; i < schoolClasses.size(); i++) { SchoolClass schoolClass = schoolClasses.get(i); map.put(schoolClass.getSchoolClassId(),schoolClass.getClassName()); } return map; } }