Skip to content

Commit

Permalink
refactor: 取消用户默认密码,改为表单填写密码
Browse files Browse the repository at this point in the history
1.修复 Sonar 扫描问题
2.优化部分代码
  • Loading branch information
Charles7c committed Feb 2, 2024
1 parent b9ce3f5 commit 3d77aa9
Show file tree
Hide file tree
Showing 17 changed files with 111 additions and 61 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -46,11 +46,6 @@ public class SysConstants {
*/
public static final String ALL_PERMISSION = StringConstants.ASTERISK;

/**
* 默认密码
*/
public static final String DEFAULT_PASSWORD = "123456";

/**
* 账号登录 URI
*/
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/*
* Copyright (c) 2022-present Charles7c Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http:https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package top.charles7c.continew.admin.system.model.req;

import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;

import java.io.Serial;
import java.io.Serializable;

/**
* 用户密码重置信息
*
* @author Charles7c
* @since 2024/2/2 22:50
*/
@Data
@Schema(description = "用户密码重置信息")
public class UserPasswordResetReq implements Serializable {

@Serial
private static final long serialVersionUID = 1L;

/**
* 新密码(加密)
*/
@Schema(description = "新密码(加密)", example = "Gzc78825P5baH190lRuZFb9KJxRt/psN2jiyOMPoc5WRcCvneCwqDm3Q33BZY56EzyyVy7vQu7jQwYTK4j1+5w==")
@NotBlank(message = "新密码不能为空")
private String newPassword;
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
import top.charles7c.continew.admin.common.enums.DisEnableStatusEnum;
import top.charles7c.continew.admin.common.enums.GenderEnum;
import top.charles7c.continew.starter.extension.crud.model.req.BaseReq;
import top.charles7c.continew.starter.extension.crud.util.ValidateGroup;

import java.io.Serial;
import java.util.List;
Expand Down Expand Up @@ -61,6 +62,13 @@ public class UserReq extends BaseReq {
@Pattern(regexp = RegexConstants.GENERAL_NAME, message = "昵称长度为 2 到 30 位,可以包含中文、字母、数字、下划线,短横线")
private String nickname;

/**
* 密码(加密)
*/
@Schema(description = "密码(加密)", example = "E7c72TH+LDxKTwavjM99W1MdI9Lljh79aPKiv3XB9MXcplhm7qJ1BJCj28yaflbdVbfc366klMtjLIWQGqb0qw==")
@NotBlank(message = "密码不能为空", groups = ValidateGroup.Crud.Add.class)
private String password;

/**
* 邮箱
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import top.charles7c.continew.admin.system.model.entity.UserDO;
import top.charles7c.continew.admin.system.model.query.UserQuery;
import top.charles7c.continew.admin.system.model.req.UserBasicInfoUpdateReq;
import top.charles7c.continew.admin.system.model.req.UserPasswordResetReq;
import top.charles7c.continew.admin.system.model.req.UserReq;
import top.charles7c.continew.admin.system.model.req.UserRoleUpdateReq;
import top.charles7c.continew.admin.system.model.resp.UserDetailResp;
Expand Down Expand Up @@ -92,9 +93,10 @@ public interface UserService extends BaseService<UserResp, UserDetailResp, UserQ
/**
* 重置密码
*
* @param id ID
* @param req 重置信息
* @param id ID
*/
void resetPassword(Long id);
void resetPassword(UserPasswordResetReq req, Long id);

/**
* 修改角色
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,13 @@
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import top.charles7c.continew.admin.common.constant.CacheConstants;
import top.charles7c.continew.admin.common.constant.SysConstants;
import top.charles7c.continew.admin.common.enums.DisEnableStatusEnum;
import top.charles7c.continew.admin.common.util.helper.LoginHelper;
import top.charles7c.continew.admin.system.mapper.UserMapper;
import top.charles7c.continew.admin.system.model.entity.UserDO;
import top.charles7c.continew.admin.system.model.query.UserQuery;
import top.charles7c.continew.admin.system.model.req.UserBasicInfoUpdateReq;
import top.charles7c.continew.admin.system.model.req.UserPasswordResetReq;
import top.charles7c.continew.admin.system.model.req.UserReq;
import top.charles7c.continew.admin.system.model.req.UserRoleUpdateReq;
import top.charles7c.continew.admin.system.model.resp.UserDetailResp;
Expand All @@ -50,8 +50,8 @@
import top.charles7c.continew.admin.system.service.UserService;
import top.charles7c.continew.starter.core.constant.StringConstants;
import top.charles7c.continew.starter.core.util.validate.CheckUtils;
import top.charles7c.continew.starter.extension.crud.service.impl.BaseServiceImpl;
import top.charles7c.continew.starter.extension.crud.service.CommonUserService;
import top.charles7c.continew.starter.extension.crud.service.impl.BaseServiceImpl;

import java.time.LocalDateTime;
import java.util.Collection;
Expand Down Expand Up @@ -92,16 +92,13 @@ protected void beforeAdd(UserReq req) {
String phone = req.getPhone();
CheckUtils.throwIf(StrUtil.isNotBlank(phone) && this.isPhoneExists(phone, null), "新增失败,[{}] 已存在", phone);
req.setStatus(DisEnableStatusEnum.ENABLE);
req.setPassword(passwordEncoder.encode(req.getPassword()));
}

@Override
protected void afterAdd(UserReq req, UserDO user) {
Long userId = user.getId();
baseMapper.lambdaUpdate()
.set(UserDO::getPassword, passwordEncoder.encode(SysConstants.DEFAULT_PASSWORD))
.set(UserDO::getPwdResetTime, LocalDateTime.now())
.eq(UserDO::getId, userId)
.update();
baseMapper.lambdaUpdate().set(UserDO::getPwdResetTime, LocalDateTime.now()).eq(UserDO::getId, userId).update();
// 保存用户和角色关联
userRoleService.add(req.getRoleIds(), userId);
}
Expand Down Expand Up @@ -166,9 +163,8 @@ protected void fill(Object obj) {
@Transactional(rollbackFor = Exception.class)
public String uploadAvatar(MultipartFile avatarFile, Long id) {
String avatarImageType = FileNameUtil.extName(avatarFile.getOriginalFilename());
CheckUtils.throwIf(!StrUtil
.equalsAnyIgnoreCase(avatarImageType, avatarSupportSuffix), "头像仅支持 {} 格式的图片", String
.join(StringConstants.CHINESE_COMMA, avatarSupportSuffix));
CheckUtils.throwIf(!StrUtil.equalsAnyIgnoreCase(avatarImageType, avatarSupportSuffix), "头像仅支持 {} 格式的图片", String
.join(StringConstants.CHINESE_COMMA, avatarSupportSuffix));
// 上传新头像
UserDO user = super.getById(id);
FileInfo fileInfo = fileService.upload(avatarFile);
Expand Down Expand Up @@ -234,9 +230,9 @@ public void updateEmail(String newEmail, String currentPassword, Long id) {
}

@Override
public void resetPassword(Long id) {
public void resetPassword(UserPasswordResetReq req, Long id) {
UserDO user = super.getById(id);
user.setPassword(passwordEncoder.encode(SysConstants.DEFAULT_PASSWORD));
user.setPassword(passwordEncoder.encode(req.getNewPassword()));
user.setPwdResetTime(LocalDateTime.now());
baseMapper.updateById(user);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ public class SocialAuthController {
@Operation(summary = "三方账号登录授权", description = "三方账号登录授权")
@Parameter(name = "source", description = "来源", example = "gitee", in = ParameterIn.PATH)
@GetMapping("/{source}")
public R authorize(@PathVariable String source) {
public R<String> authorize(@PathVariable String source) {
AuthRequest authRequest = this.getAuthRequest(source);
return R.ok("操作成功", authRequest.authorize(AuthStateUtils.createState()));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ public R<CaptchaResp> getImageCaptcha() {

@Operation(summary = "获取邮箱验证码", description = "发送验证码到指定邮箱")
@GetMapping("/mail")
public R getMailCaptcha(@NotBlank(message = "邮箱不能为空") @Pattern(regexp = RegexPool.EMAIL, message = "邮箱格式错误") String email) throws MessagingException {
public R<Void> getMailCaptcha(@NotBlank(message = "邮箱不能为空") @Pattern(regexp = RegexPool.EMAIL, message = "邮箱格式错误") String email) throws MessagingException {
String limitKeyPrefix = CacheConstants.LIMIT_KEY_PREFIX;
String captchaKeyPrefix = CacheConstants.CAPTCHA_KEY_PREFIX;
String limitCaptchaKey = limitKeyPrefix + captchaKeyPrefix + email;
Expand All @@ -129,9 +129,9 @@ public R getMailCaptcha(@NotBlank(message = "邮箱不能为空") @Pattern(regex

@Operation(summary = "获取短信验证码", description = "发送验证码到指定手机号")
@GetMapping("/sms")
public R getSmsCaptcha(@NotBlank(message = "手机号不能为空") @Pattern(regexp = RegexPool.MOBILE, message = "手机号格式错误") String phone,
CaptchaVO captchaReq,
HttpServletRequest request) {
public R<Void> getSmsCaptcha(@NotBlank(message = "手机号不能为空") @Pattern(regexp = RegexPool.MOBILE, message = "手机号格式错误") String phone,
CaptchaVO captchaReq,
HttpServletRequest request) {
// 行为验证码校验
ResponseModel verificationRes = captchaService.verification(captchaReq);
ValidationUtils.throwIfNotEqual(verificationRes.getRepCode(), RepCodeEnum.SUCCESS.getCode(), verificationRes
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ public R<PageResp<OnlineUserResp>> page(OnlineUserQuery query, @Validated PageQu
@Parameter(name = "token", description = "令牌", example = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpblR5cGUiOiJsb2dpbiIsImxvZ2luSWQiOjEsInJuU3RyIjoiTUd6djdyOVFoeHEwdVFqdFAzV3M5YjVJRzh4YjZPSEUifQ.7q7U3ouoN7WPhH2kUEM7vPe5KF3G_qavSG-vRgIxKvE", in = ParameterIn.PATH)
@SaCheckPermission("monitor:online:user:delete")
@DeleteMapping("/{token}")
public R kickout(@PathVariable String token) {
public R<Void> kickout(@PathVariable String token) {
String currentToken = StpUtil.getTokenValue();
CheckUtils.throwIfEqual(token, currentToken, "不能强退自己");
StpUtil.kickoutByTokenValue(token);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,8 @@ public R<Long> add(@Validated(ValidateGroup.Crud.Add.class) @RequestBody Announc

@Override
@SaCheckPermission("system:announcement:update")
public R update(@Validated(ValidateGroup.Crud.Update.class) @RequestBody AnnouncementReq req,
@PathVariable Long id) {
public R<Void> update(@Validated(ValidateGroup.Crud.Update.class) @RequestBody AnnouncementReq req,
@PathVariable Long id) {
this.checkTime(req);
return super.update(req, id);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ public R<Long> add(@Validated(ValidateGroup.Crud.Add.class) @RequestBody MenuReq

@Override
@SaCheckPermission("system:menu:update")
public R update(@Validated(ValidateGroup.Crud.Update.class) @RequestBody MenuReq req, @PathVariable Long id) {
public R<Void> update(@Validated(ValidateGroup.Crud.Update.class) @RequestBody MenuReq req, @PathVariable Long id) {
this.checkPath(req);
return super.update(req, id);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,15 +61,15 @@ public R<PageResp<MessageResp>> page(MessageQuery query, @Validated PageQuery pa
@Operation(summary = "删除数据", description = "删除数据")
@Parameter(name = "ids", description = "ID 列表", example = "1,2", in = ParameterIn.PATH)
@DeleteMapping("/{ids}")
public R delete(@PathVariable List<Long> ids) {
public R<Void> delete(@PathVariable List<Long> ids) {
baseService.delete(ids);
return R.ok("删除成功");
}

@Operation(summary = "标记已读", description = "将消息标记为已读状态")
@Parameter(name = "ids", description = "消息ID列表", example = "1,2", in = ParameterIn.QUERY)
@PatchMapping("/read")
public R readMessage(@RequestParam(required = false) List<Long> ids) {
public R<Void> readMessage(@RequestParam(required = false) List<Long> ids) {
messageUserService.readMessage(ids);
return R.ok();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,15 +59,15 @@ public R<List<OptionResp>> list(@Validated OptionQuery query) {
@Operation(summary = "修改参数", description = "修改参数")
@SaCheckPermission("system:config:update")
@PatchMapping
public R update(@Validated @RequestBody List<OptionReq> req) {
public R<Void> update(@Validated @RequestBody List<OptionReq> req) {
optionService.update(req);
return R.ok();
}

@Operation(summary = "重置参数", description = "重置参数")
@SaCheckPermission("system:config:reset")
@PatchMapping("/value")
public R resetValue(@Validated @RequestBody OptionResetValueReq req) {
public R<Void> resetValue(@Validated @RequestBody OptionResetValueReq req) {
optionService.resetValue(req);
return R.ok();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,14 +80,14 @@ public R<AvatarResp> uploadAvatar(@NotNull(message = "头像不能为空") Multi

@Operation(summary = "修改基础信息", description = "修改用户基础信息")
@PatchMapping("/basic/info")
public R updateBasicInfo(@Validated @RequestBody UserBasicInfoUpdateReq req) {
public R<Void> updateBasicInfo(@Validated @RequestBody UserBasicInfoUpdateReq req) {
userService.updateBasicInfo(req, LoginHelper.getUserId());
return R.ok("修改成功");
}

@Operation(summary = "修改密码", description = "修改用户登录密码")
@PatchMapping("/password")
public R updatePassword(@Validated @RequestBody UserPasswordUpdateReq updateReq) {
public R<Void> updatePassword(@Validated @RequestBody UserPasswordUpdateReq updateReq) {
String rawOldPassword = ExceptionUtils.exToNull(() -> SecureUtils.decryptByRsaPrivateKey(updateReq
.getOldPassword()));
ValidationUtils.throwIfNull(rawOldPassword, "当前密码解密失败");
Expand All @@ -97,12 +97,12 @@ public R updatePassword(@Validated @RequestBody UserPasswordUpdateReq updateReq)
ValidationUtils.throwIf(!ReUtil
.isMatch(RegexConstants.PASSWORD, rawNewPassword), "密码长度为 6 到 32 位,可以包含字母、数字、下划线,特殊字符,同时包含字母和数字");
userService.updatePassword(rawOldPassword, rawNewPassword, LoginHelper.getUserId());
return R.ok("修改成功");
return R.ok("修改成功,请牢记你的新密码");
}

@Operation(summary = "修改手机号", description = "修改手机号")
@PatchMapping("/phone")
public R updatePhone(@Validated @RequestBody UserPhoneUpdateReq updateReq) {
public R<Void> updatePhone(@Validated @RequestBody UserPhoneUpdateReq updateReq) {
String rawCurrentPassword = ExceptionUtils.exToNull(() -> SecureUtils.decryptByRsaPrivateKey(updateReq
.getCurrentPassword()));
ValidationUtils.throwIfBlank(rawCurrentPassword, "当前密码解密失败");
Expand All @@ -117,7 +117,7 @@ public R updatePhone(@Validated @RequestBody UserPhoneUpdateReq updateReq) {

@Operation(summary = "修改邮箱", description = "修改用户邮箱")
@PatchMapping("/email")
public R updateEmail(@Validated @RequestBody UserEmailUpdateRequest updateReq) {
public R<Void> updateEmail(@Validated @RequestBody UserEmailUpdateRequest updateReq) {
String rawCurrentPassword = ExceptionUtils.exToNull(() -> SecureUtils.decryptByRsaPrivateKey(updateReq
.getCurrentPassword()));
ValidationUtils.throwIfBlank(rawCurrentPassword, "当前密码解密失败");
Expand Down Expand Up @@ -147,7 +147,7 @@ public R<List<UserSocialBindResp>> listSocialBind() {
@Operation(summary = "绑定三方账号", description = "绑定三方账号")
@Parameter(name = "source", description = "来源", example = "gitee", in = ParameterIn.PATH)
@PostMapping("/social/{source}")
public R bindSocial(@PathVariable String source, @RequestBody AuthCallback callback) {
public R<Void> bindSocial(@PathVariable String source, @RequestBody AuthCallback callback) {
AuthRequest authRequest = authRequestFactory.get(source);
AuthResponse<AuthUser> response = authRequest.login(callback);
ValidationUtils.throwIf(!response.ok(), response.getMsg());
Expand All @@ -159,7 +159,7 @@ public R bindSocial(@PathVariable String source, @RequestBody AuthCallback callb
@Operation(summary = "解绑三方账号", description = "解绑三方账号")
@Parameter(name = "source", description = "来源", example = "gitee", in = ParameterIn.PATH)
@DeleteMapping("/social/{source}")
public R unbindSocial(@PathVariable String source) {
public R<Void> unbindSocial(@PathVariable String source) {
userSocialService.deleteBySourceAndUserId(source, LoginHelper.getUserId());
return R.ok("解绑成功");
}
Expand Down
Loading

0 comments on commit 3d77aa9

Please sign in to comment.