作者 朱兆平

卡口用户登录验证OK

正在显示 20 个修改的文件 包含 732 行增加24 行删除
@@ -10,9 +10,9 @@ @@ -10,9 +10,9 @@
10 <relativePath/> <!-- lookup parent from repository --> 10 <relativePath/> <!-- lookup parent from repository -->
11 </parent> 11 </parent>
12 <groupId>com.tianbo</groupId> 12 <groupId>com.tianbo</groupId>
13 - <artifactId>warehouse</artifactId>  
14 - <version>2.2Beta</version>  
15 - <name>warehouse</name> 13 + <artifactId>usercenter</artifactId>
  14 + <version>2.3Kako</version>
  15 + <name>usercenter</name>
16 <description>usercenter for springcloud</description> 16 <description>usercenter for springcloud</description>
17 17
18 <properties> 18 <properties>
@@ -22,6 +22,7 @@ @@ -22,6 +22,7 @@
22 <lombok_sersion>1.18.6</lombok_sersion> 22 <lombok_sersion>1.18.6</lombok_sersion>
23 <swagger2_version>2.9.2</swagger2_version> 23 <swagger2_version>2.9.2</swagger2_version>
24 <shiro.version>1.2.5</shiro.version> 24 <shiro.version>1.2.5</shiro.version>
  25 + <commons-lang3.version>3.3.2</commons-lang3.version>
25 </properties> 26 </properties>
26 27
27 <dependencies> 28 <dependencies>
@@ -227,6 +228,20 @@ @@ -227,6 +228,20 @@
227 <artifactId>shiro-core</artifactId> 228 <artifactId>shiro-core</artifactId>
228 <version>${shiro.version}</version> 229 <version>${shiro.version}</version>
229 </dependency> 230 </dependency>
  231 +
  232 + <dependency>
  233 + <groupId>org.apache.commons</groupId>
  234 + <artifactId>commons-lang3</artifactId>
  235 + <version>${commons-lang3.version}</version>
  236 + </dependency>
  237 +
  238 + <!-- 验证码配置-->
  239 + <dependency>
  240 + <groupId>com.github.axet</groupId>
  241 + <artifactId>kaptcha</artifactId>
  242 + <version>0.0.9</version>
  243 + </dependency>
  244 +
230 </dependencies> 245 </dependencies>
231 246
232 <dependencyManagement> 247 <dependencyManagement>
1 package com.tianbo.warehouse.controller; 1 package com.tianbo.warehouse.controller;
2 2
  3 +import com.google.code.kaptcha.Constants;
  4 +import com.google.code.kaptcha.impl.DefaultKaptcha;
  5 +import com.google.code.kaptcha.util.Config;
3 import com.tianbo.warehouse.model.USERS; 6 import com.tianbo.warehouse.model.USERS;
4 import com.tianbo.warehouse.service.UserService; 7 import com.tianbo.warehouse.service.UserService;
  8 +import com.tianbo.warehouse.util.RedisUtils;
  9 +import lombok.extern.slf4j.Slf4j;
5 import org.springframework.beans.factory.annotation.Autowired; 10 import org.springframework.beans.factory.annotation.Autowired;
  11 +import org.springframework.context.annotation.Bean;
6 import org.springframework.web.bind.annotation.GetMapping; 12 import org.springframework.web.bind.annotation.GetMapping;
  13 +import org.springframework.web.bind.annotation.RequestMapping;
7 import org.springframework.web.bind.annotation.RestController; 14 import org.springframework.web.bind.annotation.RestController;
8 15
  16 +import javax.imageio.ImageIO;
  17 +import javax.servlet.ServletOutputStream;
  18 +import javax.servlet.http.HttpServletRequest;
  19 +import javax.servlet.http.HttpServletResponse;
  20 +import javax.servlet.http.HttpSession;
  21 +import java.awt.image.BufferedImage;
  22 +import java.io.IOException;
9 import java.util.List; 23 import java.util.List;
  24 +import java.util.Properties;
10 25
  26 +@Slf4j
11 @RestController 27 @RestController
12 public class MainController { 28 public class MainController {
13 29
14 @Autowired 30 @Autowired
15 - UserService userService; 31 + private DefaultKaptcha captchaProducer;
  32 +
  33 + @Autowired
  34 + private UserService userService;
  35 +
  36 + @Autowired
  37 + private RedisUtils redisUtils;
16 38
17 @GetMapping("/error") 39 @GetMapping("/error")
18 public String error(){ 40 public String error(){
@@ -23,4 +45,75 @@ public class MainController { @@ -23,4 +45,75 @@ public class MainController {
23 public String main(){ 45 public String main(){
24 return "main"; 46 return "main";
25 } 47 }
  48 +
  49 + /**
  50 + * 生成验证码
  51 + */
  52 + @RequestMapping(value = "/randCode")
  53 + public void getRandCode(HttpServletRequest request, HttpServletResponse response){
  54 +
  55 + HttpSession session = request.getSession();
  56 +
  57 +
  58 + response.setDateHeader("Expires", 0);
  59 +
  60 + // Set standard HTTP/1.1 no-cache headers.
  61 + response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
  62 +
  63 + // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
  64 + response.addHeader("Cache-Control", "post-check=0, pre-check=0");
  65 +
  66 + // Set standard HTTP/1.0 no-cache header.
  67 + response.setHeader("Pragma", "no-cache");
  68 +
  69 + // 设置返回文件类型
  70 + response.setContentType("image/jpeg");
  71 +
  72 + // 获取验证码上的文字
  73 + String capText = captchaProducer.createText();
  74 +
  75 + // 将验证码上的文字保存在session中
  76 + session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
  77 +
  78 + //缓存存储登录验证码信息
  79 + redisUtils.set(session.getId(),capText,60);
  80 +
  81 +
  82 + String code = (String)session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
  83 +
  84 + log.info("验证码为:"+code);
  85 +
  86 +
  87 + // 将文件渲染到图片上
  88 + BufferedImage bi = captchaProducer.createImage(capText);
  89 + ServletOutputStream out = null;
  90 + try {
  91 + out = response.getOutputStream();
  92 + ImageIO.write(bi, "jpeg", out);
  93 + out.flush();
  94 + } catch (IOException e) {
  95 + e.printStackTrace();
  96 + }
  97 +
  98 +
  99 + }
  100 +
  101 + /*声明验证码生成策略属性 Bean*/
  102 + @Bean
  103 + public DefaultKaptcha captchaProducer(){
  104 + DefaultKaptcha captchaProducer =new DefaultKaptcha();
  105 + Properties properties =new Properties();
  106 + properties.setProperty("kaptcha.border","yes");
  107 + properties.setProperty("kaptcha.border.color","105,179,90");
  108 + properties.setProperty("kaptcha.textproducer.font.color","red");
  109 + properties.setProperty("kaptcha.image.width","125");
  110 + properties.setProperty("kaptcha.image.height","60");
  111 + properties.setProperty("kaptcha.textproducer.font.size","36");
  112 + properties.setProperty("kaptcha.session.key","code");
  113 + properties.setProperty("kaptcha.textproducer.char.length","4");
  114 + properties.setProperty("kaptcha.textproducer.font.names","宋体,楷体,微软雅黑");
  115 + Config config=new Config(properties);
  116 + captchaProducer.setConfig(config);
  117 + return captchaProducer;
  118 + }
26 } 119 }
@@ -35,9 +35,9 @@ import java.util.Map; @@ -35,9 +35,9 @@ import java.util.Map;
35 35
36 @RestController 36 @RestController
37 @Slf4j 37 @Slf4j
38 -@RequestMapping("/user") 38 +@RequestMapping("/olduser")
39 @Api("swaggerDemoController相关的api") 39 @Api("swaggerDemoController相关的api")
40 -public class UserController { 40 +public class OldUserController {
41 41
42 @Autowired 42 @Autowired
43 UserService userService; 43 UserService userService;
  1 +package com.tianbo.warehouse.controller.kako;
  2 +
  3 +import com.alibaba.fastjson.JSON;
  4 +import com.github.pagehelper.PageInfo;
  5 +import com.google.code.kaptcha.Constants;
  6 +import com.google.code.kaptcha.impl.DefaultKaptcha;
  7 +import com.google.code.kaptcha.util.Config;
  8 +import com.tianbo.warehouse.annotation.LogAnnotation;
  9 +import com.tianbo.warehouse.annotation.RequestRequire;
  10 +import com.tianbo.warehouse.annotation.UserPasswordMd5;
  11 +import com.tianbo.warehouse.annotation.cache.annotation.RedisCacheDelTarget;
  12 +import com.tianbo.warehouse.controller.response.ResultJson;
  13 +import com.tianbo.warehouse.dao.KakoUserMapper;
  14 +import com.tianbo.warehouse.model.KakoUser;
  15 +import com.tianbo.warehouse.model.KakoUserRole;
  16 +import com.tianbo.warehouse.model.USERS;
  17 +import com.tianbo.warehouse.model.UserRole;
  18 +import com.tianbo.warehouse.security.CustomUserDetailService;
  19 +import com.tianbo.warehouse.service.UserService;
  20 +import com.tianbo.warehouse.service.kakoImp.KakoUserService;
  21 +import com.tianbo.warehouse.service.validated.InsertUser;
  22 +import com.tianbo.warehouse.service.validated.UpdateUser;
  23 +import com.tianbo.warehouse.util.RedisUtils;
  24 +import io.swagger.annotations.Api;
  25 +import io.swagger.annotations.ApiImplicitParam;
  26 +import io.swagger.annotations.ApiImplicitParams;
  27 +import io.swagger.annotations.ApiOperation;
  28 +import lombok.extern.slf4j.Slf4j;
  29 +import org.springframework.beans.factory.annotation.Autowired;
  30 +import org.springframework.context.annotation.Bean;
  31 +import org.springframework.security.core.context.SecurityContextHolder;
  32 +import org.springframework.security.core.userdetails.UserDetails;
  33 +import org.springframework.validation.BindingResult;
  34 +import org.springframework.validation.annotation.Validated;
  35 +import org.springframework.web.bind.annotation.*;
  36 +
  37 +import javax.annotation.Resource;
  38 +import javax.imageio.ImageIO;
  39 +import javax.servlet.ServletOutputStream;
  40 +import javax.servlet.http.HttpServletRequest;
  41 +import javax.servlet.http.HttpServletResponse;
  42 +import javax.servlet.http.HttpSession;
  43 +import java.awt.image.BufferedImage;
  44 +import java.io.IOException;
  45 +import java.util.List;
  46 +import java.util.Map;
  47 +import java.util.Properties;
  48 +
  49 +@RestController
  50 +@Slf4j
  51 +@RequestMapping("/user")
  52 +@Api("swaggerDemoController相关的api")
  53 +public class UserController {
  54 +
  55 + @Autowired
  56 + private KakoUserService userService;
  57 +
  58 + @Autowired
  59 + private CustomUserDetailService userDetailService;
  60 +
  61 + @Autowired
  62 + private RedisUtils redisUtils;
  63 +
  64 + @ApiOperation(value = "查询用户列表及信息", notes = "查询用户列表及单个用户信息")
  65 + @ApiImplicitParams({@ApiImplicitParam(name = "pageNum", value = "分页-当前页", required = false, dataType = "int",defaultValue = "1"),
  66 + @ApiImplicitParam(name = "pageSize", value = "分页-每页显示多少条", required = false, dataType = "int",defaultValue = "5")})
  67 + @RequestRequire
  68 + @GetMapping("/list")
  69 + public ResultJson<PageInfo> list(@RequestParam(value = "pageNum",required = false,defaultValue = "1")
  70 + int pageNum,
  71 + @RequestParam(value = "pageSize",required = false,defaultValue = "5")
  72 + int pageSize,
  73 + @RequestParam(value = "userName",required = false) String username,
  74 + @RequestParam(value = "realName",required = false) String realname)
  75 + {
  76 +
  77 + PageInfo<KakoUser> usersPageInfo = userService.selectAllUser(pageNum,pageSize, username, realname);
  78 + return new ResultJson("200","success",usersPageInfo);
  79 + }
  80 +
  81 + public String getCurrentUser(){
  82 +
  83 + //通过session获取当前登录的用户信息
  84 + UserDetails userDetails =(UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
  85 + return userDetails.getUsername();
  86 + }
  87 +
  88 + @LogAnnotation(moduleName = "用户管理",operate = "用户编辑")
  89 + @PutMapping("/edit")
  90 + public ResultJson updateUserById(@Validated(UpdateUser.class) @RequestBody KakoUser user){
  91 + user.setPassword(null);
  92 + int i = userService.updateByPrimaryKeySelective(user);
  93 + ResultJson resultJson = new ResultJson();
  94 + return i==1 ? new ResultJson("200","success") :new ResultJson("500","update faild");
  95 +
  96 + }
  97 +
  98 + @LogAnnotation(moduleName = "用户管理",operate = "用户密码修改")
  99 + @PutMapping("/password")
  100 + public ResultJson updateUserPassById(@RequestBody KakoUser user){
  101 + int i = userService.updateByPrimaryKeySelective(user);
  102 + return i==1 ? new ResultJson("200","success") :new ResultJson("500","update faild");
  103 + }
  104 +
  105 + @LogAnnotation(moduleName = "用户管理",operate = "用户添加")
  106 + @PostMapping("/add")
  107 + public ResultJson addUser(@RequestBody @Validated(InsertUser.class) KakoUser user, HttpServletRequest request, HttpServletResponse response, BindingResult bindingResult){
  108 +
  109 + if (bindingResult.hasErrors()){
  110 + String s = bindingResult.toString();
  111 + }
  112 +
  113 + int i = userService.insertSelective(user);
  114 + ResultJson resultJson = new ResultJson();
  115 + return i==1 ? new ResultJson("200","新建账户成功") :new ResultJson("500","insert faild");
  116 +
  117 + }
  118 +
  119 + @LogAnnotation(moduleName = "用户管理",operate = "用户删除")
  120 + @DeleteMapping("/del")
  121 + public ResultJson delUser(@RequestBody KakoUser user,HttpServletRequest request,HttpServletResponse response){
  122 + //String username = getusername();
  123 + int i = userService.deleteByPrimaryKey(user);
  124 + ResultJson resultJson = new ResultJson();
  125 + return i==1 ? new ResultJson("200","删除账户成功") :new ResultJson("500","delete faild");
  126 + }
  127 +
  128 + @PutMapping("/roleset")
  129 + public ResultJson roleSet(@RequestBody Map<String,Object> map,HttpServletRequest request,HttpServletResponse respons){
  130 + String id = map.get("userId").toString();
  131 + List<Integer> roles = (List<Integer>) map.get("roleIds");
  132 + KakoUserRole userRole = new KakoUserRole();
  133 + userRole.setUserId(id);
  134 + userRole.setRoleIds(roles);
  135 + int i = userService.setUserRole(userRole);
  136 + return i==1 ? new ResultJson("200","设置角色成功") :new ResultJson("500","设置角色失败");
  137 + }
  138 +
  139 + /**
  140 + * 刷新redis权限缓存
  141 + */
  142 + @ApiOperation(value = "更新用户权限缓存", notes = "重新生成用户的信息到redis")
  143 + @RedisCacheDelTarget(cacheKey = "com.tianbo.warehouse.service.imp.PermissionServiceImp")
  144 + @PutMapping("/resetToken")
  145 + public ResultJson resetToken(HttpServletRequest request,HttpServletResponse respons) {
  146 + /**
  147 + * 更新目标用户的权限缓存
  148 + */
  149 + String authHeader = request.getHeader("Authorization");
  150 + if (authHeader != null && authHeader.startsWith("Bearer ")) {
  151 + final String authToken = authHeader.substring("Bearer ".length());
  152 + try {
  153 + String userJson = redisUtils.get(authToken);
  154 + if (userJson != null) {
  155 + KakoUser u = JSON.parseObject(userJson, KakoUser.class);
  156 + String username = u.getUsername();
  157 +
  158 +// String username = JwtTokenUtil.parseToken(authToken);
  159 + if (username != null) {
  160 + UserDetails userDetails = userDetailService.loadUserByUsername(username);
  161 + if (userDetails != null) {
  162 + String json = JSON.toJSONString(userDetails);
  163 + redisUtils.set(authToken, json, 3600 * 24 * 7);
  164 + return new ResultJson("200", "缓存更新成功");
  165 + }
  166 + }
  167 + }
  168 + }catch (Exception e){
  169 + log.error(e.toString());
  170 + return new ResultJson("500","缓存更新失败");
  171 + }
  172 + }
  173 + return new ResultJson("500","缓存更新失败");
  174 + }
  175 +
  176 +}
@@ -19,5 +19,9 @@ public interface KakoUserMapper { @@ -19,5 +19,9 @@ public interface KakoUserMapper {
19 19
20 List<KakoUser> selectByUsername(String userName); 20 List<KakoUser> selectByUsername(String userName);
21 21
  22 + List<KakoUser> selectAllUser(KakoUser record);
  23 +
22 int lockUser(KakoUser record); 24 int lockUser(KakoUser record);
  25 +
  26 +
23 } 27 }
1 package com.tianbo.warehouse.dao; 1 package com.tianbo.warehouse.dao;
2 2
  3 +import com.tianbo.warehouse.model.KakoUserRole;
3 import com.tianbo.warehouse.model.UserRole; 4 import com.tianbo.warehouse.model.UserRole;
4 5
5 public interface UserRoleMapper { 6 public interface UserRoleMapper {
@@ -7,10 +8,14 @@ public interface UserRoleMapper { @@ -7,10 +8,14 @@ public interface UserRoleMapper {
7 8
8 int deleteByUserId(Integer userId); 9 int deleteByUserId(Integer userId);
9 10
  11 + int deleteByUserIdKako(String userId);
  12 +
10 int insert(UserRole record); 13 int insert(UserRole record);
11 14
12 int insertSelective(UserRole record); 15 int insertSelective(UserRole record);
13 16
  17 + int insertSelectiveKako(KakoUserRole record);
  18 +
14 UserRole selectByPrimaryKey(Integer id); 19 UserRole selectByPrimaryKey(Integer id);
15 20
16 int updateByPrimaryKeySelective(UserRole record); 21 int updateByPrimaryKeySelective(UserRole record);
@@ -2,10 +2,16 @@ package com.tianbo.warehouse.model; @@ -2,10 +2,16 @@ package com.tianbo.warehouse.model;
2 2
3 import com.alibaba.fastjson.annotation.JSONField; 3 import com.alibaba.fastjson.annotation.JSONField;
4 import com.alibaba.fastjson.serializer.SerializerFeature; 4 import com.alibaba.fastjson.serializer.SerializerFeature;
  5 +import com.tianbo.warehouse.service.validated.InsertUser;
  6 +import com.tianbo.warehouse.service.validated.UpdateUser;
  7 +import com.tianbo.warehouse.validate.CheckUserExist;
  8 +import org.hibernate.validator.constraints.Length;
5 import org.springframework.security.core.GrantedAuthority; 9 import org.springframework.security.core.GrantedAuthority;
6 import org.springframework.security.core.authority.SimpleGrantedAuthority; 10 import org.springframework.security.core.authority.SimpleGrantedAuthority;
7 import org.springframework.security.core.userdetails.UserDetails; 11 import org.springframework.security.core.userdetails.UserDetails;
8 12
  13 +import javax.validation.constraints.NotBlank;
  14 +import javax.validation.constraints.NotNull;
9 import java.util.ArrayList; 15 import java.util.ArrayList;
10 import java.util.Collection; 16 import java.util.Collection;
11 import java.util.Date; 17 import java.util.Date;
@@ -18,8 +24,13 @@ public class KakoUser implements UserDetails { @@ -18,8 +24,13 @@ public class KakoUser implements UserDetails {
18 24
19 private String officeId; 25 private String officeId;
20 26
  27 + @NotBlank(message="用户名不能为空",groups={InsertUser.class, UpdateUser.class})
  28 + @Length(min = 4, max = 11, message = "username 长度必须在 {min} - {max} 之间",groups={InsertUser.class, UpdateUser.class})
21 private String loginName; 29 private String loginName;
22 30
  31 + @NotNull(message="密码不能为null",groups=InsertUser.class)
  32 + @NotBlank(message="密码不能为空",groups=InsertUser.class)
  33 + @Length(min = 6, max = 22, message = "密码 长度必须在 {min} - {max} 之间",groups=InsertUser.class)
23 private String password; 34 private String password;
24 35
25 private String no; 36 private String no;
  1 +package com.tianbo.warehouse.model;
  2 +
  3 +import lombok.Data;
  4 +
  5 +import javax.validation.constraints.DecimalMin;
  6 +import java.util.List;
  7 +
  8 +@Data
  9 +public class KakoUserRole {
  10 +
  11 + @DecimalMin("1")
  12 + private Integer id;
  13 +
  14 + private String userId;
  15 +
  16 + @DecimalMin("1")
  17 + private Integer roleId;
  18 +
  19 + private List<Integer> roleIds;
  20 +
  21 + public KakoUserRole(){
  22 + }
  23 + public KakoUserRole(Integer id, String userId, Integer roleId){
  24 + this.id = id;
  25 + this.roleId=roleId;
  26 + this.userId = userId;
  27 + }
  28 + public KakoUserRole(String userId, Integer roleId){
  29 + this.roleId=roleId;
  30 + this.userId = userId;
  31 + }
  32 +}
@@ -49,6 +49,8 @@ public class MyAccessDecisionManager implements AccessDecisionManager{ @@ -49,6 +49,8 @@ public class MyAccessDecisionManager implements AccessDecisionManager{
49 if(needRole.trim().equals(ga.getAuthority())) { 49 if(needRole.trim().equals(ga.getAuthority())) {
50 return; 50 return;
51 } 51 }
  52 +
  53 + if("ROLE_ANONYMOUS".equals(ga.getAuthority())) {return;};
52 } 54 }
53 } 55 }
54 throw new AccessDeniedException("权限不足!"); 56 throw new AccessDeniedException("权限不足!");
@@ -11,6 +11,7 @@ import org.springframework.security.web.util.matcher.AntPathRequestMatcher; @@ -11,6 +11,7 @@ import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
11 import org.springframework.stereotype.Service; 11 import org.springframework.stereotype.Service;
12 import org.springframework.util.AntPathMatcher; 12 import org.springframework.util.AntPathMatcher;
13 13
  14 +import javax.annotation.Resource;
14 import javax.servlet.http.HttpServletRequest; 15 import javax.servlet.http.HttpServletRequest;
15 import java.util.*; 16 import java.util.*;
16 17
@@ -21,8 +22,9 @@ import java.util.*; @@ -21,8 +22,9 @@ import java.util.*;
21 @Service 22 @Service
22 public class MyInvocationSecurityMetadataSourceService implements FilterInvocationSecurityMetadataSource{ 23 public class MyInvocationSecurityMetadataSourceService implements FilterInvocationSecurityMetadataSource{
23 24
24 - @Autowired  
25 - PERMISSIONMapper permissionMapper; 25 + @Resource
  26 + private PERMISSIONMapper permissionMapper;
  27 +
26 AntPathMatcher pathMatcher = new AntPathMatcher(); 28 AntPathMatcher pathMatcher = new AntPathMatcher();
27 29
28 private HashMap<String, Collection<ConfigAttribute>> map =null; 30 private HashMap<String, Collection<ConfigAttribute>> map =null;
1 package com.tianbo.warehouse.security.config; 1 package com.tianbo.warehouse.security.config;
2 2
3 import com.tianbo.warehouse.security.CustomUserDetailService; 3 import com.tianbo.warehouse.security.CustomUserDetailService;
4 -import com.tianbo.warehouse.security.filter.JwtAuthenticationTokenFilter;  
5 import com.tianbo.warehouse.security.handel.*; 4 import com.tianbo.warehouse.security.handel.*;
6 import com.tianbo.warehouse.security.MyFilterSecurityInterceptor; 5 import com.tianbo.warehouse.security.MyFilterSecurityInterceptor;
  6 +import com.tianbo.warehouse.security.handel.kakologin.KakoJwtAuthenticationTokenFilter;
7 import com.tianbo.warehouse.security.handel.kakologin.MyKakoAuthenticationSuccessHandler; 7 import com.tianbo.warehouse.security.handel.kakologin.MyKakoAuthenticationSuccessHandler;
8 import com.tianbo.warehouse.security.handel.kakologin.MyLoginAuthenticationProcessFilter; 8 import com.tianbo.warehouse.security.handel.kakologin.MyLoginAuthenticationProcessFilter;
9 import org.springframework.beans.factory.annotation.Autowired; 9 import org.springframework.beans.factory.annotation.Autowired;
@@ -54,7 +54,7 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @@ -54,7 +54,7 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
54 private MyAuthenticationEntryPoint authenticationEntryPoint; 54 private MyAuthenticationEntryPoint authenticationEntryPoint;
55 55
56 @Autowired 56 @Autowired
57 - private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter; 57 + private KakoJwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;
58 58
59 private final MyLoginAuthenticationProcessFilter adminAuthenticationProcessingFilter; 59 private final MyLoginAuthenticationProcessFilter adminAuthenticationProcessingFilter;
60 60
@@ -92,7 +92,7 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @@ -92,7 +92,7 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
92 //跨域配置 92 //跨域配置
93 .requestMatchers(CorsUtils::isPreFlightRequest).permitAll() 93 .requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
94 //管理页面只允许管理员角色访问 94 //管理页面只允许管理员角色访问
95 - .antMatchers("/admin/**","/ROLE/**","/user/**").authenticated() 95 + .antMatchers("/admin/**","/ROLE/**","/user/**","/perm/**","/role/**").authenticated()
96 //任何请求,登录后可以访问 96 //任何请求,登录后可以访问
97 //其余的不需要验证 97 //其余的不需要验证
98 .anyRequest().permitAll() 98 .anyRequest().permitAll()
  1 +/**
  2 + * Copyright (c) 2005-2012 springside.org.cn
  3 + */
  4 +package com.tianbo.warehouse.security.handel.kakologin;
  5 +
  6 +import org.apache.commons.lang3.Validate;
  7 +
  8 +import java.io.IOException;
  9 +import java.io.InputStream;
  10 +import java.security.GeneralSecurityException;
  11 +import java.security.MessageDigest;
  12 +import java.security.SecureRandom;
  13 +
  14 +/**
  15 + * 支持SHA-1/MD5消息摘要的工具类.
  16 + *
  17 + * 返回ByteSource,可进一步被编码为Hex, Base64或UrlSafeBase64
  18 + *
  19 + * @author calvin
  20 + */
  21 +public class Digests {
  22 +
  23 + private static final String SHA1 = "SHA-1";
  24 + private static final String MD5 = "MD5";
  25 +
  26 + private static SecureRandom random = new SecureRandom();
  27 +
  28 + /**
  29 + * 对输入字符串进行md5散列.
  30 + */
  31 + public static byte[] md5(byte[] input) {
  32 + return digest(input, MD5, null, 1);
  33 + }
  34 + public static byte[] md5(byte[] input, int iterations) {
  35 + return digest(input, MD5, null, iterations);
  36 + }
  37 +
  38 + /**
  39 + * 对输入字符串进行sha1散列.
  40 + */
  41 + public static byte[] sha1(byte[] input) {
  42 + return digest(input, SHA1, null, 1);
  43 + }
  44 +
  45 + public static byte[] sha1(byte[] input, byte[] salt) {
  46 + return digest(input, SHA1, salt, 1);
  47 + }
  48 +
  49 + public static byte[] sha1(byte[] input, byte[] salt, int iterations) {
  50 + return digest(input, SHA1, salt, iterations);
  51 + }
  52 +
  53 + /**
  54 + * 对字符串进行散列, 支持md5与sha1算法.
  55 + */
  56 + private static byte[] digest(byte[] input, String algorithm, byte[] salt, int iterations) {
  57 + try {
  58 + MessageDigest digest = MessageDigest.getInstance(algorithm);
  59 +
  60 + if (salt != null) {
  61 + digest.update(salt);
  62 + }
  63 +
  64 + byte[] result = digest.digest(input);
  65 +
  66 + for (int i = 1; i < iterations; i++) {
  67 + digest.reset();
  68 + result = digest.digest(result);
  69 + }
  70 + return result;
  71 + } catch (GeneralSecurityException e) {
  72 + throw Exceptions.unchecked(e);
  73 + }
  74 + }
  75 +
  76 + /**
  77 + * 生成随机的Byte[]作为salt.
  78 + *
  79 + * @param numBytes byte数组的大小
  80 + */
  81 + public static byte[] generateSalt(int numBytes) {
  82 + Validate.isTrue(numBytes > 0, "numBytes argument must be a positive integer (1 or larger)", numBytes);
  83 +
  84 + byte[] bytes = new byte[numBytes];
  85 + random.nextBytes(bytes);
  86 + return bytes;
  87 + }
  88 +
  89 + /**
  90 + * 对文件进行md5散列.
  91 + */
  92 + public static byte[] md5(InputStream input) throws IOException {
  93 + return digest(input, MD5);
  94 + }
  95 +
  96 + /**
  97 + * 对文件进行sha1散列.
  98 + */
  99 + public static byte[] sha1(InputStream input) throws IOException {
  100 + return digest(input, SHA1);
  101 + }
  102 +
  103 + private static byte[] digest(InputStream input, String algorithm) throws IOException {
  104 + try {
  105 + MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
  106 + int bufferLength = 8 * 1024;
  107 + byte[] buffer = new byte[bufferLength];
  108 + int read = input.read(buffer, 0, bufferLength);
  109 +
  110 + while (read > -1) {
  111 + messageDigest.update(buffer, 0, read);
  112 + read = input.read(buffer, 0, bufferLength);
  113 + }
  114 +
  115 + return messageDigest.digest();
  116 + } catch (GeneralSecurityException e) {
  117 + throw Exceptions.unchecked(e);
  118 + }
  119 + }
  120 +
  121 +}
@@ -6,8 +6,11 @@ package com.tianbo.warehouse.security.handel.kakologin; @@ -6,8 +6,11 @@ package com.tianbo.warehouse.security.handel.kakologin;
6 import org.apache.commons.codec.DecoderException; 6 import org.apache.commons.codec.DecoderException;
7 import org.apache.commons.codec.binary.Base64; 7 import org.apache.commons.codec.binary.Base64;
8 import org.apache.commons.codec.binary.Hex; 8 import org.apache.commons.codec.binary.Hex;
  9 +import org.apache.commons.lang3.StringEscapeUtils;
9 10
10 import java.io.UnsupportedEncodingException; 11 import java.io.UnsupportedEncodingException;
  12 +import java.net.URLDecoder;
  13 +import java.net.URLEncoder;
11 14
12 /** 15 /**
13 * 封装各种格式的编码解码工具类. 16 * 封装各种格式的编码解码工具类.
@@ -95,4 +98,55 @@ public class Encodes { @@ -95,4 +98,55 @@ public class Encodes {
95 return new String(chars); 98 return new String(chars);
96 } 99 }
97 100
  101 + /**
  102 + * Html 转码.
  103 + */
  104 + public static String escapeHtml(String html) {
  105 + return StringEscapeUtils.escapeHtml4(html);
  106 + }
  107 +
  108 + /**
  109 + * Html 解码.
  110 + */
  111 + public static String unescapeHtml(String htmlEscaped) {
  112 + return StringEscapeUtils.unescapeHtml4(htmlEscaped);
  113 + }
  114 +
  115 + /**
  116 + * Xml 转码.
  117 + */
  118 + public static String escapeXml(String xml) {
  119 + return StringEscapeUtils.escapeXml10(xml);
  120 + }
  121 +
  122 + /**
  123 + * Xml 解码.
  124 + */
  125 + public static String unescapeXml(String xmlEscaped) {
  126 + return StringEscapeUtils.unescapeXml(xmlEscaped);
  127 + }
  128 +
  129 + /**
  130 + * URL 编码, Encode默认为UTF-8.
  131 + */
  132 + public static String urlEncode(String part) {
  133 + try {
  134 + return URLEncoder.encode(part, DEFAULT_URL_ENCODING);
  135 + } catch (UnsupportedEncodingException e) {
  136 + throw Exceptions.unchecked(e);
  137 + }
  138 + }
  139 +
  140 + /**
  141 + * URL 解码, Encode默认为UTF-8.
  142 + */
  143 + public static String urlDecode(String part) {
  144 +
  145 + try {
  146 + return URLDecoder.decode(part, DEFAULT_URL_ENCODING);
  147 + } catch (UnsupportedEncodingException e) {
  148 + throw Exceptions.unchecked(e);
  149 + }
  150 + }
  151 +
98 } 152 }
1 -package com.tianbo.warehouse.security.filter; 1 +package com.tianbo.warehouse.security.handel.kakologin;
2 2
3 import com.alibaba.fastjson.JSON; 3 import com.alibaba.fastjson.JSON;
4 -import com.alibaba.fastjson.JSONObject; 4 +import com.tianbo.warehouse.model.KakoUser;
5 import com.tianbo.warehouse.model.USERS; 5 import com.tianbo.warehouse.model.USERS;
6 import com.tianbo.warehouse.security.CustomUserDetailService; 6 import com.tianbo.warehouse.security.CustomUserDetailService;
7 import com.tianbo.warehouse.util.RedisUtils; 7 import com.tianbo.warehouse.util.RedisUtils;
@@ -9,7 +9,6 @@ import lombok.extern.slf4j.Slf4j; @@ -9,7 +9,6 @@ import lombok.extern.slf4j.Slf4j;
9 import org.springframework.beans.factory.annotation.Autowired; 9 import org.springframework.beans.factory.annotation.Autowired;
10 import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 10 import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
11 import org.springframework.security.core.context.SecurityContextHolder; 11 import org.springframework.security.core.context.SecurityContextHolder;
12 -import org.springframework.security.core.userdetails.User;  
13 import org.springframework.security.core.userdetails.UserDetails; 12 import org.springframework.security.core.userdetails.UserDetails;
14 import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; 13 import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
15 import org.springframework.stereotype.Component; 14 import org.springframework.stereotype.Component;
@@ -17,8 +16,6 @@ import org.springframework.web.filter.OncePerRequestFilter; @@ -17,8 +16,6 @@ import org.springframework.web.filter.OncePerRequestFilter;
17 16
18 import javax.servlet.FilterChain; 17 import javax.servlet.FilterChain;
19 import javax.servlet.ServletException; 18 import javax.servlet.ServletException;
20 -import javax.servlet.ServletRequest;  
21 -import javax.servlet.ServletResponse;  
22 import javax.servlet.http.HttpServletRequest; 19 import javax.servlet.http.HttpServletRequest;
23 import javax.servlet.http.HttpServletResponse; 20 import javax.servlet.http.HttpServletResponse;
24 import java.io.IOException; 21 import java.io.IOException;
@@ -31,13 +28,13 @@ import java.io.IOException; @@ -31,13 +28,13 @@ import java.io.IOException;
31 */ 28 */
32 @Slf4j 29 @Slf4j
33 @Component 30 @Component
34 -public class JwtAuthenticationTokenFilter extends OncePerRequestFilter{ 31 +public class KakoJwtAuthenticationTokenFilter extends OncePerRequestFilter{
35 32
36 @Autowired 33 @Autowired
37 RedisUtils redisUtils; 34 RedisUtils redisUtils;
38 35
39 @Autowired 36 @Autowired
40 - CustomUserDetailService userDetailService; 37 + KakoUserDetailService userDetailService;
41 38
42 @Override 39 @Override
43 protected void doFilterInternal( 40 protected void doFilterInternal(
@@ -56,7 +53,7 @@ public class JwtAuthenticationTokenFilter extends OncePerRequestFilter{ @@ -56,7 +53,7 @@ public class JwtAuthenticationTokenFilter extends OncePerRequestFilter{
56 String userJson = redisUtils.get(authToken); 53 String userJson = redisUtils.get(authToken);
57 try { 54 try {
58 if (userJson!=null){ 55 if (userJson!=null){
59 - USERS u = JSON.parseObject(userJson,USERS.class); 56 + KakoUser u = JSON.parseObject(userJson,KakoUser.class);
60 String username = u.getUsername(); 57 String username = u.getUsername();
61 //有JWT 没有登录,去JWT的 信息 获取用户信息,赋予登录 58 //有JWT 没有登录,去JWT的 信息 获取用户信息,赋予登录
62 if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) { 59 if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
@@ -69,6 +69,7 @@ public class MyKakoAuthenticationSuccessHandler extends SavedRequestAwareAuthent @@ -69,6 +69,7 @@ public class MyKakoAuthenticationSuccessHandler extends SavedRequestAwareAuthent
69 loginedUser.setLoginName(user.getUsername()); 69 loginedUser.setLoginName(user.getUsername());
70 loginedUser.setId(user.getId()); 70 loginedUser.setId(user.getId());
71 loginedUser.setName(user.getName()); 71 loginedUser.setName(user.getName());
  72 + loginedUser.setRoles(user.getRoles());
72 73
73 74
74 //设置用户的TOKEN的有效时间,时间配置在配置文件中设置 75 //设置用户的TOKEN的有效时间,时间配置在配置文件中设置
1 package com.tianbo.warehouse.security.handel.kakologin; 1 package com.tianbo.warehouse.security.handel.kakologin;
2 2
3 3
  4 +import com.google.code.kaptcha.Constants;
4 import com.tianbo.warehouse.security.handel.MyAuthenticationFailHandler; 5 import com.tianbo.warehouse.security.handel.MyAuthenticationFailHandler;
  6 +import com.tianbo.warehouse.util.RedisUtils;
5 import lombok.extern.slf4j.Slf4j; 7 import lombok.extern.slf4j.Slf4j;
  8 +import org.springframework.beans.factory.annotation.Autowired;
6 import org.springframework.security.authentication.AuthenticationServiceException; 9 import org.springframework.security.authentication.AuthenticationServiceException;
  10 +import org.springframework.security.authentication.BadCredentialsException;
7 import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 11 import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
8 import org.springframework.security.core.Authentication; 12 import org.springframework.security.core.Authentication;
9 import org.springframework.security.core.AuthenticationException; 13 import org.springframework.security.core.AuthenticationException;
10 import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter; 14 import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
  15 +import org.springframework.security.web.authentication.preauth.PreAuthenticatedCredentialsNotFoundException;
11 import org.springframework.security.web.util.matcher.AntPathRequestMatcher; 16 import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
12 import org.springframework.stereotype.Component; 17 import org.springframework.stereotype.Component;
13 18
14 import javax.servlet.http.HttpServletRequest; 19 import javax.servlet.http.HttpServletRequest;
15 import javax.servlet.http.HttpServletResponse; 20 import javax.servlet.http.HttpServletResponse;
  21 +import javax.servlet.http.HttpSession;
16 22
17 /** 23 /**
18 * 用户登录自定义校验过滤器 24 * 用户登录自定义校验过滤器
@@ -20,6 +26,10 @@ import javax.servlet.http.HttpServletResponse; @@ -20,6 +26,10 @@ import javax.servlet.http.HttpServletResponse;
20 @Slf4j 26 @Slf4j
21 @Component 27 @Component
22 public class MyLoginAuthenticationProcessFilter extends AbstractAuthenticationProcessingFilter { 28 public class MyLoginAuthenticationProcessFilter extends AbstractAuthenticationProcessingFilter {
  29 +
  30 + @Autowired
  31 + private RedisUtils redisUtils;
  32 +
23 /** 33 /**
24 * @param authenticationManager: 认证管理器 34 * @param authenticationManager: 认证管理器
25 * @param adminAuthenticationSuccessHandler: 认证成功处理 35 * @param adminAuthenticationSuccessHandler: 认证成功处理
@@ -42,9 +52,25 @@ public class MyLoginAuthenticationProcessFilter extends AbstractAuthenticationPr @@ -42,9 +52,25 @@ public class MyLoginAuthenticationProcessFilter extends AbstractAuthenticationPr
42 try { 52 try {
43 String loginUserName = request.getParameter("username"); 53 String loginUserName = request.getParameter("username");
44 String loginUserPass = request.getParameter("password"); 54 String loginUserPass = request.getParameter("password");
  55 + String loginVerify = request.getParameter("verify");
  56 +
  57 +// //验证码判断
  58 +// HttpSession session = request.getSession();
  59 +// String verify = "";
  60 +//// String verify = redisUtils.get(session.getId());
  61 +// if (session.getAttribute(Constants.KAPTCHA_SESSION_KEY)!=null){
  62 +// verify = session.getAttribute(Constants.KAPTCHA_SESSION_KEY).toString();
  63 +// }
  64 +//
  65 +// if(verify!= null && !verify.equals(loginVerify)){
  66 +// throw new BadCredentialsException("验证码错误!");
  67 +// }
  68 +
45 authRequest = new UsernamePasswordAuthenticationToken(loginUserName,loginUserPass, null); 69 authRequest = new UsernamePasswordAuthenticationToken(loginUserName,loginUserPass, null);
46 authRequest.setDetails(authenticationDetailsSource.buildDetails(request)); 70 authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
47 - } catch (Exception e) { 71 + } catch (BadCredentialsException e){
  72 + throw new PreAuthenticatedCredentialsNotFoundException(e.getMessage());
  73 + }catch (Exception e) {
48 throw new AuthenticationServiceException(e.getMessage()); 74 throw new AuthenticationServiceException(e.getMessage());
49 } 75 }
50 return this.getAuthenticationManager().authenticate(authRequest); 76 return this.getAuthenticationManager().authenticate(authRequest);
1 package com.tianbo.warehouse.service.kakoImp; 1 package com.tianbo.warehouse.service.kakoImp;
2 2
  3 +import com.github.pagehelper.PageInfo;
3 import com.tianbo.warehouse.model.KakoUser; 4 import com.tianbo.warehouse.model.KakoUser;
  5 +import com.tianbo.warehouse.model.KakoUserRole;
  6 +import com.tianbo.warehouse.model.USERS;
4 import org.springframework.stereotype.Service; 7 import org.springframework.stereotype.Service;
5 8
6 import java.util.List; 9 import java.util.List;
@@ -9,4 +12,14 @@ import java.util.List; @@ -9,4 +12,14 @@ import java.util.List;
9 public interface KakoUserService { 12 public interface KakoUserService {
10 13
11 KakoUser loadByUsername(String username); 14 KakoUser loadByUsername(String username);
  15 +
  16 + PageInfo<KakoUser> selectAllUser(int pageNum, int pageSize, String username, String realName);
  17 +
  18 + int insertSelective(KakoUser record);
  19 +
  20 + int setUserRole(KakoUserRole userRole);
  21 +
  22 + int updateByPrimaryKeySelective(KakoUser record);
  23 +
  24 + int deleteByPrimaryKey(KakoUser record);
12 } 25 }
1 package com.tianbo.warehouse.service.kakoImp; 1 package com.tianbo.warehouse.service.kakoImp;
2 2
  3 +import com.github.pagehelper.Page;
  4 +import com.github.pagehelper.PageHelper;
3 import com.github.pagehelper.PageInfo; 5 import com.github.pagehelper.PageInfo;
4 import com.tianbo.warehouse.dao.KakoUserMapper; 6 import com.tianbo.warehouse.dao.KakoUserMapper;
5 import com.tianbo.warehouse.dao.ROLEMapper; 7 import com.tianbo.warehouse.dao.ROLEMapper;
  8 +import com.tianbo.warehouse.dao.UserRoleMapper;
6 import com.tianbo.warehouse.model.*; 9 import com.tianbo.warehouse.model.*;
  10 +import com.tianbo.warehouse.security.handel.kakologin.Digests;
  11 +import com.tianbo.warehouse.security.handel.kakologin.Encodes;
7 import com.tianbo.warehouse.service.PermissionService; 12 import com.tianbo.warehouse.service.PermissionService;
8 -import com.tianbo.warehouse.service.UserService;  
9 import org.springframework.beans.factory.annotation.Autowired; 13 import org.springframework.beans.factory.annotation.Autowired;
10 import org.springframework.stereotype.Service; 14 import org.springframework.stereotype.Service;
  15 +import org.springframework.transaction.annotation.Transactional;
11 16
12 import javax.annotation.Resource; 17 import javax.annotation.Resource;
  18 +import java.util.Date;
13 import java.util.List; 19 import java.util.List;
  20 +import java.util.UUID;
14 21
15 @Service 22 @Service
16 public class KakoUserServiceImpl implements KakoUserService{ 23 public class KakoUserServiceImpl implements KakoUserService{
17 24
  25 + public static final String HASH_ALGORITHM = "SHA-1";
  26 + public static final int HASH_INTERATIONS = 1024;
  27 + public static final int SALT_SIZE = 8;
  28 +
18 @Resource 29 @Resource
19 private KakoUserMapper kakoUserMapper; 30 private KakoUserMapper kakoUserMapper;
20 31
@@ -24,6 +35,9 @@ public class KakoUserServiceImpl implements KakoUserService{ @@ -24,6 +35,9 @@ public class KakoUserServiceImpl implements KakoUserService{
24 @Resource 35 @Resource
25 private ROLEMapper roleMapper; 36 private ROLEMapper roleMapper;
26 37
  38 + @Resource
  39 + private UserRoleMapper userRoleMapper;
  40 +
27 @Override 41 @Override
28 public KakoUser loadByUsername(String username){ 42 public KakoUser loadByUsername(String username){
29 List<KakoUser> userList = kakoUserMapper.selectByUsername(username); 43 List<KakoUser> userList = kakoUserMapper.selectByUsername(username);
@@ -44,4 +58,102 @@ public class KakoUserServiceImpl implements KakoUserService{ @@ -44,4 +58,102 @@ public class KakoUserServiceImpl implements KakoUserService{
44 return null; 58 return null;
45 } 59 }
46 60
  61 + @Override
  62 + public PageInfo<KakoUser> selectAllUser(int pageNum, int pageSize,String username, String realName){
  63 + Page<KakoUser> page = PageHelper.startPage(pageNum,pageSize);
  64 + KakoUser users = new KakoUser();
  65 + users.setLoginName(username);
  66 + users.setName(realName);
  67 + List<KakoUser> list = kakoUserMapper.selectAllUser(users);
  68 + for (KakoUser user: list) {
  69 +// List<PERMISSION> permissionList = permissionMapper.findByUserId(user.getUserId());
  70 +// user.setPermissions(permissionList);
  71 + List<ROLE> roleList = roleMapper.findRolesByUserIdKako(user.getId());
  72 + user.setRoles(roleList);
  73 + }
  74 + PageInfo<KakoUser> result = new PageInfo<KakoUser>(list);
  75 + return result;
  76 + }
  77 +
  78 + @Override
  79 + public int updateByPrimaryKeySelective(KakoUser record){
  80 + int i = 0;
  81 + if(record.getPassword()!=null && !record.getPassword().isEmpty()){
  82 + String entryPassWord = entryptPassword(record.getPassword());
  83 + record.setPassword(entryPassWord);
  84 + }
  85 + if (record!=null){
  86 + i = kakoUserMapper.updateByPrimaryKeySelective(record);
  87 + }
  88 + return i;
  89 +
  90 + }
  91 +
  92 + @Override
  93 + public int deleteByPrimaryKey(KakoUser record) {
  94 + return kakoUserMapper.deleteByPrimaryKey(record.getId());
  95 + }
  96 +
  97 + @Override
  98 + public int insertSelective(KakoUser record) {
  99 + if (!userValid(record)){
  100 + return 0;
  101 + }
  102 + if(record.getPassword()!=null && !record.getPassword().isEmpty()){
  103 + String entryPassWord = entryptPassword(record.getPassword());
  104 + record.setPassword(entryPassWord);
  105 + }
  106 + record.setCreateDate(new Date());
  107 + record.setUpdateDate(new Date());
  108 + record.setLoginFlag("1");
  109 + record.setId(UUID.randomUUID().toString());
  110 + return kakoUserMapper.insertSelective(record);
  111 + }
  112 +
  113 + /**
  114 + * 生成安全的密码,生成随机的16位salt并经过1024次 sha-1 hash
  115 + */
  116 + public static String entryptPassword(String plainPassword) {
  117 + String plain = Encodes.unescapeHtml(plainPassword);
  118 + byte[] salt = Digests.generateSalt(SALT_SIZE);
  119 + byte[] hashPassword = Digests.sha1(plain.getBytes(), salt, HASH_INTERATIONS);
  120 + return Encodes.encodeHex(salt)+Encodes.encodeHex(hashPassword);
  121 + }
  122 +
  123 + /**
  124 + * 检查是否存在用户
  125 + */
  126 + public boolean userValid(KakoUser user){
  127 + //根据用户名查询出来有数据,则返回失败存在用户
  128 + if (loadByUsername(user.getLoginName())!=null){
  129 + return false;
  130 + }else {
  131 + return true;
  132 + }
  133 + }
  134 +
  135 + @Override
  136 + @Transactional(rollbackFor = Exception.class)
  137 + public int setUserRole(KakoUserRole userRole) {
  138 + try{
  139 + String userId = userRole.getUserId();
  140 + List<Integer> ids = userRole.getRoleIds();
  141 +
  142 + userRoleMapper.deleteByUserIdKako(userId);
  143 + if (null!=ids && !ids.isEmpty()){
  144 + for (Integer id:ids) {
  145 + KakoUserRole ur = new KakoUserRole(userId,id);
  146 + userRoleMapper.insertSelectiveKako(ur);
  147 + }
  148 + }
  149 + /**
  150 + * 重写redis用户权限等相关资料
  151 + */
  152 +
  153 + return 1;
  154 + }catch (Exception e){
  155 + e.printStackTrace();
  156 + return 0;
  157 + }
  158 + }
47 } 159 }
@@ -35,16 +35,29 @@ @@ -35,16 +35,29 @@
35 from sys_user 35 from sys_user
36 where id = #{id,jdbcType=VARCHAR} 36 where id = #{id,jdbcType=VARCHAR}
37 </select> 37 </select>
  38 + <select id="selectAllUser" resultMap="BaseResultMap" parameterType="com.tianbo.warehouse.model.KakoUser" >
  39 + select
  40 + <include refid="Base_Column_List" />
  41 + from sys_user
  42 + WHERE 1=1
  43 + <if test=" loginName != null" >
  44 + and login_name = #{loginName,jdbcType=VARCHAR}
  45 + </if>
  46 + <if test="name != null" >
  47 + and name = #{name,jdbcType=VARCHAR}
  48 + </if>
  49 + </select>
38 <select id="selectByUsername" resultMap="BaseResultMap" parameterType="java.lang.String" > 50 <select id="selectByUsername" resultMap="BaseResultMap" parameterType="java.lang.String" >
39 select 51 select
40 <include refid="Base_Column_List" /> 52 <include refid="Base_Column_List" />
41 from sys_user 53 from sys_user
42 where login_name = #{login_name,jdbcType=VARCHAR} 54 where login_name = #{login_name,jdbcType=VARCHAR}
43 </select> 55 </select>
44 - <delete id="deleteByPrimaryKey" parameterType="java.lang.String" >  
45 - delete from sys_user 56 + <update id="deleteByPrimaryKey" parameterType="java.lang.String" >
  57 + update from sys_user
  58 + del_flag = '1'
46 where id = #{id,jdbcType=VARCHAR} 59 where id = #{id,jdbcType=VARCHAR}
47 - </delete> 60 + </update>
48 <insert id="insert" parameterType="com.tianbo.warehouse.model.KakoUser" > 61 <insert id="insert" parameterType="com.tianbo.warehouse.model.KakoUser" >
49 insert into sys_user (id, company_id, office_id, 62 insert into sys_user (id, company_id, office_id,
50 login_name, password, no, 63 login_name, password, no,
@@ -23,6 +23,11 @@ @@ -23,6 +23,11 @@
23 delete from user_role 23 delete from user_role
24 where user_id = #{userId,jdbcType=INTEGER} 24 where user_id = #{userId,jdbcType=INTEGER}
25 </delete> 25 </delete>
  26 +
  27 + <delete id="deleteByUserIdKako" parameterType="java.lang.String" >
  28 + delete from user_role
  29 + where user_id = #{userId,jdbcType=VARCHAR}
  30 + </delete>
26 <insert id="insert" parameterType="com.tianbo.warehouse.model.UserRole" > 31 <insert id="insert" parameterType="com.tianbo.warehouse.model.UserRole" >
27 insert into user_role (id,user_id, role_id 32 insert into user_role (id,user_id, role_id
28 ) 33 )
@@ -54,6 +59,32 @@ @@ -54,6 +59,32 @@
54 </if> 59 </if>
55 </trim> 60 </trim>
56 </insert> 61 </insert>
  62 +
  63 + <insert id="insertSelectiveKako" parameterType="com.tianbo.warehouse.model.KakoUserRole" >
  64 + insert into user_role
  65 + <trim prefix="(" suffix=")" suffixOverrides="," >
  66 + <if test="id != null" >
  67 + id,
  68 + </if>
  69 + <if test="userId != null" >
  70 + user_id,
  71 + </if>
  72 + <if test="roleId != null" >
  73 + role_id,
  74 + </if>
  75 + </trim>
  76 + <trim prefix="values (" suffix=")" suffixOverrides="," >
  77 + <if test="id != null" >
  78 + #{id,jdbcType=INTEGER},
  79 + </if>
  80 + <if test="userId != null" >
  81 + #{userId,jdbcType=VARCHAR},
  82 + </if>
  83 + <if test="roleId != null" >
  84 + #{roleId,jdbcType=INTEGER},
  85 + </if>
  86 + </trim>
  87 + </insert>
57 <update id="updateByPrimaryKeySelective" parameterType="com.tianbo.warehouse.model.UserRole" > 88 <update id="updateByPrimaryKeySelective" parameterType="com.tianbo.warehouse.model.UserRole" >
58 update user_role 89 update user_role
59 <set > 90 <set >