UserController.java 7.2 KB
package com.tianbo.warehouse.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.tianbo.warehouse.annotation.LogAnnotation;
import com.tianbo.warehouse.annotation.RequestRequire;
import com.tianbo.warehouse.annotation.UserPasswordMd5;
import com.tianbo.warehouse.controller.response.ResultJson;
import com.tianbo.warehouse.model.USERS;
import com.tianbo.warehouse.model.UserRole;
import com.tianbo.warehouse.security.CustomUserDetailService;
import com.tianbo.warehouse.security.filter.JwtTokenUtil;
import com.tianbo.warehouse.service.UserService;
import com.tianbo.warehouse.service.validated.InsertUser;
import com.tianbo.warehouse.service.validated.UpdateUser;
import com.tianbo.warehouse.util.RedisUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/user")
@Api("swaggerDemoController相关的api")
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    CustomUserDetailService userDetailService;

    @Autowired
    RedisUtils redisUtils;

    @ApiOperation(value = "查询用户列表及信息", notes = "查询用户列表及单个用户信息")
    @ApiImplicitParams({@ApiImplicitParam(name = "pageNum", value = "分页-当前页", required = false, dataType = "int",defaultValue = "1"),
            @ApiImplicitParam(name = "pageSize", value = "分页-每页显示多少条", required = false, dataType = "int",defaultValue = "5")})
    @RequestRequire
    @GetMapping("/list")
    public ResultJson<PageInfo> list(@RequestParam(value = "pageNum",required = false,defaultValue = "1")
                                        int pageNum,
                                @RequestParam(value = "pageSize",required = false,defaultValue = "5")
                                        int pageSize,
                                @RequestParam(value = "userName",required = false) String username,
                                @RequestParam(value = "realName",required = false) String realname,
                                @RequestParam(value = "companyId",required = false) Integer companyId)
    {

        PageInfo<USERS> usersPageInfo = userService.selectAllUser(pageNum,pageSize, username,  realname,companyId);
        return new ResultJson("200","success",usersPageInfo);
    }

    public String getCurrentUser(){

        //通过session获取当前登录的用户信息
        UserDetails userDetails =(UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return userDetails.getUsername();
    }
    @ApiOperation(value = "更新用户信息", notes = "跟新用户信息除了用户密码")
    @LogAnnotation(moduleName = "用户管理",operate = "用户编辑")
    @PutMapping("/edit")
    public ResultJson updateUserById(@Validated(UpdateUser.class) @RequestBody USERS user){
        int i = userService.updateByPrimaryKeySelective(user);
        user.setPassword(null);
        ResultJson resultJson = new ResultJson();
        return i==1 ? new ResultJson("200","success") :new ResultJson("500","update faild");

    }

    @LogAnnotation(moduleName = "用户管理",operate = "用户密码修改")
    @UserPasswordMd5
    @PutMapping("/password")
    public ResultJson updateUserPassById(@RequestBody USERS user){
        int i = userService.updateByPrimaryKeySelective(user);
        return i==1 ? new ResultJson("200","success") :new ResultJson("500","update faild");
    }

    @UserPasswordMd5
    @LogAnnotation(moduleName = "用户管理",operate = "用户添加")
    @PostMapping("/add")
    public ResultJson addUser(@RequestBody @Validated(InsertUser.class) USERS user, HttpServletRequest request, HttpServletResponse response, BindingResult bindingResult){

        if (bindingResult.hasErrors()){
           String s =  bindingResult.toString();
        }

        int i = userService.insertSelective(user);
        ResultJson resultJson = new ResultJson();
        return i==1 ? new ResultJson("200","新建账户成功") :new ResultJson("500","insert faild");

    }

    @LogAnnotation(moduleName = "用户管理",operate = "用户删除")
    @DeleteMapping("/del")
    public ResultJson delUser(@RequestBody USERS user,HttpServletRequest request,HttpServletResponse response){
        //String username = getusername();
        int i = userService.deleteByPrimaryKey(user.getUserId());
        ResultJson resultJson = new ResultJson();
        return i==1 ? new ResultJson("200","删除账户成功") :new ResultJson("500","delete faild");
    }

    @PutMapping("/roleset")
    public ResultJson roleSet(@RequestBody Map<String,Object> map,HttpServletRequest request,HttpServletResponse respons){
        Integer id = (Integer) map.get("userId");
        List<Integer> roles = (List<Integer>) map.get("roleIds");
        UserRole userRole = new UserRole();
        userRole.setUserId(id);
        userRole.setRoleIds(roles);
        int i =  userService.setUserRole(userRole);
        return i==1 ? new ResultJson("200","设置角色成功") :new ResultJson("500","设置角色失败");
    }

    /**
     * 刷新redis权限缓存
     */
    @ApiOperation(value = "更新用户权限缓存", notes = "重新生成用户的信息到redis")
    @PutMapping("/resetToken")
    public ResultJson resetToken(HttpServletRequest request,HttpServletResponse respons) {
        /**
         * 更新目标用户的权限缓存
         */
        String authHeader = request.getHeader("Authorization");
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            final String authToken = authHeader.substring("Bearer ".length());
            try {
                String userJson = redisUtils.get(authToken);
                if (userJson != null) {
                    USERS u = JSON.parseObject(userJson, USERS.class);
                    String username = u.getUsername();

//                  String username = JwtTokenUtil.parseToken(authToken);
                    if (username != null) {
                        UserDetails userDetails = userDetailService.loadUserByUsername(username);
                        if (userDetails != null) {
                            String json = JSON.toJSONString(userDetails);
                            redisUtils.set(authToken, json, 3600 * 24 * 7);
                            return new ResultJson("200", "缓存更新成功");
                        }
                    }
                }
            }catch (Exception e){
                log.error(e.toString());
                return new ResultJson("500","缓存更新失败");
            }
        }
        return new ResultJson("500","缓存更新失败");
    }
}