diff --git a/luoo_common/src/main/java/constants/ErrorConstants.java b/luoo_common/src/main/java/constants/ErrorConstants.java index 92de5bb..4f86971 100644 --- a/luoo_common/src/main/java/constants/ErrorConstants.java +++ b/luoo_common/src/main/java/constants/ErrorConstants.java @@ -27,4 +27,13 @@ public class ErrorConstants { public final static String PRICING_MUST_BE_GREATER_THAN_0 = "定价必须大于0"; public final static String ALBUM_SONG_LIST_IS_EMPTY = "专辑歌曲为空"; + + // 用户部分 + public final static String REAL_NAME_APPROVE_IS_EXISTS = "该用户实名认证已存在"; + + public final static String REAL_NAME_IS_CHECKED = "该用户实名认证已审核完成"; + + public final static String REAL_NAME_ERROR = "实名认证错误"; + + public final static String REASONS_FOR_REFUSAL_MUST_BE_GIVEN = "必须填写拒绝理由"; } diff --git a/luoo_common/src/main/java/enums/UserRealNameStateEnum.java b/luoo_common/src/main/java/enums/UserRealNameStateEnum.java new file mode 100644 index 0000000..9fbe52b --- /dev/null +++ b/luoo_common/src/main/java/enums/UserRealNameStateEnum.java @@ -0,0 +1,32 @@ +package enums; + +import lombok.Getter; + +/** + * @Author: yawei.huang + * @Package: enums + * @Project: luoo_parent + * @Date: 2024/5/6 15:40 + * @Filename: UserRealNameStateEnum + * @Describe: 实名认证状态 + */ +@Getter +public enum UserRealNameStateEnum { + + UNBIND(-1, "解绑"), + + CREATE(1, "待审核"), + + PASS(2, "通过"), + + FAIL(3, "不通过"); + + + private Integer code; + private String desc; + + UserRealNameStateEnum(Integer status, String desc) { + this.code = status; + this.desc = desc; + } +} diff --git a/luoo_user/src/main/java/com/luoo/user/controller/MyController.java b/luoo_user/src/main/java/com/luoo/user/controller/MyController.java index b3ca20f..828e61c 100644 --- a/luoo_user/src/main/java/com/luoo/user/controller/MyController.java +++ b/luoo_user/src/main/java/com/luoo/user/controller/MyController.java @@ -1,18 +1,25 @@ package com.luoo.user.controller; -import java.io.IOException; -import java.util.*; -import java.util.function.Function; -import java.util.stream.Collectors; - +import annotation.GlobalInterceptor; +import annotation.VerifyParam; +import api.PageResult; +import api.Result; +import api.StatusCode; import com.github.houbb.sensitive.word.bs.SensitiveWordBs; import com.luoo.user.dao.UserMessageDao; -import com.luoo.user.dto.FeedbackImage; -import com.luoo.user.dto.TotalCommentVo; +import com.luoo.user.dto.*; import com.luoo.user.dto.request.LoginReq; import com.luoo.user.dto.request.LogoffReq; +import com.luoo.user.dto.response.UserRespDTO; import com.luoo.user.pojo.*; import com.luoo.user.service.*; +import com.luoo.user.util.EmojiConverterUtil; +import com.luoo.user.util.IpUtil; +import constants.Constants; +import controller.BaseController; +import dto.UserLoginDto; +import enums.*; +import io.swagger.annotations.*; import org.apache.commons.lang.StringUtils; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.BeanUtils; @@ -26,465 +33,439 @@ import org.springframework.data.mongodb.core.aggregation.AggregationResults; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.util.CollectionUtils; -import org.springframework.web.bind.annotation.CrossOrigin; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.PutMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestHeader; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; -import constants.Constants; -import controller.BaseController; - -import com.luoo.user.dto.UserInfoUpdateDto; -import com.luoo.user.dto.response.UserRespDTO; -import com.luoo.user.util.EmojiConverterUtil; -import com.luoo.user.util.IpUtil; - -import annotation.GlobalInterceptor; -import annotation.VerifyParam; -import api.PageResult; -import api.Result; -import api.StatusCode; -import dto.UserLoginDto; -import enums.CollectTypeEnum; -import enums.DateTimePatternEnum; -import enums.RequestFrequencyTypeEnum; -import enums.UserBadgeEnum; -import enums.UserRelationEnum; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiImplicitParam; -import io.swagger.annotations.ApiImplicitParams; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; import util.DateUtil; import util.IdWorker; import util.ScaleFilter; import util.StringTools; +import java.io.IOException; +import java.util.*; +import java.util.function.Function; +import java.util.stream.Collectors; + @RestController @CrossOrigin @RequestMapping("/my") @Api(tags = "MyController") public class MyController extends BaseController { - private static final String REDIS_KEY_THANKS = "thanks"; - @Autowired - private S3Service s3Service; - @Autowired - private UserInfoService userInfoService; - @Autowired - private IdWorker idWorker; - @Autowired - private UserCollectInfoService userCollectInfoService; - - @Autowired - private FeedbackService feedbackService; - - @Autowired - private MyService myService; - - @Autowired - private MongoTemplate mongoTemplate; - - @Autowired - private RabbitTemplate rabbitTemplate; - - @Autowired - private SensitiveWordBs sensitiveWordBs; - - @Autowired - private RedisTemplate redisTemplate; - - @Autowired - private UserMessageDao userMessageDao; - - @ApiOperation(value = "1.获取个人信息", notes = "游客无法获取个人信息") - @GetMapping("/userInfo") - @GlobalInterceptor(checkAppUserLogin = true) - public Result getUserInfo( - @RequestHeader(value = "Authorization", required = true) String authorization) { - UserLoginDto userLoginDto = getUserLoginDto(authorization); - UserInfo user = userInfoService.findById(userLoginDto.getUserId()); - UserRespDTO userRespDTO = getUserRespDTO(user, true, Collections.emptySet()); - userRespDTO.setMobile(user.getMobile()); - userRespDTO.setWxId(user.getWxId()); - userRespDTO.setAppleId(user.getAppleId()); - userRespDTO.setWxNickname(user.getWxNickname()); - userRespDTO.setAppleEmail(user.getAppleEmail()); - userRespDTO.setEnableNotice(1); - userRespDTO.setEnablePush(1); - if (null != user.getEnableNotice()) { - userRespDTO.setEnableNotice(user.getEnableNotice()); - } - if (null != user.getEnablePush()) { - userRespDTO.setEnablePush(user.getEnablePush()); - } - return Result.success(userRespDTO); - } - - @ApiOperation(value = "2.更新个人信息", notes = "游客无法编辑个人信息") - @PutMapping("/userInfo") - @GlobalInterceptor(checkAppUserLogin = true) - public Result updateUserInfo(@RequestHeader(value = "Authorization", required = true) String authorization, - @VerifyParam(required = true) @RequestBody UserInfoUpdateDto userInfoUpdateDto) { - UserLoginDto userLoginDto = getUserLoginDto(authorization); - UserInfo user = userInfoService.findById(userLoginDto.getUserId()); - String nickName = EmojiConverterUtil.encode(userInfoUpdateDto.getNickName()); + private static final String REDIS_KEY_THANKS = "thanks"; + @Autowired + private S3Service s3Service; + @Autowired + private UserInfoService userInfoService; + @Autowired + private IdWorker idWorker; + @Autowired + private UserCollectInfoService userCollectInfoService; + + @Autowired + private FeedbackService feedbackService; + + @Autowired + private MyService myService; + + @Autowired + private MongoTemplate mongoTemplate; + + @Autowired + private RabbitTemplate rabbitTemplate; + + @Autowired + private SensitiveWordBs sensitiveWordBs; + + @Autowired + private RedisTemplate redisTemplate; + + @Autowired + private UserMessageDao userMessageDao; + + @ApiOperation(value = "1.获取个人信息", notes = "游客无法获取个人信息") + @GetMapping("/userInfo") + @GlobalInterceptor(checkAppUserLogin = true) + public Result getUserInfo( + @RequestHeader(value = "Authorization", required = true) String authorization) { + UserLoginDto userLoginDto = getUserLoginDto(authorization); + UserInfo user = userInfoService.findById(userLoginDto.getUserId()); + UserRespDTO userRespDTO = getUserRespDTO(user, true, Collections.emptySet()); + userRespDTO.setMobile(user.getMobile()); + userRespDTO.setWxId(user.getWxId()); + userRespDTO.setAppleId(user.getAppleId()); + userRespDTO.setWxNickname(user.getWxNickname()); + userRespDTO.setAppleEmail(user.getAppleEmail()); + userRespDTO.setEnableNotice(1); + userRespDTO.setEnablePush(1); + if (null != user.getEnableNotice()) { + userRespDTO.setEnableNotice(user.getEnableNotice()); + } + if (null != user.getEnablePush()) { + userRespDTO.setEnablePush(user.getEnablePush()); + } + return Result.success(userRespDTO); + } + + @ApiOperation(value = "2.更新个人信息", notes = "游客无法编辑个人信息") + @PutMapping("/userInfo") + @GlobalInterceptor(checkAppUserLogin = true) + public Result updateUserInfo(@RequestHeader(value = "Authorization", required = true) String authorization, + @VerifyParam(required = true) @RequestBody UserInfoUpdateDto userInfoUpdateDto) { + UserLoginDto userLoginDto = getUserLoginDto(authorization); + UserInfo user = userInfoService.findById(userLoginDto.getUserId()); + String nickName = EmojiConverterUtil.encode(userInfoUpdateDto.getNickName()); String result = sensitiveWordBs.findFirst(nickName); - if (StringUtils.isNotEmpty(result)) { - return Result.failed(StatusCode.USER_SENSITIVE_INFO); - } - if (!StringTools.isEmpty(nickName) && !nickName.equals(user.getNickName())) { - long count = userInfoService.countByNickName(nickName); - if (count > 0) { - return Result.failed(StatusCode.USER_NICK_NAME_HAS_BEEN_EXIST); - } - } - - if (!StringTools.isEmpty(nickName)) { - user.setNickName(nickName); - rabbitTemplate.convertAndSend("userInfoCommentCache",userLoginDto.getUserId()); - } - if (!StringTools.isEmpty(userInfoUpdateDto.getSignature())) { - String signature = sensitiveWordBs.findFirst(userInfoUpdateDto.getSignature()); - if(StringUtils.isNotEmpty(signature)) { - return Result.failed(StatusCode.USER_SENSITIVE_INFO); - } - user.setSignature(userInfoUpdateDto.getSignature()); - } - if (!StringTools.isEmpty(userInfoUpdateDto.getBirthDay())) { - user.setBirthday(DateUtil.parse(userInfoUpdateDto.getBirthDay(), - DateTimePatternEnum.YYYY_DOT_MM_DOT_DD.getPattern())); - } - if (null != userInfoUpdateDto.getSex()) { - user.setSex(userInfoUpdateDto.getSex()); - } - user.setModifyTime(new Date()); - userInfoService.update(user); - return Result.success(); - } - - @ApiOperation(value = "3.上传个人头像", notes = "图片存入S3,桶为indie,目录为 user/avatar/, 缩略图大小为200X200") - @PostMapping("/avatar") - @GlobalInterceptor(checkAppUserLogin = true) - public Result uploadAvatar(@RequestHeader(value = "Authorization", required = true) String authorization, - @VerifyParam(required = true) MultipartFile file) throws IOException { - UserLoginDto userLoginDto = getUserLoginDto(authorization); - - byte[] avatar = file.getBytes(); - String fileId=userLoginDto.getUserId() + "_" + idWorker.nextId(); - String avatarName = fileId - + StringTools.getFileSuffix(file.getOriginalFilename()); - String avatarFilePath = Constants.USER_AVATAR_DIRECTORY + avatarName; - s3Service.uploadImage("indie", avatarFilePath, avatar); - - - UserInfo user = userInfoService.findById(userLoginDto.getUserId()); - user.setAvatar(avatarFilePath); - - byte[] thumbnail = ScaleFilter.createThumbnail(file.getInputStream(), Constants.LENGTH_200, Constants.LENGTH_200); - if(null!=thumbnail) { - String thumbnailName = fileId+"_thumbnail" - + StringTools.getFileSuffix(file.getOriginalFilename()); - String thumbnailFilePath = Constants.USER_AVATAR_DIRECTORY + thumbnailName; - s3Service.uploadImage("indie", thumbnailFilePath, thumbnail); - user.setThumbnail(thumbnailFilePath); - }else { - user.setThumbnail(avatarFilePath); - } - - userInfoService.update(user); - rabbitTemplate.convertAndSend("userInfoCommentCache",userLoginDto.getUserId()); - return Result.success(Constants.RESOURCE_PREFIX + user.getThumbnail()); - } - - @ApiOperation(value = "4.查看他人信息", notes = "游客无法查看他人信息") - @GetMapping("/otherUserInfo/{userId}") - @GlobalInterceptor(checkAppUserLogin = true) - public Result getOtherUserInfo( - @RequestHeader(value = "Authorization", required = true) String authorization, - @VerifyParam(required = true) @PathVariable String userId) { - UserInfo user = userInfoService.findById(userId); - if (null == user) { - return Result.failed(StatusCode.USER_INVALID_USER_ID); - } - - UserRespDTO userRespDTO = getUserRespDTO(user, true, Collections.emptySet()); - userRespDTO.setIpLocation(IpUtil.getIpLocation(user.getLastLoginIp())); - - UserLoginDto userLoginDto = getUserLoginDto(authorization); - //若当前登录用户与查询他人 用户 id一致,则为我的主页,不查询与他人关系 - if(userId.equals(userLoginDto.getUserId())) { - return Result.success(userRespDTO); - } - userRespDTO.setRelation(userCollectInfoService.getRelation(userLoginDto.getUserId(),userId).getStatus()); - return Result.success(userRespDTO); - } - - @ApiOperation(value = "5.查询黑名单") - @ApiImplicitParams({ @ApiImplicitParam(name = "pageNum", value = "分页: 页码,以1开始", required = true), - @ApiImplicitParam(name = "pageSize", value = "分页: 每页数量", required = true) }) - @GetMapping("/blackList/{pageNum}/{pageSize}") - @GlobalInterceptor(checkAppUserLogin = true) - public Result> getBlackList( - @RequestHeader(value = "Authorization", required = true) String authorization, - @PathVariable @VerifyParam(required = true) Integer pageNum, - @PathVariable @VerifyParam(required = true) Integer pageSize) { - UserLoginDto userLoginDto = getUserLoginDto(authorization); - return getCollectedUserInfo(userLoginDto.getUserId(), pageNum, pageSize, CollectTypeEnum.BLACK_LIST); - } - - @ApiOperation(value = "6.查询关注人信息") - @ApiImplicitParams({ @ApiImplicitParam(name = "userId", value = "用户id", required = true), - @ApiImplicitParam(name = "pageNum", value = "分页: 页码,以1开始", required = true), - @ApiImplicitParam(name = "pageSize", value = "分页: 每页数量", required = true) }) - @GetMapping("/follows/{userId}/{pageNum}/{pageSize}") - @GlobalInterceptor(checkAppUserLogin = true) - public Result> getFollows( - @RequestHeader(value = "Authorization", required = true) String authorization, - @PathVariable @VerifyParam(required = true) String userId, - @PathVariable @VerifyParam(required = true) Integer pageNum, - @PathVariable @VerifyParam(required = true) Integer pageSize) { - - return getCollectedUserInfo(userId, pageNum, pageSize, CollectTypeEnum.FOLLOWS); - } - - @ApiOperation(value = "7.查询粉丝信息") - @ApiImplicitParams({ @ApiImplicitParam(name = "userId", value = "用户id", required = true), - @ApiImplicitParam(name = "pageNum", value = "分页: 页码,以1开始", required = true), - @ApiImplicitParam(name = "pageSize", value = "分页: 每页数量", required = true) }) - @GetMapping("/fans/{userId}/{pageNum}/{pageSize}") - @GlobalInterceptor(checkAppUserLogin = true) - public Result> getFans( - @RequestHeader(value = "Authorization", required = true) String authorization, - @PathVariable @VerifyParam(required = true) String userId, - @PathVariable @VerifyParam(required = true) Integer pageNum, - @PathVariable @VerifyParam(required = true) Integer pageSize) { - return getCollectedUserInfo(userId, pageNum, pageSize, CollectTypeEnum.FANS); - } - - @ApiOperation(value = "8.意见反馈", notes = "每天最多反馈30条") - @PostMapping("/feedback") - @GlobalInterceptor(checkAppUserLogin = true, frequencyType = RequestFrequencyTypeEnum.DAY, requestFrequencyThreshold = 30) - public Result sendFeedback(@RequestHeader(value = "Authorization", required = true) String authorization, - @ApiParam(value = "反馈类型,3个值,0:bug, 1:建议,2:其它", required = true) @VerifyParam(required = true) @RequestParam("type") Integer type, - @ApiParam(value = "反馈内容,最多300字", required = true) @VerifyParam(required = true, max = 300) @RequestParam("content") String content, - @ApiParam(value = "图片,单张图片最大5M,一次上传最多10张图片", required = false) @RequestParam("files") List files, - @ApiParam(value = "联系方式(可选),最多50字", required = false) @RequestParam("contact") @VerifyParam(max = 50) String contact) { - UserLoginDto userLoginDto = getUserLoginDto(authorization); - Feedback feedback = new Feedback(); - feedback.setFeedbackId(String.valueOf(idWorker.nextId())); - feedback.setType(type); - feedback.setUserId(userLoginDto.getUserId()); - feedback.setNickName(EmojiConverterUtil.encode(userLoginDto.getNickName())); - feedback.setContent(EmojiConverterUtil.encode(content)); - feedbackService.send(feedback, getInputStream(files)); - return Result.success(); - } - - private List getInputStream(List files) { - if(null==files) { - return Collections.emptyList(); - } - return files.stream().map(this::getFeedbackImage).collect(Collectors.toList()); - } - private FeedbackImage getFeedbackImage(MultipartFile multipartFile) { - FeedbackImage feedbackImage=new FeedbackImage(); - try { - feedbackImage.setInputStream(multipartFile.getInputStream()); - }catch(Exception e) { - e.printStackTrace(); - } - feedbackImage.setContentType(multipartFile.getContentType()); - feedbackImage.setOriginalFilename(multipartFile.getOriginalFilename()); - feedbackImage.setSize(multipartFile.getSize()); - return feedbackImage; - } - - private Result> getCollectedUserInfo(String userId, Integer pageNum, Integer pageSize, - CollectTypeEnum collectTypeEnum) { - Pageable pageable = PageRequest.of(pageNum-1,pageSize); - boolean isGetFan=isGetFan(collectTypeEnum); - Page userCollectInfos = isGetFan?userCollectInfoService.findByObjectIdAndCollectType(userId,CollectTypeEnum.FOLLOWS,pageable):userCollectInfoService.findByUserIdAndCollectType(userId,collectTypeEnum,pageable); - Function idFunction=isGetFan?UserCollectInfo::getUserId:UserCollectInfo::getObjectId; - List objectIds=userCollectInfos.stream().map(idFunction).collect(Collectors.toList()); - if (objectIds.isEmpty()) { - return Result.success(new PageResult(0L, Collections.emptyList())); - } - List userInfos = userInfoService.orderByField(objectIds); - Set bothFollowSet=userCollectInfos.stream().filter(c->Boolean.TRUE.equals(c.getIsMutualFans())).map(u->isGetFan?u.getUserId():u.getObjectId()).collect(Collectors.toSet()); - List results = userInfos.stream().map(s -> getUserRespDTO(s, false, bothFollowSet)) - .collect(Collectors.toList()); - return Result.success(new PageResult(Long.valueOf(results.size()), results)); - } - - private boolean isGetFan(CollectTypeEnum collectTypeEnum) { - return CollectTypeEnum.FANS.equals(collectTypeEnum); - } - - private UserRespDTO getUserRespDTO(UserInfo user, boolean withCount, Set bothFollowSet) { - UserRespDTO userRespDTO = new UserRespDTO(); - BeanUtils.copyProperties(user, userRespDTO); - if(!StringTools.isEmpty(user.getBadges())) { - Set badgeSet = new HashSet<>(); - Arrays.stream(user.getBadges().split(",")).forEach(b->{ - int code=Integer.valueOf(b.substring(0, 1)); - badgeSet.add(code); - if(code==UserBadgeEnum.CONTRIBUTOR.getCode()) { - userRespDTO.setContributorRole(UserBadgeEnum.getByCode(Integer.valueOf(b.split("_")[0])).getDesc()); - } - }); - userRespDTO.setBadgeList(new ArrayList<>(badgeSet)); - } - if (null != userRespDTO.getAvatar()) { - userRespDTO.setAvatar(getAvatar(user)); - } - if (null != user.getBirthday()) { - userRespDTO.setBirthDay( - DateUtil.format(user.getBirthday(), DateTimePatternEnum.YYYY_DOT_MM_DOT_DD.getPattern())); - } - if (!bothFollowSet.isEmpty() && bothFollowSet.contains(userRespDTO.getId())) { - userRespDTO.setRelation(UserRelationEnum.BOTH_FOLLOW.getStatus()); - } - if (!withCount) { - return userRespDTO; - } - /** - * 获取点赞数和评论数 - */ - Criteria criteria = Criteria.where("userId").is(userRespDTO.getId()); - Aggregation agg = Aggregation.newAggregation( - Aggregation.match(criteria),//匹配条件 - Aggregation.group().sum("thumbupCount").as("totalThumbup") - .sum("commentCount").as("totalComment") - ); - - AggregationResults results = mongoTemplate.aggregate(agg,"comment", TotalCommentVo.class); - - TotalCommentVo totalCommentVo = results.getUniqueMappedResult(); - if(null != totalCommentVo) { - userRespDTO.setThumbUpCount(totalCommentVo.getTotalThumbup()); - userRespDTO.setCommentReplyCount(totalCommentVo.getTotalComment()); - } - UserMessage userMessage = userMessageDao.findTopByUserIdOrderBySendTimeDesc(user.getId()); - userRespDTO.setHaveNewMessage(false); - if (null!=userMessage) { - int read = userMessage.getHaveRead(); - userRespDTO.setHaveNewMessage(read==0?true:false); - } - return userRespDTO; - } - - private String getAvatar(UserInfo user) { - if(StringTools.isEmpty(user.getThumbnail())) { - return Constants.RESOURCE_PREFIX + user.getAvatar(); - } - return Constants.RESOURCE_PREFIX + user.getThumbnail(); - } - - // 查询我的获赞 - @ApiOperation(value = "9.查询我的获赞的分页列表", notes = "游客无法获取") - @GetMapping("/myThumbupList/{page}/{size}") - public Result getMyThumbupList(@PathVariable int page,@PathVariable int size,@RequestHeader(value = "Authorization", required = true) String authorization) { - - //验证是否登录,并且拿到ID - UserLoginDto userLoginDto = getUserLoginDto(authorization); - if (null == userLoginDto) { - return Result.unauthorized(null); - } - String userId = userLoginDto.getUserId(); - Page pageList = myService.getMyThumbupList(userId,page,size); - - List list = pageList.stream().parallel().map(x->getPublicationLike(x)).collect(Collectors.toList()); - - - - return Result.success(new PageResult(Long.valueOf(list.size()),list)); - } - - private PublicationLike getPublicationLike(PublicationLike publicationLike) { - UserInfo userInfo = userInfoService.findById(publicationLike.getUserId()); - publicationLike.setNickName("已注销"); - publicationLike.setAvatar(Constants.RESOURCE_PREFIX+Constants.DEFAULT_USER_THUMBNAIL); - if(null != userInfo) { - publicationLike.setNickName(userInfo.getNickName()); - publicationLike.setAvatar(Constants.RESOURCE_PREFIX+userInfo.getAvatar()); - } - - return publicationLike; - } - // 查询我收到的评论 - @ApiOperation(value = "10.查询我收到的评论分页列表", notes = "游客无法获取") - @GetMapping("/myCommentReplyList/{page}/{size}") - public Result getMyCommentReplyList(@PathVariable int page,@PathVariable int size,@RequestHeader(value = "Authorization", required = true) String authorization) { - - //验证是否登录,并且拿到ID - UserLoginDto userLoginDto = getUserLoginDto(authorization); - if (null == userLoginDto) { - return Result.unauthorized(null); - } - String userId = userLoginDto.getUserId(); - Page pageList = myService.getMyCommentReplyList(userId,page,size); - List list = pageList.stream().parallel().map(x->getCommentHis(x)).collect(Collectors.toList()); - return Result.success(new PageResult(Long.valueOf(list.size()),list)); - } - - private CommentHis getCommentHis(CommentHis commentHis) { - - UserInfo userInfo = userInfoService.findById(commentHis.getCommenterId()); - commentHis.setNickName("已注销"); - commentHis.setCommenterAvatar(Constants.RESOURCE_PREFIX+Constants.DEFAULT_USER_THUMBNAIL); - if(null != userInfo) { - commentHis.setNickName(userInfo.getNickName()); - commentHis.setCommenterAvatar(Constants.RESOURCE_PREFIX+userInfo.getAvatar()); - } - - return commentHis; - } - - // 查询我收到的评论 - @ApiOperation(value = "11.感谢", notes = "贡献者列表") - @GetMapping("/thanks") - public Result> getThanks() { - return Result.success(getThankList()); - } - - @SuppressWarnings("unchecked") - private List getThankList() { - List thanks = (List) redisTemplate.opsForValue().get(REDIS_KEY_THANKS); - if (CollectionUtils.isEmpty(thanks)) { - thanks = userInfoService.getThanks().stream().sorted(Comparator.comparing(u->getIndex(u))).map(user->getUserRespDTO(user, false, Collections.emptySet())).collect(Collectors.toList()); - redisTemplate.opsForValue().set(REDIS_KEY_THANKS, thanks); - } - return thanks; - } - - - @ApiOperation(value = "12 注销账号", notes = "注销账号") - @PostMapping ("/logOff") - public Result logOff(@RequestHeader(value = "Authorization", required = true) String authorization, @VerifyParam LogoffReq logoffReq) { - //验证是否登录,并且拿到ID - UserLoginDto userLoginDto = getUserLoginDto(authorization); - if (null == userLoginDto) { - return Result.unauthorized(null); - } - String userId = userLoginDto.getUserId(); - // 得到缓存中的验证码 - String redisMobileCheckCodeKey = Constants.REDIS_KEY_MOBILE_CHECK_CODE + logoffReq.getDeviceId(); - String redisMobileCheckCode = (String) redisTemplate.opsForValue().get(redisMobileCheckCodeKey); - if (StringTools.isEmpty(redisMobileCheckCode)) { - return Result.failed(StatusCode.USER_MOBILE_VERIFICATION_CODE_EXPIRED); - } - if (!redisMobileCheckCode.equals(logoffReq.getMobileCheckCode())) { - return Result.failed(StatusCode.USER_MOBILE_VERIFICATION_CODE_MISMATCH); - } - - // 删除账号 + if (StringUtils.isNotEmpty(result)) { + return Result.failed(StatusCode.USER_SENSITIVE_INFO); + } + if (!StringTools.isEmpty(nickName) && !nickName.equals(user.getNickName())) { + long count = userInfoService.countByNickName(nickName); + if (count > 0) { + return Result.failed(StatusCode.USER_NICK_NAME_HAS_BEEN_EXIST); + } + } + + if (!StringTools.isEmpty(nickName)) { + user.setNickName(nickName); + rabbitTemplate.convertAndSend("userInfoCommentCache", userLoginDto.getUserId()); + } + if (!StringTools.isEmpty(userInfoUpdateDto.getSignature())) { + String signature = sensitiveWordBs.findFirst(userInfoUpdateDto.getSignature()); + if (StringUtils.isNotEmpty(signature)) { + return Result.failed(StatusCode.USER_SENSITIVE_INFO); + } + user.setSignature(userInfoUpdateDto.getSignature()); + } + if (!StringTools.isEmpty(userInfoUpdateDto.getBirthDay())) { + user.setBirthday(DateUtil.parse(userInfoUpdateDto.getBirthDay(), + DateTimePatternEnum.YYYY_DOT_MM_DOT_DD.getPattern())); + } + if (null != userInfoUpdateDto.getSex()) { + user.setSex(userInfoUpdateDto.getSex()); + } + user.setModifyTime(new Date()); + userInfoService.update(user); + return Result.success(); + } + + @ApiOperation(value = "3.上传个人头像", notes = "图片存入S3,桶为indie,目录为 user/avatar/, 缩略图大小为200X200") + @PostMapping("/avatar") + @GlobalInterceptor(checkAppUserLogin = true) + public Result uploadAvatar(@RequestHeader(value = "Authorization", required = true) String authorization, + @VerifyParam(required = true) MultipartFile file) throws IOException { + UserLoginDto userLoginDto = getUserLoginDto(authorization); + + byte[] avatar = file.getBytes(); + String fileId = userLoginDto.getUserId() + "_" + idWorker.nextId(); + String avatarName = fileId + + StringTools.getFileSuffix(file.getOriginalFilename()); + String avatarFilePath = Constants.USER_AVATAR_DIRECTORY + avatarName; + s3Service.uploadImage("indie", avatarFilePath, avatar); + + + UserInfo user = userInfoService.findById(userLoginDto.getUserId()); + user.setAvatar(avatarFilePath); + + byte[] thumbnail = ScaleFilter.createThumbnail(file.getInputStream(), Constants.LENGTH_200, Constants.LENGTH_200); + if (null != thumbnail) { + String thumbnailName = fileId + "_thumbnail" + + StringTools.getFileSuffix(file.getOriginalFilename()); + String thumbnailFilePath = Constants.USER_AVATAR_DIRECTORY + thumbnailName; + s3Service.uploadImage("indie", thumbnailFilePath, thumbnail); + user.setThumbnail(thumbnailFilePath); + } else { + user.setThumbnail(avatarFilePath); + } + + userInfoService.update(user); + rabbitTemplate.convertAndSend("userInfoCommentCache", userLoginDto.getUserId()); + return Result.success(Constants.RESOURCE_PREFIX + user.getThumbnail()); + } + + @ApiOperation(value = "4.查看他人信息", notes = "游客无法查看他人信息") + @GetMapping("/otherUserInfo/{userId}") + @GlobalInterceptor(checkAppUserLogin = true) + public Result getOtherUserInfo( + @RequestHeader(value = "Authorization", required = true) String authorization, + @VerifyParam(required = true) @PathVariable String userId) { + UserInfo user = userInfoService.findById(userId); + if (null == user) { + return Result.failed(StatusCode.USER_INVALID_USER_ID); + } + + UserRespDTO userRespDTO = getUserRespDTO(user, true, Collections.emptySet()); + userRespDTO.setIpLocation(IpUtil.getIpLocation(user.getLastLoginIp())); + + UserLoginDto userLoginDto = getUserLoginDto(authorization); + //若当前登录用户与查询他人 用户 id一致,则为我的主页,不查询与他人关系 + if (userId.equals(userLoginDto.getUserId())) { + return Result.success(userRespDTO); + } + userRespDTO.setRelation(userCollectInfoService.getRelation(userLoginDto.getUserId(), userId).getStatus()); + return Result.success(userRespDTO); + } + + @ApiOperation(value = "5.查询黑名单") + @ApiImplicitParams({@ApiImplicitParam(name = "pageNum", value = "分页: 页码,以1开始", required = true), + @ApiImplicitParam(name = "pageSize", value = "分页: 每页数量", required = true)}) + @GetMapping("/blackList/{pageNum}/{pageSize}") + @GlobalInterceptor(checkAppUserLogin = true) + public Result> getBlackList( + @RequestHeader(value = "Authorization", required = true) String authorization, + @PathVariable @VerifyParam(required = true) Integer pageNum, + @PathVariable @VerifyParam(required = true) Integer pageSize) { + UserLoginDto userLoginDto = getUserLoginDto(authorization); + return getCollectedUserInfo(userLoginDto.getUserId(), pageNum, pageSize, CollectTypeEnum.BLACK_LIST); + } + + @ApiOperation(value = "6.查询关注人信息") + @ApiImplicitParams({@ApiImplicitParam(name = "userId", value = "用户id", required = true), + @ApiImplicitParam(name = "pageNum", value = "分页: 页码,以1开始", required = true), + @ApiImplicitParam(name = "pageSize", value = "分页: 每页数量", required = true)}) + @GetMapping("/follows/{userId}/{pageNum}/{pageSize}") + @GlobalInterceptor(checkAppUserLogin = true) + public Result> getFollows( + @RequestHeader(value = "Authorization", required = true) String authorization, + @PathVariable @VerifyParam(required = true) String userId, + @PathVariable @VerifyParam(required = true) Integer pageNum, + @PathVariable @VerifyParam(required = true) Integer pageSize) { + + return getCollectedUserInfo(userId, pageNum, pageSize, CollectTypeEnum.FOLLOWS); + } + + @ApiOperation(value = "7.查询粉丝信息") + @ApiImplicitParams({@ApiImplicitParam(name = "userId", value = "用户id", required = true), + @ApiImplicitParam(name = "pageNum", value = "分页: 页码,以1开始", required = true), + @ApiImplicitParam(name = "pageSize", value = "分页: 每页数量", required = true)}) + @GetMapping("/fans/{userId}/{pageNum}/{pageSize}") + @GlobalInterceptor(checkAppUserLogin = true) + public Result> getFans( + @RequestHeader(value = "Authorization", required = true) String authorization, + @PathVariable @VerifyParam(required = true) String userId, + @PathVariable @VerifyParam(required = true) Integer pageNum, + @PathVariable @VerifyParam(required = true) Integer pageSize) { + return getCollectedUserInfo(userId, pageNum, pageSize, CollectTypeEnum.FANS); + } + + @ApiOperation(value = "8.意见反馈", notes = "每天最多反馈30条") + @PostMapping("/feedback") + @GlobalInterceptor(checkAppUserLogin = true, frequencyType = RequestFrequencyTypeEnum.DAY, requestFrequencyThreshold = 30) + public Result sendFeedback(@RequestHeader(value = "Authorization", required = true) String authorization, + @ApiParam(value = "反馈类型,3个值,0:bug, 1:建议,2:其它", required = true) @VerifyParam(required = true) @RequestParam("type") Integer type, + @ApiParam(value = "反馈内容,最多300字", required = true) @VerifyParam(required = true, max = 300) @RequestParam("content") String content, + @ApiParam(value = "图片,单张图片最大5M,一次上传最多10张图片", required = false) @RequestParam("files") List files, + @ApiParam(value = "联系方式(可选),最多50字", required = false) @RequestParam("contact") @VerifyParam(max = 50) String contact) { + UserLoginDto userLoginDto = getUserLoginDto(authorization); + Feedback feedback = new Feedback(); + feedback.setFeedbackId(String.valueOf(idWorker.nextId())); + feedback.setType(type); + feedback.setUserId(userLoginDto.getUserId()); + feedback.setNickName(EmojiConverterUtil.encode(userLoginDto.getNickName())); + feedback.setContent(EmojiConverterUtil.encode(content)); + feedbackService.send(feedback, getInputStream(files)); + return Result.success(); + } + + private List getInputStream(List files) { + if (null == files) { + return Collections.emptyList(); + } + return files.stream().map(this::getFeedbackImage).collect(Collectors.toList()); + } + + private FeedbackImage getFeedbackImage(MultipartFile multipartFile) { + FeedbackImage feedbackImage = new FeedbackImage(); + try { + feedbackImage.setInputStream(multipartFile.getInputStream()); + } catch (Exception e) { + e.printStackTrace(); + } + feedbackImage.setContentType(multipartFile.getContentType()); + feedbackImage.setOriginalFilename(multipartFile.getOriginalFilename()); + feedbackImage.setSize(multipartFile.getSize()); + return feedbackImage; + } + + private Result> getCollectedUserInfo(String userId, Integer pageNum, Integer pageSize, + CollectTypeEnum collectTypeEnum) { + Pageable pageable = PageRequest.of(pageNum - 1, pageSize); + boolean isGetFan = isGetFan(collectTypeEnum); + Page userCollectInfos = isGetFan ? userCollectInfoService.findByObjectIdAndCollectType(userId, CollectTypeEnum.FOLLOWS, pageable) : userCollectInfoService.findByUserIdAndCollectType(userId, collectTypeEnum, pageable); + Function idFunction = isGetFan ? UserCollectInfo::getUserId : UserCollectInfo::getObjectId; + List objectIds = userCollectInfos.stream().map(idFunction).collect(Collectors.toList()); + if (objectIds.isEmpty()) { + return Result.success(new PageResult(0L, Collections.emptyList())); + } + List userInfos = userInfoService.orderByField(objectIds); + Set bothFollowSet = userCollectInfos.stream().filter(c -> Boolean.TRUE.equals(c.getIsMutualFans())).map(u -> isGetFan ? u.getUserId() : u.getObjectId()).collect(Collectors.toSet()); + List results = userInfos.stream().map(s -> getUserRespDTO(s, false, bothFollowSet)) + .collect(Collectors.toList()); + return Result.success(new PageResult(Long.valueOf(results.size()), results)); + } + + private boolean isGetFan(CollectTypeEnum collectTypeEnum) { + return CollectTypeEnum.FANS.equals(collectTypeEnum); + } + + private UserRespDTO getUserRespDTO(UserInfo user, boolean withCount, Set bothFollowSet) { + UserRespDTO userRespDTO = new UserRespDTO(); + BeanUtils.copyProperties(user, userRespDTO); + if (!StringTools.isEmpty(user.getBadges())) { + Set badgeSet = new HashSet<>(); + Arrays.stream(user.getBadges().split(",")).forEach(b -> { + int code = Integer.valueOf(b.substring(0, 1)); + badgeSet.add(code); + if (code == UserBadgeEnum.CONTRIBUTOR.getCode()) { + userRespDTO.setContributorRole(UserBadgeEnum.getByCode(Integer.valueOf(b.split("_")[0])).getDesc()); + } + }); + userRespDTO.setBadgeList(new ArrayList<>(badgeSet)); + } + if (null != userRespDTO.getAvatar()) { + userRespDTO.setAvatar(getAvatar(user)); + } + if (null != user.getBirthday()) { + userRespDTO.setBirthDay( + DateUtil.format(user.getBirthday(), DateTimePatternEnum.YYYY_DOT_MM_DOT_DD.getPattern())); + } + if (!bothFollowSet.isEmpty() && bothFollowSet.contains(userRespDTO.getId())) { + userRespDTO.setRelation(UserRelationEnum.BOTH_FOLLOW.getStatus()); + } + if (!withCount) { + return userRespDTO; + } + /** + * 获取点赞数和评论数 + */ + Criteria criteria = Criteria.where("userId").is(userRespDTO.getId()); + Aggregation agg = Aggregation.newAggregation( + Aggregation.match(criteria),//匹配条件 + Aggregation.group().sum("thumbupCount").as("totalThumbup") + .sum("commentCount").as("totalComment") + ); + + AggregationResults results = mongoTemplate.aggregate(agg, "comment", TotalCommentVo.class); + + TotalCommentVo totalCommentVo = results.getUniqueMappedResult(); + if (null != totalCommentVo) { + userRespDTO.setThumbUpCount(totalCommentVo.getTotalThumbup()); + userRespDTO.setCommentReplyCount(totalCommentVo.getTotalComment()); + } + UserMessage userMessage = userMessageDao.findTopByUserIdOrderBySendTimeDesc(user.getId()); + userRespDTO.setHaveNewMessage(false); + if (null != userMessage) { + int read = userMessage.getHaveRead(); + userRespDTO.setHaveNewMessage(read == 0 ? true : false); + } + return userRespDTO; + } + + private String getAvatar(UserInfo user) { + if (StringTools.isEmpty(user.getThumbnail())) { + return Constants.RESOURCE_PREFIX + user.getAvatar(); + } + return Constants.RESOURCE_PREFIX + user.getThumbnail(); + } + + // 查询我的获赞 + @ApiOperation(value = "9.查询我的获赞的分页列表", notes = "游客无法获取") + @GetMapping("/myThumbupList/{page}/{size}") + public Result getMyThumbupList(@PathVariable int page, @PathVariable int size, @RequestHeader(value = "Authorization", required = true) String authorization) { + + //验证是否登录,并且拿到ID + UserLoginDto userLoginDto = getUserLoginDto(authorization); + if (null == userLoginDto) { + return Result.unauthorized(null); + } + String userId = userLoginDto.getUserId(); + Page pageList = myService.getMyThumbupList(userId, page, size); + + List list = pageList.stream().parallel().map(x -> getPublicationLike(x)).collect(Collectors.toList()); + + + return Result.success(new PageResult(Long.valueOf(list.size()), list)); + } + + private PublicationLike getPublicationLike(PublicationLike publicationLike) { + UserInfo userInfo = userInfoService.findById(publicationLike.getUserId()); + publicationLike.setNickName("已注销"); + publicationLike.setAvatar(Constants.RESOURCE_PREFIX + Constants.DEFAULT_USER_THUMBNAIL); + if (null != userInfo) { + publicationLike.setNickName(userInfo.getNickName()); + publicationLike.setAvatar(Constants.RESOURCE_PREFIX + userInfo.getAvatar()); + } + + return publicationLike; + } + + // 查询我收到的评论 + @ApiOperation(value = "10.查询我收到的评论分页列表", notes = "游客无法获取") + @GetMapping("/myCommentReplyList/{page}/{size}") + public Result getMyCommentReplyList(@PathVariable int page, @PathVariable int size, @RequestHeader(value = "Authorization", required = true) String authorization) { + + //验证是否登录,并且拿到ID + UserLoginDto userLoginDto = getUserLoginDto(authorization); + if (null == userLoginDto) { + return Result.unauthorized(null); + } + String userId = userLoginDto.getUserId(); + Page pageList = myService.getMyCommentReplyList(userId, page, size); + List list = pageList.stream().parallel().map(x -> getCommentHis(x)).collect(Collectors.toList()); + return Result.success(new PageResult(Long.valueOf(list.size()), list)); + } + + private CommentHis getCommentHis(CommentHis commentHis) { + + UserInfo userInfo = userInfoService.findById(commentHis.getCommenterId()); + commentHis.setNickName("已注销"); + commentHis.setCommenterAvatar(Constants.RESOURCE_PREFIX + Constants.DEFAULT_USER_THUMBNAIL); + if (null != userInfo) { + commentHis.setNickName(userInfo.getNickName()); + commentHis.setCommenterAvatar(Constants.RESOURCE_PREFIX + userInfo.getAvatar()); + } + + return commentHis; + } + + // 查询我收到的评论 + @ApiOperation(value = "11.感谢", notes = "贡献者列表") + @GetMapping("/thanks") + public Result> getThanks() { + return Result.success(getThankList()); + } + + @SuppressWarnings("unchecked") + private List getThankList() { + List thanks = (List) redisTemplate.opsForValue().get(REDIS_KEY_THANKS); + if (CollectionUtils.isEmpty(thanks)) { + thanks = userInfoService.getThanks().stream().sorted(Comparator.comparing(u -> getIndex(u))).map(user -> getUserRespDTO(user, false, Collections.emptySet())).collect(Collectors.toList()); + redisTemplate.opsForValue().set(REDIS_KEY_THANKS, thanks); + } + return thanks; + } + + + @ApiOperation(value = "12 注销账号", notes = "注销账号") + @PostMapping("/logOff") + public Result logOff(@RequestHeader(value = "Authorization", required = true) String authorization, @VerifyParam LogoffReq logoffReq) { + //验证是否登录,并且拿到ID + UserLoginDto userLoginDto = getUserLoginDto(authorization); + if (null == userLoginDto) { + return Result.unauthorized(null); + } + String userId = userLoginDto.getUserId(); + // 得到缓存中的验证码 + String redisMobileCheckCodeKey = Constants.REDIS_KEY_MOBILE_CHECK_CODE + logoffReq.getDeviceId(); + String redisMobileCheckCode = (String) redisTemplate.opsForValue().get(redisMobileCheckCodeKey); + if (StringTools.isEmpty(redisMobileCheckCode)) { + return Result.failed(StatusCode.USER_MOBILE_VERIFICATION_CODE_EXPIRED); + } + if (!redisMobileCheckCode.equals(logoffReq.getMobileCheckCode())) { + return Result.failed(StatusCode.USER_MOBILE_VERIFICATION_CODE_MISMATCH); + } + + // 删除账号 // UserInfo userInfo = userInfoService.findById(userId); // userInfo.setMobile("已注销"); // userInfo.setAvatar(Constants.DEFAULT_USER_AVATAR); @@ -493,79 +474,106 @@ public class MyController extends BaseController { // userInfo.setAppleEmail(""); // userInfo.setWxNickname(""); // userInfoService.update(userInfo); - userInfoService.deleteById(userId); - return Result.success(); - } - - - @ApiOperation(value = "13 绑定手机号", notes = "绑定手机号") - @PostMapping ("/bindMobile") - public Result bindMobile(@RequestHeader(value = "Authorization", required = true) String authorization, @VerifyParam LoginReq loginReq) { - //验证是否登录,并且拿到ID - UserLoginDto userLoginDto = getUserLoginDto(authorization); - if (null == userLoginDto) { - return Result.unauthorized(null); - } - String userId = userLoginDto.getUserId(); - // 得到缓存中的验证码 - String redisMobileCheckCodeKey = Constants.REDIS_KEY_MOBILE_CHECK_CODE + loginReq.getDeviceId(); - String redisMobileCheckCode = (String) redisTemplate.opsForValue().get(redisMobileCheckCodeKey); - if (StringTools.isEmpty(redisMobileCheckCode)) { - return Result.failed(StatusCode.USER_MOBILE_VERIFICATION_CODE_EXPIRED); - } - if (!redisMobileCheckCode.equals(loginReq.getMobileCheckCode())) { - return Result.failed(StatusCode.USER_MOBILE_VERIFICATION_CODE_MISMATCH); - } - - UserInfo userInfo1 =userInfoService.findByMobile(loginReq.getMobile()); - UserInfo userInfo2 = userInfoService.findById(userId); - if (null != userInfo1) { - // 如果绑定的手机号已存在 + userInfoService.deleteById(userId); + return Result.success(); + } + + + @ApiOperation(value = "13 绑定手机号", notes = "绑定手机号") + @PostMapping("/bindMobile") + public Result bindMobile(@RequestHeader(value = "Authorization", required = true) String authorization, @VerifyParam LoginReq loginReq) { + //验证是否登录,并且拿到ID + UserLoginDto userLoginDto = getUserLoginDto(authorization); + if (null == userLoginDto) { + return Result.unauthorized(null); + } + String userId = userLoginDto.getUserId(); + // 得到缓存中的验证码 + String redisMobileCheckCodeKey = Constants.REDIS_KEY_MOBILE_CHECK_CODE + loginReq.getDeviceId(); + String redisMobileCheckCode = (String) redisTemplate.opsForValue().get(redisMobileCheckCodeKey); + if (StringTools.isEmpty(redisMobileCheckCode)) { + return Result.failed(StatusCode.USER_MOBILE_VERIFICATION_CODE_EXPIRED); + } + if (!redisMobileCheckCode.equals(loginReq.getMobileCheckCode())) { + return Result.failed(StatusCode.USER_MOBILE_VERIFICATION_CODE_MISMATCH); + } + + UserInfo userInfo1 = userInfoService.findByMobile(loginReq.getMobile()); + UserInfo userInfo2 = userInfoService.findById(userId); + if (null != userInfo1) { + // 如果绑定的手机号已存在 // userInfo1.setMobile(loginReq.getMobile()); - userInfo1.setAppleId(userInfo2.getAppleId()); - userInfo1.setAppleEmail(userInfo2.getAppleEmail()); - userInfoService.update(userInfo1); - String token = userInfoService.loginOrRegister(userInfo1); - userInfoService.deleteById(userId); - return Result.success(token); - - } - userInfo2.setMobile(loginReq.getMobile()); - userInfoService.update(userInfo2); - String token = userInfoService.loginOrRegister(userInfo2); - return Result.success(token); - } - - @ApiOperation(value = "14.1 启用/停用 消息, 0为停用,1为启用", notes = "启用/停用 消息, 0为停用,1为启用") - @PutMapping("/enableNotice/{flag}") - public Result updateEnableNotice(@RequestHeader(value = "Authorization", required = true) String authorization,@PathVariable int flag){ - //验证是否登录,并且拿到ID - UserLoginDto userLoginDto = getUserLoginDto(authorization); - if (null == userLoginDto) { - return Result.unauthorized(null); - } - String userId = userLoginDto.getUserId(); - UserInfo userInfo = userInfoService.findById(userId); - userInfo.setEnableNotice(flag); - userInfoService.update(userInfo); - return Result.success(); - } - - @ApiOperation(value = "14.2 启用/停用 推送, 0为停用,1为启用", notes = "启用/停用 推送, 0为停用,1为启用") - @PutMapping("/enablePush/{flag}") - public Result updateEnablePush(@RequestHeader(value = "Authorization", required = true) String authorization,@PathVariable int flag){ - //验证是否登录,并且拿到ID - UserLoginDto userLoginDto = getUserLoginDto(authorization); - if (null == userLoginDto) { - return Result.unauthorized(null); - } - String userId = userLoginDto.getUserId(); - UserInfo userInfo = userInfoService.findById(userId); - userInfo.setEnablePush(flag); - userInfoService.update(userInfo); - return Result.success(); - } - private Integer getIndex(UserInfo u) { - return Integer.valueOf(Arrays.stream(u.getBadges().split(",")).filter(s->s.startsWith(String.valueOf(UserBadgeEnum.CONTRIBUTOR.getCode()))).findFirst().get().split("_")[1]); - } + userInfo1.setAppleId(userInfo2.getAppleId()); + userInfo1.setAppleEmail(userInfo2.getAppleEmail()); + userInfoService.update(userInfo1); + String token = userInfoService.loginOrRegister(userInfo1); + userInfoService.deleteById(userId); + return Result.success(token); + + } + userInfo2.setMobile(loginReq.getMobile()); + userInfoService.update(userInfo2); + String token = userInfoService.loginOrRegister(userInfo2); + return Result.success(token); + } + + @ApiOperation(value = "14.1 启用/停用 消息, 0为停用,1为启用", notes = "启用/停用 消息, 0为停用,1为启用") + @PutMapping("/enableNotice/{flag}") + public Result updateEnableNotice(@RequestHeader(value = "Authorization", required = true) String authorization, @PathVariable int flag) { + //验证是否登录,并且拿到ID + UserLoginDto userLoginDto = getUserLoginDto(authorization); + if (null == userLoginDto) { + return Result.unauthorized(null); + } + String userId = userLoginDto.getUserId(); + UserInfo userInfo = userInfoService.findById(userId); + userInfo.setEnableNotice(flag); + userInfoService.update(userInfo); + return Result.success(); + } + + @ApiOperation(value = "14.2 启用/停用 推送, 0为停用,1为启用", notes = "启用/停用 推送, 0为停用,1为启用") + @PutMapping("/enablePush/{flag}") + public Result updateEnablePush(@RequestHeader(value = "Authorization", required = true) String authorization, @PathVariable int flag) { + //验证是否登录,并且拿到ID + UserLoginDto userLoginDto = getUserLoginDto(authorization); + if (null == userLoginDto) { + return Result.unauthorized(null); + } + String userId = userLoginDto.getUserId(); + UserInfo userInfo = userInfoService.findById(userId); + userInfo.setEnablePush(flag); + userInfoService.update(userInfo); + return Result.success(); + } + + private Integer getIndex(UserInfo u) { + return Integer.valueOf(Arrays.stream(u.getBadges().split(",")).filter(s -> s.startsWith(String.valueOf(UserBadgeEnum.CONTRIBUTOR.getCode()))).findFirst().get().split("_")[1]); + } + + @ApiOperation(value = "15.1 提交实名认证") + @PostMapping("/approve/real/name") + public Result approveRealName(@RequestHeader(value = "Authorization", required = true) String authorization, + @Validated @RequestBody UserRealNameFormDto userRealNameFormDto) { + userInfoService.approveRealName(authorization, userRealNameFormDto); + return Result.success(); + } + + @ApiOperation(value = "15.2 审核实名认证") + @PostMapping("/check/real/name") + public Result checkRealName(@RequestHeader(value = "Authorization", required = true) String authorization, + @Validated @RequestBody UserRealNameCheckDto userRealNameCheckDto) { + userInfoService.checkRealName(authorization, userRealNameCheckDto); + return Result.success(); + } + + @ApiOperation(value = "15.3 审核实名解绑") + @PostMapping("/unbind/real/name/{id}") + public Result realNameCheck(@RequestHeader(value = "Authorization", required = true) String authorization, + @PathVariable String id) { + userInfoService.unBindRealName(authorization, id); + return Result.success(); + } + + } diff --git a/luoo_user/src/main/java/com/luoo/user/dao/UserRealNameDao.java b/luoo_user/src/main/java/com/luoo/user/dao/UserRealNameDao.java new file mode 100644 index 0000000..82b9a69 --- /dev/null +++ b/luoo_user/src/main/java/com/luoo/user/dao/UserRealNameDao.java @@ -0,0 +1,22 @@ +package com.luoo.user.dao; + +import com.luoo.user.pojo.UserRealName; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.JpaSpecificationExecutor; +import org.springframework.data.jpa.repository.Query; + +import java.util.List; + +/** + * @Author: yawei.huang + * @Package: com.luoo.user.dao + * @Project: luoo_parent + * @Date: 2024/5/6 15:37 + * @Filename: UserRealNameDao + * @Describe: + */ +public interface UserRealNameDao extends JpaRepository, JpaSpecificationExecutor { + + @Query(value = "select * from indie_user.tb_user_real_name where user_id = ? and (state = 1 or state = 2)",nativeQuery = true) + public List checkExist(String userId); +} diff --git a/luoo_user/src/main/java/com/luoo/user/dto/UserRealNameCheckDto.java b/luoo_user/src/main/java/com/luoo/user/dto/UserRealNameCheckDto.java new file mode 100644 index 0000000..f1f205c --- /dev/null +++ b/luoo_user/src/main/java/com/luoo/user/dto/UserRealNameCheckDto.java @@ -0,0 +1,31 @@ +package com.luoo.user.dto; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; +import java.io.Serializable; + +/** + * @Author: yawei.huang + * @Package: com.luoo.user.dto + * @Project: luoo_parent + * @Date: 2024/5/6 15:54 + * @Filename: UserRealNameCheckDto + * @Describe: 实名认证审核对象 + */ +@Data +public class UserRealNameCheckDto implements Serializable { + + @ApiModelProperty("实名认证id") + @NotBlank(message = "id不能为空") + private String id; + + @ApiModelProperty("审核结果") + @NotNull(message = "审核结果不能为空") + private Integer state; + + @ApiModelProperty("拒绝理由") + private String content; +} diff --git a/luoo_user/src/main/java/com/luoo/user/dto/UserRealNameFormDto.java b/luoo_user/src/main/java/com/luoo/user/dto/UserRealNameFormDto.java new file mode 100644 index 0000000..05a7167 --- /dev/null +++ b/luoo_user/src/main/java/com/luoo/user/dto/UserRealNameFormDto.java @@ -0,0 +1,48 @@ +package com.luoo.user.dto; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import javax.validation.constraints.NotBlank; +import java.io.Serializable; + +/** + * @Author: yawei.huang + * @Package: com.luoo.user.dto + * @Project: luoo_parent + * @Date: 2024/5/6 15:30 + * @Filename: UserRealNameAddDto + * @Describe: 实名认证对象 + */ +@Data +public class UserRealNameFormDto implements Serializable { + + /** + * 真名 + */ + @ApiModelProperty("真名") + @NotBlank(message = "姓名不能为空") + private String realName; + + /** + * 身份证号 + */ + @ApiModelProperty("身份证号") + @NotBlank(message = "身份证号不能为空") + private String idCard; + + /** + * 身份证正面url + */ + @ApiModelProperty("身份证正面url") + @NotBlank(message = "请上传身份证正面") + private String frontUrl; + + /** + * 身份证反面url + */ + @ApiModelProperty("身份证反面url") + @NotBlank(message = "请上传身份证反面") + private String backUrl; + +} diff --git a/luoo_user/src/main/java/com/luoo/user/pojo/UserRealName.java b/luoo_user/src/main/java/com/luoo/user/pojo/UserRealName.java new file mode 100644 index 0000000..c6cb639 --- /dev/null +++ b/luoo_user/src/main/java/com/luoo/user/pojo/UserRealName.java @@ -0,0 +1,95 @@ +package com.luoo.user.pojo; + +import com.fasterxml.jackson.annotation.JsonFormat; +import io.swagger.annotations.ApiModelProperty; +import lombok.*; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.annotation.LastModifiedDate; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import java.io.Serializable; +import java.time.LocalDateTime; + +/** + * 实名认证表单 + * + * @TableName tb_user_real_name + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +@EqualsAndHashCode +@Builder +@Entity +@Table(name = "tb_user_real_name") +public class UserRealName implements Serializable { + + /** + * id + */ + @Id + @ApiModelProperty("id") + private String id; + /** + * user_info表id + */ + @ApiModelProperty("user_info表id") + private String userId; + /** + * 真名 + */ + @ApiModelProperty("真名") + private String realName; + /** + * 身份证号 + */ + @ApiModelProperty("身份证号") + private String idCard; + /** + * 身份证正面url + */ + @ApiModelProperty("身份证正面url") + private String frontUrl; + /** + * 身份证反面url + */ + @ApiModelProperty("身份证反面url") + private String backUrl; + /** + * 实名认证状态 1-审核中 2-审核通过 3-审核失败 -1解绑 + */ + @ApiModelProperty("实名认证状态 1-审核中 2-审核通过 3-审核失败 -1解绑") + private Integer state; + /** + * 拒绝理由 + */ + @ApiModelProperty("拒绝理由") + private String content; + /** + * 创建时间 + */ + @ApiModelProperty("创建时间") + @CreatedDate + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") + private LocalDateTime createTime; + /** + * 修改时间 + */ + @ApiModelProperty("修改时间") + @LastModifiedDate + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") + private LocalDateTime updateTime; + /** + * 创建人 + */ + @ApiModelProperty("创建人") + private String createUser; + /** + * 修改人 + */ + @ApiModelProperty("修改人") + private String updateUser; + +} diff --git a/luoo_user/src/main/java/com/luoo/user/service/UserInfoService.java b/luoo_user/src/main/java/com/luoo/user/service/UserInfoService.java index b8b6de5..a3321c4 100644 --- a/luoo_user/src/main/java/com/luoo/user/service/UserInfoService.java +++ b/luoo_user/src/main/java/com/luoo/user/service/UserInfoService.java @@ -1,21 +1,26 @@ package com.luoo.user.service; -import java.util.*; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; - -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Predicate; -import javax.persistence.criteria.Root; -import javax.servlet.http.HttpServletRequest; - -import api.Result; -import api.StatusCode; +import client.vo.SimpleUser; +import com.luoo.user.dao.UserInfoDao; +import com.luoo.user.dao.UserRealNameDao; +import com.luoo.user.dto.UserQueryReq; +import com.luoo.user.dto.UserRealNameCheckDto; +import com.luoo.user.dto.UserRealNameFormDto; +import com.luoo.user.pojo.UserInfo; +import com.luoo.user.pojo.UserRealName; +import com.luoo.user.util.NickNameUtil; import com.luoo.user.util.NickNameUtil2; +import constants.Constants; +import constants.ErrorConstants; +import dto.UserLoginDto; +import enums.UserRealNameStateEnum; +import enums.UserStatusEnum; +import exception.BizException; +import org.apache.commons.lang.ObjectUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang3.RandomStringUtils; import org.springframework.amqp.rabbit.core.RabbitTemplate; +import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; @@ -23,238 +28,234 @@ import org.springframework.data.jpa.domain.Specification; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; - import org.springframework.transaction.annotation.Transactional; import util.IdWorker; - -import constants.Constants; - -import com.luoo.user.dao.UserInfoDao; -import com.luoo.user.dto.UserQueryReq; -import com.luoo.user.pojo.UserInfo; -import com.luoo.user.util.NickNameUtil; - -import client.vo.SimpleUser; -import dto.UserLoginDto; -import enums.UserStatusEnum; import util.JwtUtil; +import javax.persistence.criteria.Predicate; +import javax.servlet.http.HttpServletRequest; +import java.util.*; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; + /** * 服务层 - * - * @author Administrator * + * @author Administrator */ @Service public class UserInfoService { - @Autowired - private UserInfoDao userInfoDao; - @Autowired - private IdWorker idWorker; - - @Autowired - private RedisTemplate redisTemplate; - - @Autowired - private RabbitTemplate rabbitTemplate; - - @Autowired - private BCryptPasswordEncoder encoder; - - @Autowired - private HttpServletRequest request; - - @Autowired - private JwtUtil jwtUtil; - - /** - * token解析示例 - */ - public void testParseToken() { - - String userInfoid = (String) request.getAttribute("userInfoid"); - String mobile = (String) request.getAttribute("mobile"); - System.out.println("用户ID" + userInfoid); - System.out.println("手机号" + mobile); - } - - /** - * 查询全部列表 - * - * @return - */ - public List findAll() { - return userInfoDao.findAll(); - } - - /** - * 根据ID查询实体 - * - * @param id - * @return - */ - public UserInfo findById(String id) { - return userInfoDao.getById(id); - } - - /** - * 修改 - * - * @param userInfo - */ - public void update(UserInfo userInfo) { - userInfoDao.save(userInfo); - } - - /** - * 删除 - * - * @param id - */ - public void deleteById(String id) { - - String token = (String) request.getAttribute("claims_admin"); - if (token == null || "".equals(token)) { - throw new RuntimeException("权限不足"); - } - userInfoDao.deleteById(id); - } - - public void sendSms(String deviceId, String mobile) { - // 生成6位数字随机数 - String checkcode = RandomStringUtils.randomNumeric(6); - // 向缓存中放一份 - String redisKey = Constants.REDIS_KEY_MOBILE_CHECK_CODE + deviceId; - redisTemplate.opsForValue().set(redisKey, checkcode, 15, TimeUnit.MINUTES); - - // 向用户发一份 - Map map = new HashMap<>(); - map.put("mobile", mobile); - map.put("checkcode", checkcode); - rabbitTemplate.convertAndSend("sms", map); - - // 在控制台放一份(方便测试) - - System.out.println("验证码是:" + checkcode); - } - - public UserInfo login(String mobile, String password) { + @Autowired + private UserInfoDao userInfoDao; + @Autowired + private IdWorker idWorker; + + @Autowired + private RedisTemplate redisTemplate; + + @Autowired + private RabbitTemplate rabbitTemplate; + + @Autowired + private BCryptPasswordEncoder encoder; + + @Autowired + private HttpServletRequest request; + + @Autowired + private JwtUtil jwtUtil; + + @Autowired + private UserRealNameDao userRealNameDao; + + /** + * token解析示例 + */ + public void testParseToken() { + + String userInfoid = (String) request.getAttribute("userInfoid"); + String mobile = (String) request.getAttribute("mobile"); + System.out.println("用户ID" + userInfoid); + System.out.println("手机号" + mobile); + } + + /** + * 查询全部列表 + * + * @return + */ + public List findAll() { + return userInfoDao.findAll(); + } + + /** + * 根据ID查询实体 + * + * @param id + * @return + */ + public UserInfo findById(String id) { + return userInfoDao.getById(id); + } + + /** + * 修改 + * + * @param userInfo + */ + public void update(UserInfo userInfo) { + userInfoDao.save(userInfo); + } + + /** + * 删除 + * + * @param id + */ + public void deleteById(String id) { + + String token = (String) request.getAttribute("claims_admin"); + if (token == null || "".equals(token)) { + throw new RuntimeException("权限不足"); + } + userInfoDao.deleteById(id); + } + + public void sendSms(String deviceId, String mobile) { + // 生成6位数字随机数 + String checkcode = RandomStringUtils.randomNumeric(6); + // 向缓存中放一份 + String redisKey = Constants.REDIS_KEY_MOBILE_CHECK_CODE + deviceId; + redisTemplate.opsForValue().set(redisKey, checkcode, 15, TimeUnit.MINUTES); + + // 向用户发一份 + Map map = new HashMap<>(); + map.put("mobile", mobile); + map.put("checkcode", checkcode); + rabbitTemplate.convertAndSend("sms", map); + + // 在控制台放一份(方便测试) + + System.out.println("验证码是:" + checkcode); + } + + public UserInfo login(String mobile, String password) { // UserInfo userInfo = userInfoDao.findByLoginname(loginname); - UserInfo userInfo = userInfoDao.findByMobile(mobile); - if (userInfo != null && encoder.matches(password, userInfo.getPassword())) { - return userInfo; - } - return null; - } - - @Transactional - public void updatefanscountandfollowcount(int x, String userInfoid, String friendid) { - userInfoDao.updatefanscount(x, friendid); - userInfoDao.updatefollowcount(x, userInfoid); - } - - public UserInfo loginOrRegister(String mobile) { - UserInfo userInfo = userInfoDao.findByMobile(mobile); - if (null == userInfo) { - userInfo = new UserInfo(); - userInfo.setJoinTime(new Date()); - userInfo.setId(String.valueOf(idWorker.nextId())); - userInfo.setMobile(mobile); - userInfo.setNickName("雀乐-" + NickNameUtil.getRandomNickName()); - userInfoDao.save(userInfo); - } else { - userInfo.setLastLoginTime(new Date()); - userInfoDao.save(userInfo); - } - return userInfo; - } - - public UserInfo findByMobile(String mobile) { - UserInfo userInfo = userInfoDao.findByMobile(mobile); - return userInfo; - } - - public String autoLogin(String authorization, String deviceId, String deviceBrand, String ip) { - UserLoginDto userLoginDto = jwtUtil.getUserLoginDto(authorization); - if (null == userLoginDto) { - return null; - } - UserInfo userInfo = userInfoDao.findById(userLoginDto.getUserId()).get(); - if (!UserStatusEnum.ENABLE.getStatus().equals(userInfo.getStatus())) { - return null; - } - userInfo.setLastLoginTime(new Date()); - userInfo.setLastLoginIp(ip); - userInfo.setLastUseDeviceId(deviceId); - userInfo.setLastUseDeviceBrand(deviceBrand); - userInfoDao.save(userInfo); - return Constants.TOKEN_PREFIX + jwtUtil.createJWT(userLoginDto.getUserId(), userInfo.getNickName(), - userLoginDto.getRoles(), userLoginDto.getAvatar()); - } - - public long countByNickName(String nickName) { - return userInfoDao.countByNickName(nickName); - } - - public String loginOrRegister(UserInfo loginUserInfo) { - UserInfo userInfo = userInfoDao.findByMobile(loginUserInfo.getMobile()); - if (null == userInfo) { - userInfo = loginUserInfo; - userInfo.setId(String.valueOf(idWorker.nextId())); + UserInfo userInfo = userInfoDao.findByMobile(mobile); + if (userInfo != null && encoder.matches(password, userInfo.getPassword())) { + return userInfo; + } + return null; + } + + @Transactional + public void updatefanscountandfollowcount(int x, String userInfoid, String friendid) { + userInfoDao.updatefanscount(x, friendid); + userInfoDao.updatefollowcount(x, userInfoid); + } + + public UserInfo loginOrRegister(String mobile) { + UserInfo userInfo = userInfoDao.findByMobile(mobile); + if (null == userInfo) { + userInfo = new UserInfo(); + userInfo.setJoinTime(new Date()); + userInfo.setId(String.valueOf(idWorker.nextId())); + userInfo.setMobile(mobile); + userInfo.setNickName("雀乐-" + NickNameUtil.getRandomNickName()); + userInfoDao.save(userInfo); + } else { + userInfo.setLastLoginTime(new Date()); + userInfoDao.save(userInfo); + } + return userInfo; + } + + public UserInfo findByMobile(String mobile) { + UserInfo userInfo = userInfoDao.findByMobile(mobile); + return userInfo; + } + + public String autoLogin(String authorization, String deviceId, String deviceBrand, String ip) { + UserLoginDto userLoginDto = jwtUtil.getUserLoginDto(authorization); + if (null == userLoginDto) { + return null; + } + UserInfo userInfo = userInfoDao.findById(userLoginDto.getUserId()).get(); + if (!UserStatusEnum.ENABLE.getStatus().equals(userInfo.getStatus())) { + return null; + } + userInfo.setLastLoginTime(new Date()); + userInfo.setLastLoginIp(ip); + userInfo.setLastUseDeviceId(deviceId); + userInfo.setLastUseDeviceBrand(deviceBrand); + userInfoDao.save(userInfo); + return Constants.TOKEN_PREFIX + jwtUtil.createJWT(userLoginDto.getUserId(), userInfo.getNickName(), + userLoginDto.getRoles(), userLoginDto.getAvatar()); + } + + public long countByNickName(String nickName) { + return userInfoDao.countByNickName(nickName); + } + + public String loginOrRegister(UserInfo loginUserInfo) { + UserInfo userInfo = userInfoDao.findByMobile(loginUserInfo.getMobile()); + if (null == userInfo) { + userInfo = loginUserInfo; + userInfo.setId(String.valueOf(idWorker.nextId())); // userInfo.setNickName("雀乐-" + NickNameUtil.getRandomNickName()); - userInfo.setNickName(NickNameUtil2.generateRandomString()); - Date curDate = new Date(); - userInfo.setJoinTime(curDate); - userInfo.setLastLoginTime(curDate); - userInfo.setStatus(UserStatusEnum.ENABLE.getStatus()); - userInfo.setAvatar(Constants.DEFAULT_USER_AVATAR); - userInfo.setThumbnail(Constants.DEFAULT_USER_THUMBNAIL); - userInfo.setSignature(Constants.DEFAULT_USER_SIGNATURE); - - } else { + userInfo.setNickName(NickNameUtil2.generateRandomString()); + Date curDate = new Date(); + userInfo.setJoinTime(curDate); + userInfo.setLastLoginTime(curDate); + userInfo.setStatus(UserStatusEnum.ENABLE.getStatus()); + userInfo.setAvatar(Constants.DEFAULT_USER_AVATAR); + userInfo.setThumbnail(Constants.DEFAULT_USER_THUMBNAIL); + userInfo.setSignature(Constants.DEFAULT_USER_SIGNATURE); + + } else { // userInfo.setAppleId(loginUserInfo.getAppleId()); - userInfo.setLastUseDeviceId(loginUserInfo.getLastUseDeviceId()); - userInfo.setLastUseDeviceBrand(loginUserInfo.getLastUseDeviceBrand()); - userInfo.setLastLoginIp(loginUserInfo.getLastLoginIp()); - } - if (!UserStatusEnum.ENABLE.getStatus().equals(userInfo.getStatus())) { - return null; - } - userInfo.setLastLoginTime(new Date()); - userInfoDao.save(userInfo); - return Constants.TOKEN_PREFIX - + jwtUtil.createJWT(userInfo.getId(), userInfo.getNickName(), Constants.TOKEN_ROLE_APP_USER, userInfo.getAvatar()); - } - - - public String appleLoginOrRegister(UserInfo loginUserInfo) { - UserInfo userInfo = userInfoDao.findByAppleId(loginUserInfo.getAppleId()); - if (null == userInfo) { + userInfo.setLastUseDeviceId(loginUserInfo.getLastUseDeviceId()); + userInfo.setLastUseDeviceBrand(loginUserInfo.getLastUseDeviceBrand()); + userInfo.setLastLoginIp(loginUserInfo.getLastLoginIp()); + } + if (!UserStatusEnum.ENABLE.getStatus().equals(userInfo.getStatus())) { + return null; + } + userInfo.setLastLoginTime(new Date()); + userInfoDao.save(userInfo); + return Constants.TOKEN_PREFIX + + jwtUtil.createJWT(userInfo.getId(), userInfo.getNickName(), Constants.TOKEN_ROLE_APP_USER, userInfo.getAvatar()); + } + + + public String appleLoginOrRegister(UserInfo loginUserInfo) { + UserInfo userInfo = userInfoDao.findByAppleId(loginUserInfo.getAppleId()); + if (null == userInfo) { // return "未注册"; - userInfo = loginUserInfo; - userInfo.setId(String.valueOf(idWorker.nextId())); - userInfo.setNickName(NickNameUtil2.generateRandomString()); + userInfo = loginUserInfo; + userInfo.setId(String.valueOf(idWorker.nextId())); + userInfo.setNickName(NickNameUtil2.generateRandomString()); // userInfo.setNickName("雀乐-" + NickNameUtil.getRandomNickName()); - Date curDate = new Date(); - userInfo.setJoinTime(curDate); - userInfo.setLastLoginTime(curDate); - userInfo.setStatus(UserStatusEnum.ENABLE.getStatus()); - userInfo.setAvatar(Constants.DEFAULT_USER_AVATAR); - userInfo.setThumbnail(Constants.DEFAULT_USER_THUMBNAIL); - userInfo.setSignature(Constants.DEFAULT_USER_SIGNATURE); - } else { - userInfo.setLastUseDeviceId(loginUserInfo.getLastUseDeviceId()); - userInfo.setLastUseDeviceBrand(loginUserInfo.getLastUseDeviceBrand()); - userInfo.setLastLoginIp(loginUserInfo.getLastLoginIp()); - } - if (!UserStatusEnum.ENABLE.getStatus().equals(userInfo.getStatus())) { - return null; - } - userInfo.setLastLoginTime(new Date()); - userInfoDao.save(userInfo); - return Constants.TOKEN_PREFIX - + jwtUtil.createJWT(userInfo.getId(), userInfo.getNickName(), Constants.TOKEN_ROLE_APP_USER, userInfo.getAvatar()); - } + Date curDate = new Date(); + userInfo.setJoinTime(curDate); + userInfo.setLastLoginTime(curDate); + userInfo.setStatus(UserStatusEnum.ENABLE.getStatus()); + userInfo.setAvatar(Constants.DEFAULT_USER_AVATAR); + userInfo.setThumbnail(Constants.DEFAULT_USER_THUMBNAIL); + userInfo.setSignature(Constants.DEFAULT_USER_SIGNATURE); + } else { + userInfo.setLastUseDeviceId(loginUserInfo.getLastUseDeviceId()); + userInfo.setLastUseDeviceBrand(loginUserInfo.getLastUseDeviceBrand()); + userInfo.setLastLoginIp(loginUserInfo.getLastLoginIp()); + } + if (!UserStatusEnum.ENABLE.getStatus().equals(userInfo.getStatus())) { + return null; + } + userInfo.setLastLoginTime(new Date()); + userInfoDao.save(userInfo); + return Constants.TOKEN_PREFIX + + jwtUtil.createJWT(userInfo.getId(), userInfo.getNickName(), Constants.TOKEN_ROLE_APP_USER, userInfo.getAvatar()); + } // // public String wechatloginOrRegister(UserInfo loginUserInfo) { @@ -286,146 +287,239 @@ public class UserInfoService { // } - public String wechatlogin(UserInfo loginUserInfo) { + public String wechatlogin(UserInfo loginUserInfo) { - if (!UserStatusEnum.ENABLE.getStatus().equals(loginUserInfo.getStatus())) { - return null; - } - loginUserInfo.setLastLoginTime(new Date()); - userInfoDao.save(loginUserInfo); - return Constants.TOKEN_PREFIX - + jwtUtil.createJWT(loginUserInfo.getId(), loginUserInfo.getNickName(), Constants.TOKEN_ROLE_APP_USER, loginUserInfo.getAvatar()); - } + if (!UserStatusEnum.ENABLE.getStatus().equals(loginUserInfo.getStatus())) { + return null; + } + loginUserInfo.setLastLoginTime(new Date()); + userInfoDao.save(loginUserInfo); + return Constants.TOKEN_PREFIX + + jwtUtil.createJWT(loginUserInfo.getId(), loginUserInfo.getNickName(), Constants.TOKEN_ROLE_APP_USER, loginUserInfo.getAvatar()); + } - public String wechatRegister(UserInfo loginUserInfo) { - UserInfo userInfo = userInfoDao.findByMobile(loginUserInfo.getMobile()); - if (null == userInfo) { - userInfo = loginUserInfo; - userInfo.setId(String.valueOf(idWorker.nextId())); - userInfo.setNickName(NickNameUtil2.generateRandomString()); + public String wechatRegister(UserInfo loginUserInfo) { + UserInfo userInfo = userInfoDao.findByMobile(loginUserInfo.getMobile()); + if (null == userInfo) { + userInfo = loginUserInfo; + userInfo.setId(String.valueOf(idWorker.nextId())); + userInfo.setNickName(NickNameUtil2.generateRandomString()); // userInfo.setNickName("雀乐-" + NickNameUtil.getRandomNickName()); - Date curDate = new Date(); - userInfo.setJoinTime(curDate); - userInfo.setLastLoginTime(curDate); - userInfo.setStatus(UserStatusEnum.ENABLE.getStatus()); - userInfo.setAvatar(Constants.DEFAULT_USER_AVATAR); - userInfo.setThumbnail(Constants.DEFAULT_USER_THUMBNAIL); - userInfo.setSignature(Constants.DEFAULT_USER_SIGNATURE); - } else { - userInfo.setLastUseDeviceId(loginUserInfo.getLastUseDeviceId()); - userInfo.setLastUseDeviceBrand(loginUserInfo.getLastUseDeviceBrand()); - userInfo.setLastLoginIp(loginUserInfo.getLastLoginIp()); - } - - userInfo.setWxId(loginUserInfo.getWxId()); - if (!UserStatusEnum.ENABLE.getStatus().equals(userInfo.getStatus())) { - return null; - } - userInfo.setLastLoginTime(new Date()); - userInfoDao.save(userInfo); - return Constants.TOKEN_PREFIX - + jwtUtil.createJWT(userInfo.getId(), userInfo.getNickName(), Constants.TOKEN_ROLE_APP_USER, userInfo.getAvatar()); - } - - - public List orderByField(List idList) { - return userInfoDao.orderByField(idList); - } - - public List cmsOrderByField(List idList) { - return orderByField(idList).stream().map(this::updateAvatarPath).collect(Collectors.toList()); - } - - public List getSimpleUserOrderByField(List idList) { - return userInfoDao.getSimpleUserOrderByField(idList); - } - - public Page findSearch(UserQueryReq queryReq) { - Specification specification = createUserInfoSpecification(queryReq); - PageRequest pageRequest = PageRequest.of(queryReq.getPageNum() - 1, queryReq.getPageSize()); - Page userInfoPage = userInfoDao.findAll(specification, pageRequest); - return userInfoPage.map(this::updateAvatarPath); - } - - private UserInfo updateAvatarPath(UserInfo userInfo) { - if (null != userInfo && null != userInfo.getAvatar()) { - userInfo.setAvatar(Constants.RESOURCE_PREFIX + userInfo.getAvatar()); - } - return userInfo; - } - - public Page findSearch(UserQueryReq queryReq, int page, int size) { - Specification specification = createUserInfoSpecification(queryReq); - PageRequest pageRequest = PageRequest.of(page - 1, size); - return userInfoDao.findAll(specification, pageRequest); - } - - private Specification createUserInfoSpecification(UserQueryReq queryReq) { - return (root, criteriaQuery, criteriaBuilder) -> { - List predicateList = new ArrayList<>(); - if (StringUtils.isNotBlank(queryReq.getId())) { - predicateList.add(criteriaBuilder.equal(root.get("id"), queryReq.getId())); - } - if (StringUtils.isNotBlank(queryReq.getMobile())) { - predicateList.add(criteriaBuilder.equal(root.get("mobile").as(String.class), queryReq.getMobile())); - } - if (StringUtils.isNotBlank(queryReq.getNickName())) { - predicateList.add(criteriaBuilder.like(root.get("nickName"), '%' + queryReq.getNickName() + '%')); - } - if (StringUtils.isNotBlank(queryReq.getBadge())) { - predicateList.add(criteriaBuilder.equal(root.get("badge").as(String.class), queryReq.getBadge())); - } - if (Objects.nonNull(queryReq.getStatus())) { - predicateList.add(criteriaBuilder.equal(root.get("status").as(Integer.class), queryReq.getStatus())); - } - /* - * if(Objects.nonNull(queryReq.getOnlineStatus())){ - * predicateList.add(criteriaBuilder.equal(root.get("onlineStatus").as(Integer. - * class), queryReq.getOnlineStatus())); } - */ - - if (Objects.nonNull(queryReq.getCreateDateStart())) { - predicateList.add(criteriaBuilder.greaterThanOrEqualTo(root.get("joinTime").as(Date.class), - queryReq.getCreateDateStart())); - } - if (Objects.nonNull(queryReq.getCreateDateEnd())) { - predicateList.add(criteriaBuilder.lessThanOrEqualTo(root.get("joinTime").as(Date.class), - queryReq.getCreateDateEnd())); - } - Predicate[] predicates = new Predicate[predicateList.size()]; - criteriaQuery.orderBy(criteriaBuilder.desc(root.get("joinTime").as(Date.class))); - return criteriaBuilder.and(predicateList.toArray(predicates)); - }; - } - - public UserInfo cmsFindById(String id) { - return updateAvatarPath(userInfoDao.getById(id)); - } - - public List getThanks() { - return userInfoDao.getThanks(); - } - - - public void bindMobile(UserInfo userInfo){ - userInfoDao.save(userInfo); - } - - /** - * 校验用户名密码是否匹配 - * - * @param userName 用户名 - * @param password 密码 - * @return 成功返回该用户,失败返回null - */ - public UserInfo findByUserNameAndPassword(String userName, String password) { - UserInfo userInfoByUserName = userInfoDao.findUserInfoByUserName(userName); - if(userInfoByUserName != null && encoder.matches(password, userInfoByUserName.getPassword())) { - return userInfoByUserName; - } else { - return null; - } - } + Date curDate = new Date(); + userInfo.setJoinTime(curDate); + userInfo.setLastLoginTime(curDate); + userInfo.setStatus(UserStatusEnum.ENABLE.getStatus()); + userInfo.setAvatar(Constants.DEFAULT_USER_AVATAR); + userInfo.setThumbnail(Constants.DEFAULT_USER_THUMBNAIL); + userInfo.setSignature(Constants.DEFAULT_USER_SIGNATURE); + } else { + userInfo.setLastUseDeviceId(loginUserInfo.getLastUseDeviceId()); + userInfo.setLastUseDeviceBrand(loginUserInfo.getLastUseDeviceBrand()); + userInfo.setLastLoginIp(loginUserInfo.getLastLoginIp()); + } + + userInfo.setWxId(loginUserInfo.getWxId()); + if (!UserStatusEnum.ENABLE.getStatus().equals(userInfo.getStatus())) { + return null; + } + userInfo.setLastLoginTime(new Date()); + userInfoDao.save(userInfo); + return Constants.TOKEN_PREFIX + + jwtUtil.createJWT(userInfo.getId(), userInfo.getNickName(), Constants.TOKEN_ROLE_APP_USER, userInfo.getAvatar()); + } + + + public List orderByField(List idList) { + return userInfoDao.orderByField(idList); + } + + public List cmsOrderByField(List idList) { + return orderByField(idList).stream().map(this::updateAvatarPath).collect(Collectors.toList()); + } + + public List getSimpleUserOrderByField(List idList) { + return userInfoDao.getSimpleUserOrderByField(idList); + } + + public Page findSearch(UserQueryReq queryReq) { + Specification specification = createUserInfoSpecification(queryReq); + PageRequest pageRequest = PageRequest.of(queryReq.getPageNum() - 1, queryReq.getPageSize()); + Page userInfoPage = userInfoDao.findAll(specification, pageRequest); + return userInfoPage.map(this::updateAvatarPath); + } + + private UserInfo updateAvatarPath(UserInfo userInfo) { + if (null != userInfo && null != userInfo.getAvatar()) { + userInfo.setAvatar(Constants.RESOURCE_PREFIX + userInfo.getAvatar()); + } + return userInfo; + } + + public Page findSearch(UserQueryReq queryReq, int page, int size) { + Specification specification = createUserInfoSpecification(queryReq); + PageRequest pageRequest = PageRequest.of(page - 1, size); + return userInfoDao.findAll(specification, pageRequest); + } + + private Specification createUserInfoSpecification(UserQueryReq queryReq) { + return (root, criteriaQuery, criteriaBuilder) -> { + List predicateList = new ArrayList<>(); + if (StringUtils.isNotBlank(queryReq.getId())) { + predicateList.add(criteriaBuilder.equal(root.get("id"), queryReq.getId())); + } + if (StringUtils.isNotBlank(queryReq.getMobile())) { + predicateList.add(criteriaBuilder.equal(root.get("mobile").as(String.class), queryReq.getMobile())); + } + if (StringUtils.isNotBlank(queryReq.getNickName())) { + predicateList.add(criteriaBuilder.like(root.get("nickName"), '%' + queryReq.getNickName() + '%')); + } + if (StringUtils.isNotBlank(queryReq.getBadge())) { + predicateList.add(criteriaBuilder.equal(root.get("badge").as(String.class), queryReq.getBadge())); + } + if (Objects.nonNull(queryReq.getStatus())) { + predicateList.add(criteriaBuilder.equal(root.get("status").as(Integer.class), queryReq.getStatus())); + } + /* + * if(Objects.nonNull(queryReq.getOnlineStatus())){ + * predicateList.add(criteriaBuilder.equal(root.get("onlineStatus").as(Integer. + * class), queryReq.getOnlineStatus())); } + */ + + if (Objects.nonNull(queryReq.getCreateDateStart())) { + predicateList.add(criteriaBuilder.greaterThanOrEqualTo(root.get("joinTime").as(Date.class), + queryReq.getCreateDateStart())); + } + if (Objects.nonNull(queryReq.getCreateDateEnd())) { + predicateList.add(criteriaBuilder.lessThanOrEqualTo(root.get("joinTime").as(Date.class), + queryReq.getCreateDateEnd())); + } + Predicate[] predicates = new Predicate[predicateList.size()]; + criteriaQuery.orderBy(criteriaBuilder.desc(root.get("joinTime").as(Date.class))); + return criteriaBuilder.and(predicateList.toArray(predicates)); + }; + } + + public UserInfo cmsFindById(String id) { + return updateAvatarPath(userInfoDao.getById(id)); + } + + public List getThanks() { + return userInfoDao.getThanks(); + } + + + public void bindMobile(UserInfo userInfo) { + userInfoDao.save(userInfo); + } + + /** + * 校验用户名密码是否匹配 + * + * @param userName 用户名 + * @param password 密码 + * @return 成功返回该用户,失败返回null + */ + public UserInfo findByUserNameAndPassword(String userName, String password) { + UserInfo userInfoByUserName = userInfoDao.findUserInfoByUserName(userName); + if (userInfoByUserName != null && encoder.matches(password, userInfoByUserName.getPassword())) { + return userInfoByUserName; + } else { + return null; + } + } + + /** + * 提交实名认证 + * + * @param token token + * @param userRealNameFormDto 实名认证对象 + */ + @Transactional(rollbackFor = Exception.class) + public void approveRealName(String token, UserRealNameFormDto userRealNameFormDto) { + UserRealName userRealName = new UserRealName(); + BeanUtils.copyProperties(userRealNameFormDto, userRealName); + UserLoginDto user = jwtUtil.getUserLoginDto(token); + if (user != null) { + userRealName.setCreateUser(user.getUserId()); + } else { + // 用户校验失败,请重新登录 + throw new BizException(ErrorConstants.USER_VERIFICATION_FAILURE); + } + userRealName.setState(UserRealNameStateEnum.CREATE.getCode()); + + // 校验是否允许 + List userRealNames = userRealNameDao.checkExist(user.getUserId()); + if (!userRealNames.isEmpty()) { + // 该用户实名认证已存在 + throw new BizException(ErrorConstants.REAL_NAME_APPROVE_IS_EXISTS); + } + + userRealNameDao.save(userRealName); + } + + /** + * 审核实名认证 + * + * @param token token + * @param userRealNameCheckDto 审核对象 + */ + @Transactional(rollbackFor = Exception.class) + public void checkRealName(String token, UserRealNameCheckDto userRealNameCheckDto) { + + UserRealName userRealName = userRealNameDao.findById(userRealNameCheckDto.getId()).get(); + if (userRealName == null) { + // 实名认证错误 + throw new BizException(ErrorConstants.REAL_NAME_ERROR); + } + + if (ObjectUtils.notEqual(UserRealNameStateEnum.CREATE.getCode(), userRealName.getState())) { + // 该用户实名认证已审核完成 + throw new BizException(ErrorConstants.REAL_NAME_IS_CHECKED); + } + + if (ObjectUtils.equals(UserRealNameStateEnum.FAIL.getCode(), userRealNameCheckDto.getState()) + && StringUtils.isBlank(userRealNameCheckDto.getContent())) { + // 必须填写拒绝理由 + throw new BizException(ErrorConstants.REASONS_FOR_REFUSAL_MUST_BE_GIVEN); + } + + UserLoginDto user = jwtUtil.getUserLoginDto(token); + if (user != null) { + userRealName.setCreateUser(user.getUserId()); + } else { + // 用户校验失败,请重新登录 + throw new BizException(ErrorConstants.USER_VERIFICATION_FAILURE); + } + + userRealName.setContent(userRealNameCheckDto.getContent()); + userRealName.setState(userRealNameCheckDto.getState()); + userRealName.setUpdateUser(user.getUserId()); + userRealNameDao.save(userRealName); + } + + /** + * 解绑实名认证 + * + * @param token token + * @param id 实名认证id + */ + public void unBindRealName(String token, String id) { + UserRealName userRealName = userRealNameDao.findById(id).get(); + UserLoginDto user = jwtUtil.getUserLoginDto(token); + if (user != null) { + if (ObjectUtils.notEqual(user.getUserId(), userRealName.getCreateUser())) { + // 必须本人操作 + throw new BizException(ErrorConstants.MUST_OPERATE_IN_PERSON); + } + } else { + // 用户校验失败,请重新登录 + throw new BizException(ErrorConstants.USER_VERIFICATION_FAILURE); + } + + userRealName.setState(UserRealNameStateEnum.UNBIND.getCode()); + userRealName.setUpdateUser(user.getUserId()); + userRealNameDao.save(userRealName); + } } diff --git a/luoo_user/src/main/resources/sql/20240506.sql b/luoo_user/src/main/resources/sql/20240506.sql new file mode 100644 index 0000000..cd05ca9 --- /dev/null +++ b/luoo_user/src/main/resources/sql/20240506.sql @@ -0,0 +1,18 @@ +create table tb_user_real_name +( + id varchar(20) not null comment 'id' + primary key, + user_id varchar(20) not null comment 'user_info表id', + real_name varchar(255) not null comment '真名', + id_card varchar(255) null comment '身份证号', + front_url varchar(255) null comment '身份证正面url', + back_url varchar(255) null comment '身份证反面url', + state int null comment '实名认证状态 1-审核中 2-审核通过 3-审核失败 -1解绑', + content longtext null comment '拒绝理由', + create_time datetime null comment '创建时间', + update_time datetime null comment '修改时间', + create_user varchar(20) null comment '创建人', + update_user varchar(20) null comment '修改人' +) + comment '实名认证表单'; +