UserController.java 9.37 KB
package com.uccc.admin.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.uccc.admin.domain.Permission;
import com.uccc.admin.exception.ApiException;
import com.uccc.admin.service.PermissionService;
import com.uccc.admin.service.UserService;
import com.uccc.pretty.common.Result;
import com.uccc.pretty.common.SystemLog;
import com.uccc.pretty.common.User;
import com.uccc.pretty.common.UserEntity;
import com.uccc.pretty.constants.ErrorCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Base64;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import static com.uccc.pretty.constants.ActionEnum.*;
import static com.uccc.pretty.constants.ResultEnum.RESULT_ERR;
import static com.uccc.pretty.constants.ResultEnum.RESULT_OK;
import static com.uccc.pretty.constants.UserStatusEnum.*;

/**
 * Created by bert on 2021-09-11 11:50
 */

@RestController
@RequestMapping("/admin/")
public class UserController {
    private Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private PermissionService permissionService;

    /**
     * login in
     * @param user
     * @param ip
     * @return
     * @throws NullPointerException
     */
    @RequestMapping(value = "login",method = RequestMethod.POST)
    public Result doLogin(@RequestBody User user, @RequestParam String ip) throws NullPointerException{
        if (ip == null) throw  new ApiException(ErrorCode.IP_NOT_FOUND);
        Result result = new Result();
        if (user == null) {
            throw new ApiException(ErrorCode.USER_LOGIN_WRONG);
        }else {
            logger.info("user:{}", user.toString());
            if (user.getAccount() == null) {
                throw new ApiException(ErrorCode.USER_ACCOUNT_NOT_FOUND);
            }else if (user.getPassword() == null){
                throw new ApiException(ErrorCode.USER_PASSWORD_NOT_FOUND);
            }
            byte[] pwdBytes = user.getPassword().getBytes();
            //base64 encode
            String pwdEncoded = Base64.getEncoder().encodeToString(pwdBytes);
            user.setPassword(pwdEncoded);
            user = userService.getUserByCondition(user);
            if (user == null) throw new ApiException(ErrorCode.USER_PASSWORD_WRONG);
            if (user.getStatus() == USER_STATUS_OFF.getCode() || user.getStatus() == USER_STATUS_FROZEN.getCode()) {
                throw new ApiException(ErrorCode.LOGIN_ACCOUNT_CLOSE);
            }
            //get user permission
            List<Permission> permissionList = permissionService.getPermissionByUserId(user.getId());
            if (permissionList.size() == 0) {
                throw new ApiException(ErrorCode.USER_PERMISSION_NOT_FOUND);
            }else {
//                String[] permissions = permissionService.formatPermissions(permissionList);
                JSONArray jsonArray = permissionService.formatPermissions(permissionList);
                user.setPermission(jsonArray);
            }
            User updateUser = new User();
            updateUser.setId(user.getId());
            updateUser.setLastLoginIp(ip);
            updateUser.setLastLoginTime(new Date());
            userService.updateUser(updateUser);
            SystemLog systemLog = new SystemLog(USER_LOGIN.getCode(),USER_LOGIN.getMessage(),USER_LOGIN.getMessage(),new Date(),"",ip);
            userService.sendSystemLogToRabbitMq(JSONObject.toJSONString(systemLog));
        }
        result.setCode(RESULT_OK.getCode());
        result.setMessage(RESULT_OK.getMessage());
        String jsonString = JSONObject.toJSONString(user);
        UserEntity userEntity = JSONObject.parseObject(jsonString,UserEntity.class);
        //签发token
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE,30);
        Date date = calendar.getTime();
        String token= JWT.create().withAudience(userEntity.getId().toString(),user.getPassword()).withExpiresAt(date)    // 将有效期放入token中
                .sign(Algorithm.HMAC256(user.getPassword()));
        userEntity.setToken(token);
        result.setData(userEntity);
        return result;
    }

    /**
     * update user
     * @param user
     * @param ip
     * @return
     * @throws NullPointerException
     */
    @RequestMapping(value = "user",method = RequestMethod.PUT)
    public Result modifyUser (@RequestBody User user, @RequestParam String ip) throws NullPointerException{
        if (ip == null) throw  new ApiException(ErrorCode.IP_NOT_FOUND);
        Result result = new Result();
        if (user.getId() == null) throw new ApiException(ErrorCode.USER_ID_NOT_FOUND);
        //check user exist
        User check = new User();
        check.setId(user.getId());
        check = userService.getUserByCondition(check);
        if (check == null) throw new ApiException(ErrorCode.USER_ID_NOT_FOUND);

        SystemLog systemLog = new SystemLog(USER_INFO_MODIFY.getCode(),USER_INFO_MODIFY.getMessage(),USER_INFO_MODIFY.getMessage(),new Date(),"modify user id is"+user.getId(),ip);
        userService.sendSystemLogToRabbitMq(JSONObject.toJSONString(systemLog));
        boolean updateResult = userService.updateUser(user);
        if (updateResult) {
            result.setCode(RESULT_OK.getCode());
            result.setMessage(RESULT_OK.getMessage());
        }else {
            throw new ApiException(ErrorCode.USER_INFO_UPDATE_FAILED);
        }
        return result;
    }

    /**
     * search user
     * @param user
     * @return
     * @throws NullPointerException
     */
    @RequestMapping(value = "user",method = RequestMethod.GET)
    public Result findUser (@RequestBody User user) throws NullPointerException{
        Result result = new Result();
        List<UserEntity>  userEntities = userService.getUserListByCondition(user);
        result.setCode(RESULT_OK.getCode());
        result.setMessage(RESULT_OK.getMessage());
        result.setData(userEntities);
        return result;
    }

    /**
     * add user
     * @param user
     * @return
     * @throws NullPointerException
     */
    @RequestMapping(value = "user",method = RequestMethod.POST)
    public Result createUser (@RequestBody User user, @RequestParam String ip) throws NullPointerException{
        if (ip == null) throw  new ApiException(ErrorCode.IP_NOT_FOUND);
        Result result = new Result();
        if (user.getAccount().equals("")) {
            throw new ApiException(ErrorCode.USER_ACCOUNT_NOT_FOUND);
        }else if (user.getPassword().equals("")){
            throw new ApiException(ErrorCode.USER_PASSWORD_NOT_FOUND);
        }else if (user.getName().equals("")) {
            throw new ApiException(ErrorCode.USER_NAME_NOT_FOUND);
        }else if (user.getPhone().equals("")) {
            throw new ApiException(ErrorCode.USER_PHONE_NOT_FOUND);
        }else if (user.getAddress().equals("")) {
            throw new ApiException(ErrorCode.USER_ADDRESS_NOT_FOUND);
        }else if (user.getQq().equals("")) {
            throw new ApiException(ErrorCode.USER_ADDRESS_NOT_FOUND);
        }else if (user.getRoleIds().length == 0) {
            throw new ApiException(ErrorCode.USER_ROLE_NOT_FOUND);
        }
        //check account repeat
        int accountCount = userService.checkAccountRepeat(user.getAccount());
        if (accountCount > 0) throw new ApiException(ErrorCode.USER_ACCOUNT_REPEAT);
        byte[] pwdBytes = user.getPassword().getBytes();
        //base64 encode
        String pwdEncoded = Base64.getEncoder().encodeToString(pwdBytes);
        user.setPassword(pwdEncoded);
        boolean createResult = userService.createUser(user, user.getRoleIds());

        if (createResult) {
            result.setCode(RESULT_OK.getCode());
            result.setMessage(RESULT_OK.getMessage());
        }else {
            result.setCode(RESULT_ERR.getCode());
            result.setMessage(RESULT_ERR.getMessage());
        }
        SystemLog systemLog = new SystemLog(USER_CREATE.getCode(),USER_CREATE.getMessage(),USER_CREATE.getMessage(),new Date(),"create user result is:"+createResult,ip);
        userService.sendSystemLogToRabbitMq(JSONObject.toJSONString(systemLog));
        return result;
    }

    /**
     * delete user
     * @param user
     * @param ip
     * @return
     * @throws NullPointerException
     */
    @RequestMapping(value = "user",method = RequestMethod.DELETE)
    public Result deleteUser (@RequestBody User user, @RequestParam String ip) throws NullPointerException{
        if (ip == null) throw  new ApiException(ErrorCode.IP_NOT_FOUND);
        Result result = new Result();
        if (user.getId() == null) throw new ApiException(ErrorCode.USER_ID_NOT_FOUND);

        boolean updateResult = userService.deleteUser(user);
        if (updateResult) {
            result.setCode(RESULT_OK.getCode());
            result.setMessage(RESULT_OK.getMessage());
        }else {
            throw new ApiException(ErrorCode.USER_INFO_UPDATE_FAILED);
        }
        SystemLog systemLog = new SystemLog(USER_INFO_MODIFY.getCode(),USER_INFO_MODIFY.getMessage(),USER_INFO_MODIFY.getMessage(),new Date(),"delete user id is"+user.getId(),ip);
        userService.sendSystemLogToRabbitMq(JSONObject.toJSONString(systemLog));
        return result;
    }

}