All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.rexsheng.springboot.faster.system.user.adapter.UserController Maven / Gradle / Ivy

The newest version!
package com.github.rexsheng.springboot.faster.system.user.adapter;

import com.github.rexsheng.springboot.faster.common.constant.CommonConstant;
import com.github.rexsheng.springboot.faster.common.domain.PagedList;
import com.github.rexsheng.springboot.faster.common.domain.Result;
import com.github.rexsheng.springboot.faster.logging.RequestLog;
import com.github.rexsheng.springboot.faster.request.repeat.annotation.RequestRepeat;
import com.github.rexsheng.springboot.faster.security.IgnorePermission;
import com.github.rexsheng.springboot.faster.system.user.application.UserService;
import com.github.rexsheng.springboot.faster.system.user.application.dto.*;
import com.github.rexsheng.springboot.faster.system.utils.AuthenticationUtil;
import com.github.rexsheng.springboot.faster.util.PasswordUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.ArraySchema;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.media.SchemaProperty;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/sys/user")
@Tag(name = "UserController",description = "用户管理")
@ConditionalOnProperty(prefix = "app.module.management",name = "controller",havingValue = "true",matchIfMissing = true)
@ConditionalOnClass(Authentication.class)
public class UserController {

    @Resource
    private UserService userService;

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


    @PreAuthorize("hasAuthority(T(com.github.rexsheng.springboot.faster.common.constant.AuthCodeConstant).USER_ADD)")
    @PostMapping
    @RequestLog("新增用户")
    @Operation(summary = "新增用户")
    @ApiResponses(value = {
            @ApiResponse(description = "successful operation", content = { @Content(schema = @Schema(type = "string",description = "系统自动生成的密码")) })
    })
    public Result addUser(@RequestBody @Validated AddUserRequest request){
        return Result.success(userService.add(request));
    }

    @PreAuthorize("hasAuthority(T(com.github.rexsheng.springboot.faster.common.constant.AuthCodeConstant).USER_LIST)" +
            " || hasAuthority(T(com.github.rexsheng.springboot.faster.common.constant.AuthCodeConstant).LOG_LIST)")
    @GetMapping
    @Operation(summary = "查询用户列表")
    @ApiResponses(value = {
            @ApiResponse(description = "successful operation", content = { @Content(mediaType = "application/json",
                    schemaProperties = {
                            @SchemaProperty(name = "pageIndex", schema = @Schema(implementation = Long.class,description = "页码",defaultValue = "1")),
                            @SchemaProperty(name = "pageSize", schema = @Schema(implementation = Long.class,description = "页大小",defaultValue = "10")),
                            @SchemaProperty(name = "totalCount", schema = @Schema(implementation = Long.class,description = "总记录数")),
                            @SchemaProperty(name = "totalPage", schema = @Schema(implementation = Long.class,description = "总页数")),
                            @SchemaProperty(name = "dataList", array = @ArraySchema(schema = @Schema(implementation = UserDetailResponse.class)))}
            )}),
            @ApiResponse(description = "successful operation")
    })
    public Result> queryUser(@Parameter(description = "关键字") @RequestParam(required = false) String keyword,
                            @Parameter(description = "部门ID") @RequestParam(required = false) Integer deptId,
                            @Parameter(description = "页码", schema = @Schema(implementation = Long.class, defaultValue = "1")) @RequestParam Long pageIndex,
                            @Parameter(description = "页大小", schema = @Schema(implementation = Long.class, defaultValue = "10")) @RequestParam Long pageSize){
        QueryUserRequest request=new QueryUserRequest();
        request.setPageIndex(pageIndex);
        request.setPageSize(pageSize);
        request.setKeyword(keyword);
        request.setDeptId(deptId);
        return Result.success(userService.pagedList(request));
    }

    @PreAuthorize("@ss.denyApi()")
    @GetMapping("/personal")
    @Operation(summary = "获取个人信息")
    @ApiResponses(value = {@ApiResponse(description = "successful operation", content = { @Content(schema = @Schema(implementation = UserDetailResponse.class)) })})
    public Result getPersonalInfo(Authentication authentication) {
        UserDetailResponse user=userService.getAllInfo(AuthenticationUtil.getUserIdFromAuthentication(authentication));
        user.setUserId(null);
        return Result.success(user);
    }

    @PostMapping("/token")
    @PreAuthorize("@ss.denyApi()")
    @RequestLog("生成用户凭证")
    @Operation(summary = "生成用户凭证")
    public Result createUserToken(@Validated @RequestBody CreateUserTokenRequest request) {
        return Result.success(userService.createToken(request));
    }

    @GetMapping("/token")
    @PreAuthorize("@ss.denyApi()")
    @Operation(summary = "查看用户凭证")
    public Result getUserTokens(Authentication authentication) {
        QueryTokenRequest request=new QueryTokenRequest();
        request.setUserId(AuthenticationUtil.getUserIdFromAuthentication(authentication));
        return Result.success(userService.queryTokens(request));
    }

    @DeleteMapping("/token")
    @PreAuthorize("@ss.denyApi()")
    @RequestLog("删除用户凭证")
    @Operation(summary = "删除用户凭证")
    public Result deleteUserTokens(@RequestBody Long[] ids){
        userService.deleteTokens(Arrays.asList(ids));
        return Result.success();
    }

    @PreAuthorize("hasAuthority(T(com.github.rexsheng.springboot.faster.common.constant.AuthCodeConstant).USER_EDIT)")
    @GetMapping("/{id}")
    @Operation(summary = "查询单个用户",parameters = {@Parameter(name = "id",description = "用户ID", required = true,in = ParameterIn.PATH)})
    @ApiResponses(value = {@ApiResponse(description = "successful operation", content = { @Content(schema = @Schema(implementation = UserDetailResponse.class)) })})
    public Result getUser(@PathVariable Long id){
        return Result.success(userService.get(id));
    }

    @PreAuthorize("hasAuthority(T(com.github.rexsheng.springboot.faster.common.constant.AuthCodeConstant).USER_EDIT)")
    @PutMapping("/{id}")
    @RequestLog("修改用户")
    @Operation(summary = "修改用户",parameters = {@Parameter(name = "id",description = "用户ID", required = true,in = ParameterIn.PATH)})
    @ApiResponses(value = {@ApiResponse(description = "successful operation", content = { @Content(schema = @Schema(implementation = Void.class)) })})
    public Result updateUser(@PathVariable Long id, @RequestBody @Validated UpdateUserRequest request){
        request.setUserId(id);
        userService.update(request);
        return Result.success();
    }

    @PreAuthorize("hasAuthority(T(com.github.rexsheng.springboot.faster.common.constant.AuthCodeConstant).USER_EDIT)")
    @PutMapping("/{ids}/status/{status}")
    @RequestLog("修改用户状态")
    @Operation(summary = "修改用户状态",parameters = {@Parameter(name = "ids",description = "用户IDs", required = true,in = ParameterIn.PATH),
            @Parameter(name = "status",description = "状态", required = true,in = ParameterIn.PATH,schema = @Schema(type = "boolean",description = "状态,true有效,false无效"))})
    @ApiResponses(value = {@ApiResponse(description = "successful operation", content = { @Content(schema = @Schema(implementation = Void.class)) })})
    public Result changeUserStatus(@PathVariable Long[] ids,@PathVariable Boolean status){
        userService.updateStatus(UpdateUserRequest.of(ids,status?CommonConstant.STATUS_RUNNING:CommonConstant.STATUS_STOP));
        return Result.success();
    }

    @PreAuthorize("hasAuthority(T(com.github.rexsheng.springboot.faster.common.constant.AuthCodeConstant).USER_DEL)")
    @DeleteMapping
    @RequestLog("删除用户")
    @Operation(summary = "删除用户",parameters = {@Parameter(name = "ids",description = "用户IDs", required = true,in = ParameterIn.DEFAULT)})
    @ApiResponses(value = {@ApiResponse(description = "successful operation", content = { @Content(schema = @Schema(implementation = Void.class)) })})
    public Result deleteUser(@RequestBody Long[] ids){
        userService.delete(Arrays.asList(ids));
        return Result.success();
    }

    @PreAuthorize("hasAuthority(T(com.github.rexsheng.springboot.faster.common.constant.AuthCodeConstant).USER_ADD)" +
            " || hasAuthority(T(com.github.rexsheng.springboot.faster.common.constant.AuthCodeConstant).USER_EDIT)")
    @PutMapping("/account/valid")
    @RequestRepeat(enabled = false)
    @Operation(summary = "用户账号唯一性校验")
    @ApiResponses(value = {
            @ApiResponse(description = "successful operation", content = { @Content(schema = @Schema(type = "boolean",description = "true校验成功"))}),
    })
    public Result validUserAccount(@RequestBody ValidateAccountRequest request){
        return Result.success(userService.validAccount(request));
    }

    @PreAuthorize("hasAuthority(T(com.github.rexsheng.springboot.faster.common.constant.AuthCodeConstant).USER_RESETPWD)")
    @PostMapping("/password/reset")
    @RequestLog("重置用户密码")
    @Operation(summary = "重置用户密码")
    @ApiResponses(value = {
            @ApiResponse(description = "successful operation", content = { @Content(schema = @Schema(type = "string",description = "新密码")) }),
    })
    public Result resetPassword(@RequestBody @Validated ResetPasswordRequest request){
        return Result.success(userService.resetPassword(request));
    }

    @PostMapping("/password")
    @PreAuthorize("@ss.denyApi()")
    @RequestLog("修改密码")
    @Operation(summary = "修改密码")
    @ApiResponses(value = {@ApiResponse(description = "successful operation", content = { @Content(schema = @Schema(implementation = Void.class)) })})
    public Result changePassword(@Parameter(hidden = true) Authentication authentication, @RequestBody @Validated ChangePasswordRequest request){
        request.setUserId(AuthenticationUtil.getUserIdFromAuthentication(authentication));
        userService.changePassword(request);
        return Result.success();
    }

    @PostMapping("/password/renew")
    @IgnorePermission
    @Operation(summary = "修改过期的密码")
    @ApiResponses(value = {@ApiResponse(description = "successful operation", content = { @Content(schema = @Schema(implementation = Void.class)) })})
    public Result changeExpiredPassword(@RequestBody @Validated ChangeExpiredPasswordRequest request){
        ChangePasswordRequest changePasswordRequest=new ChangePasswordRequest();
        String userIdStr=PasswordUtils.decodeRSAPrivate(request.getIdentity(),CommonConstant.RSA_PRIVATE_KEY_INNER);
        if(userIdStr==null){
            throw new IllegalArgumentException("illegal argument");
        }
        changePasswordRequest.setUserId(Long.valueOf(userIdStr));
        changePasswordRequest.setOldPassword(request.getOldPassword());
        changePasswordRequest.setNewPassword(request.getNewPassword());
        userService.changePassword(changePasswordRequest);
        return Result.success();
    }

    @PreAuthorize("hasAuthority(T(com.github.rexsheng.springboot.faster.common.constant.AuthCodeConstant).USER_ASSIGNROLE)")
    @PutMapping("/{id}/role")
    @RequestLog("修改用户角色")
    @Operation(summary = "修改用户角色")
    @ApiResponses(value = {@ApiResponse(description = "successful operation", content = { @Content(schema = @Schema(implementation = Void.class)) })})
    public Result assignUserRole(@PathVariable Long id,@RequestBody List roleIds){
        ChangeUserRoleRequest request=new ChangeUserRoleRequest(id,roleIds);
        userService.changeRole(request);
        return Result.success();
    }

    @PreAuthorize("hasAuthority(T(com.github.rexsheng.springboot.faster.common.constant.AuthCodeConstant).USER_ASSIGNROLE)")
    @GetMapping("/{id}/role")
    @Operation(summary = "获取用户角色")
    @ApiResponses(value = {
            @ApiResponse(description = "successful operation", content = { @Content(array = @ArraySchema(schema = @Schema(type = "integer",description = "角色ID"))) }),
    })
    public Result getUserRole(@PathVariable Long id){
        return Result.success(userService.getRoles(id));
    }


    @PreAuthorize("hasAuthority(T(com.github.rexsheng.springboot.faster.common.constant.AuthCodeConstant).USER_ADD)")
    @PostMapping("/import/valid")
    @Operation(summary = "校验导入的用户")
//    @Parameters({@Parameter(description = "请求列表",array = @ArraySchema(schema = @Schema(implementation = ValidateImportUserRequest.class)))})
//    @Parameter(description = "请求列表",array = @ArraySchema(schema = @Schema(implementation = ValidateImportUserRequest.class)))
    @ApiResponses(value = {
            @ApiResponse(description = "successful operation", content = { @Content(mediaType = "application/json", schema = @Schema(implementation = ValidateImportUserResponse.class)) }),
    })
    public Result validateImportUsers(@RequestBody @Validated List request){
        return Result.success(userService.validateImportList(request));
    }

    @PreAuthorize("hasAuthority(T(com.github.rexsheng.springboot.faster.common.constant.AuthCodeConstant).USER_ADD)")
    @PostMapping("/import")
    @RequestLog("导入用户")
    @Operation(summary = "导入用户")
    @ApiResponses(value = {@ApiResponse(description = "successful operation", content = { @Content(schema = @Schema(implementation = Void.class)) })})
    public Result importUsers(@RequestBody @Validated List request){
        userService.add(request);
        return Result.success();
    }

    @PostMapping("/avatar")
    @PreAuthorize("@ss.denyApi()")
    @RequestLog("上传用户头像")
    @Operation(summary = "上传用户头像")
    public Result uploadAvatar(Authentication authentication, @RequestParam MultipartFile avatar) throws IOException {
        UpdateAvatarRequest request=new UpdateAvatarRequest();
        request.setUserId(AuthenticationUtil.getUserIdFromAuthentication(authentication));
        request.setAvatar(avatar.getBytes());
        userService.updateAvatar(request);
        return Result.success();
    }

    @PostMapping("/personal")
    @PreAuthorize("@ss.denyApi()")
    @RequestLog("修改个人信息")
    @Operation(summary = "修改个人信息")
    public Result changePersonal(Authentication authentication,@RequestBody UpdatePersonalRequest request) throws IOException {
        request.setUserId(AuthenticationUtil.getUserIdFromAuthentication(authentication));
        userService.updatePersonal(request);
        return Result.success();
    }

    @PutMapping("/token/valid")
    @PreAuthorize("@ss.denyApi()")
    @RequestRepeat(enabled = false)
    @Operation(summary = "校验用户凭证是否重复")
    public Result validateUserToken(Authentication authentication,@RequestBody ValidateUserTokenRequest request) throws IOException {
        request.setUserId(AuthenticationUtil.getUserIdFromAuthentication(authentication));
        return Result.success(userService.validToken(request));
    }

    @PreAuthorize("hasAuthority(T(com.github.rexsheng.springboot.faster.common.constant.AuthCodeConstant).USER_EXPIRE)")
    @PutMapping("/{id}/expire")
    @RequestLog("修改账号过期时间")
    @Operation(summary = "修改账号过期时间")
    @ApiResponses(value = {@ApiResponse(description = "successful operation", content = { @Content(schema = @Schema(implementation = Void.class)) })})
    public Result changeExpiredTime(@PathVariable Long id,@RequestBody(required = false) String expiredTime){
        ChangeExpiredTimeRequest request=new ChangeExpiredTimeRequest();
        request.setUserId(id);
        request.setExpiredTime(expiredTime);
        userService.changeExpiredTime(request);
        return Result.success();
    }

    @PreAuthorize("hasAuthority(T(com.github.rexsheng.springboot.faster.common.constant.AuthCodeConstant).USER_LOCK)")
    @PutMapping("/{id}/lock")
    @RequestLog("修改账号锁定时间")
    @Operation(summary = "修改账号锁定时间")
    @ApiResponses(value = {@ApiResponse(description = "successful operation", content = { @Content(schema = @Schema(implementation = Void.class)) })})
    public Result changeLockedTime(@PathVariable Long id,@RequestBody(required = false) String lockedTime){
        ChangeLockedTimeRequest request=new ChangeLockedTimeRequest();
        request.setUserId(id);
        request.setLockedTime(lockedTime);
        userService.changeLockedTime(request);
        return Result.success();
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy