1.fix bug of getUserInfo for tourist;2.add update userinfo interface

main
Gary 1 year ago
parent e812995138
commit 0b0285b6ee

@ -16,6 +16,8 @@ public enum StatusCode implements IErrorCode {
USER_NAME_OR_PASSWORD_FAILED(10003, "用户名或密码错误"), USER_NAME_OR_PASSWORD_FAILED(10003, "用户名或密码错误"),
USER_IMAGE_VERIFICATION_CODE_EXPIRED(10004, "图形验证码过期,请重新获取"), USER_IMAGE_VERIFICATION_CODE_EXPIRED(10004, "图形验证码过期,请重新获取"),
USER_IMAGE_VERIFICATION_CODE_MISMATCH(10005, "图形验证码校验失败,请输入正确的验证码"), USER_IMAGE_VERIFICATION_CODE_MISMATCH(10005, "图形验证码校验失败,请输入正确的验证码"),
USER_NICK_NAME_HAS_BEEN_EXIST(10006, "昵称已经存在"),
// music 模块错误码以20XXX不足5位补0; // music 模块错误码以20XXX不足5位补0;
MUSIC_COMMON_FAILED(20000, "歌曲模块错误"), MUSIC_COMMON_FAILED(20000, "歌曲模块错误"),

@ -0,0 +1,16 @@
package enums;
public enum DateTimePatternEnum {
YYYY_MM_DD_HH_MM_SS("yyyy-MM-dd HH:mm:ss"), YYYY_MM_DD("yyyy-MM-dd"), YYYYMM("YYYYMM"),YYYY_DOT_MM_DOT_DD("yyyy.MM.dd");
private String pattern;
DateTimePatternEnum(String pattern) {
this.pattern = pattern;
}
public String getPattern() {
return pattern;
}
}

@ -0,0 +1,81 @@
package util;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import enums.DateTimePatternEnum;
public class DateUtil {
private static final Object lockObj = new Object();
private static Map<String, ThreadLocal<SimpleDateFormat>> sdfMap = new HashMap<String, ThreadLocal<SimpleDateFormat>>();
private static SimpleDateFormat getSdf(final String pattern) {
ThreadLocal<SimpleDateFormat> tl = sdfMap.get(pattern);
if (tl == null) {
synchronized (lockObj) {
tl = sdfMap.get(pattern);
if (tl == null) {
tl = new ThreadLocal<SimpleDateFormat>() {
@Override
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat(pattern);
}
};
sdfMap.put(pattern, tl);
}
}
}
return tl.get();
}
public static String format(Date date, String pattern) {
return getSdf(pattern).format(date);
}
public static Date parse(String dateStr, String pattern) {
try {
return getSdf(pattern).parse(dateStr);
} catch (ParseException e) {
e.printStackTrace();
}
return new Date();
}
public static LocalDate fromLocateDate2String(Date date) {
Instant instant = date.toInstant();
ZoneId zone = ZoneId.systemDefault();
LocalDate localDate = instant.atZone(zone).toLocalDate();
return localDate;
}
public static Date getDayAgo(Integer day) {
LocalDateTime localDateTime = LocalDateTime.now().minusDays(day);
ZoneId zone = ZoneId.systemDefault();
Instant instant = localDateTime.atZone(zone).toInstant();
return Date.from(instant);
}
public static List<String> getBetweenDate(Date startDate, Date endDate) {
LocalDate startLocalDate = fromLocateDate2String(startDate);
LocalDate endLocalDate = fromLocateDate2String(endDate);
long numOfDays = ChronoUnit.DAYS.between(startLocalDate, endLocalDate) + 1;
List<LocalDate> localDateList = Stream.iterate(startLocalDate, date -> date.plusDays(1)).limit(numOfDays).collect(Collectors.toList());
List<String> dateList = localDateList.stream().map(date -> date.format(DateTimeFormatter.ofPattern(DateTimePatternEnum.YYYY_MM_DD.getPattern()))).collect(Collectors.toList());
return dateList;
}
}

@ -12,6 +12,7 @@ import com.luoo.user.enums.RequestFrequencyTypeEnum;
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
public @interface GlobalInterceptor { public @interface GlobalInterceptor {
boolean checkLogin() default false; boolean checkLogin() default false;
boolean checkAppUserLogin() default false;
boolean checkAdminLogin() default false; boolean checkAdminLogin() default false;
boolean checkParam() default true; boolean checkParam() default true;

@ -69,6 +69,13 @@ public class OperationAspect {
checkAdminLogin(); checkAdminLogin();
} }
/**
* app
*/
if (interceptor.checkAppUserLogin()) {
checkAppUserLogin();
}
/** /**
* *
*/ */
@ -96,6 +103,16 @@ public class OperationAspect {
} }
redisUtils.increment(redisKey, 1, frequencyTyp.getSeconds()); redisUtils.increment(redisKey, 1, frequencyTyp.getSeconds());
} }
private void checkAppUserLogin() {
UserLoginDto userLoginDto = getUserLoginDtoFromToken();
if (userLoginDto == null) {
throw new BizException(StatusCode.UNAUTHORIZED);
}
if (!Constants.TOKEN_ROLE_APP_USER.equals(userLoginDto.getRoles())) {
throw new BizException(StatusCode.FORBIDDEN);
}
}
private void checkAdminLogin() { private void checkAdminLogin() {
UserLoginDto userLoginDto = getUserLoginDtoFromToken(); UserLoginDto userLoginDto = getUserLoginDtoFromToken();
if (userLoginDto == null) { if (userLoginDto == null) {
@ -105,7 +122,7 @@ public class OperationAspect {
throw new BizException(StatusCode.FORBIDDEN); throw new BizException(StatusCode.FORBIDDEN);
} }
} }
private void checkLogin() { private void checkLogin() {
UserLoginDto userLoginDto = getUserLoginDtoFromToken(); UserLoginDto userLoginDto = getUserLoginDtoFromToken();
if (userLoginDto == null) { if (userLoginDto == null) {

@ -8,24 +8,32 @@ import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin; 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.PathVariable;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import com.luoo.user.annotation.GlobalInterceptor; import com.luoo.user.annotation.GlobalInterceptor;
import com.luoo.user.annotation.VerifyParam;
import com.luoo.user.constants.Constants; import com.luoo.user.constants.Constants;
import com.luoo.user.dto.response.UserRespDTO; import com.luoo.user.dto.response.UserRespDTO;
import com.luoo.user.enums.VerifyRegexEnum;
import com.luoo.user.pojo.User; import com.luoo.user.pojo.User;
import com.luoo.user.service.UserService; import com.luoo.user.service.UserService;
import api.Result; import api.Result;
import api.StatusCode; import api.StatusCode;
import dto.UserLoginDto; import dto.UserLoginDto;
import enums.DateTimePatternEnum;
import io.swagger.annotations.Api; import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiOperation;
import util.DateUtil;
import util.JwtUtil; import util.JwtUtil;
import util.StringTools; import util.StringTools;
@ -42,20 +50,64 @@ public class MyController {
/* /*
* @Value("${project.folder:}") private String projectFolder="./"; * @Value("${project.folder:}") private String projectFolder="./";
*/ */
@ApiOperation(value = "1.获取个人信息") @ApiOperation(value = "1.获取个人信息")
@PostMapping("/getUserInfo") @GetMapping("/getUserInfo")
@GlobalInterceptor @GlobalInterceptor
public Result getUserInfo(@RequestHeader(value = "token", required = false) String token) { public Result getUserInfo(@RequestHeader(value = "token", required = false) String token) {
UserLoginDto userLoginDto = jwtUtil.getUserLoginDto(token); UserLoginDto userLoginDto = jwtUtil.getUserLoginDto(token);
if (null == userLoginDto) { if (null == userLoginDto) {
return Result.validateFailed(); return Result.validateFailed();
} }
User user = userService.findById(userLoginDto.getUserId());
UserRespDTO userRespDTO = new UserRespDTO(); UserRespDTO userRespDTO = new UserRespDTO();
BeanUtils.copyProperties(user, userRespDTO); if (Constants.TOKEN_ROLE_APP_USER.equals(userLoginDto.getRoles())) {
User user = userService.findById(userLoginDto.getUserId());
BeanUtils.copyProperties(user, userRespDTO);
} else {
userRespDTO.setNickname(userLoginDto.getNickName());
userRespDTO.setId(userLoginDto.getUserId());
}
return Result.success(userRespDTO); return Result.success(userRespDTO);
} }
@ApiOperation(value = "2.编辑个人信息",notes="游客无法编辑个人信息")
@ApiImplicitParams({
@ApiImplicitParam(name = "nickName", value = "昵称最多12个字符", required = false),
@ApiImplicitParam(name = "signature", value = "签名最多50个字符", required = false),
@ApiImplicitParam(name = "birthDay", value = "生日,格式为: yyyy.MM.dd", required = false),
@ApiImplicitParam(name = "sex", value = "性别4个值0为男1 为女2为保密不填为空", required = false)
})
@PutMapping("/updateUserInfo")
@GlobalInterceptor(checkAppUserLogin = true)
public Result<Void> updateUserInfo(@RequestHeader(value = "token", required = false) String token,
@VerifyParam(max = 12) String nickName,
@VerifyParam(max = 50) String signature,
String birthDay,
String sex) {
UserLoginDto userLoginDto = jwtUtil.getUserLoginDto(token);
if(!StringTools.isEmpty(nickName)) {
long count = userService.countByNickName(nickName);
if (count > 0) {
return Result.failed(StatusCode.USER_NICK_NAME_HAS_BEEN_EXIST);
}
}
User user = userService.findById(userLoginDto.getUserId());
if(!StringTools.isEmpty(nickName)) {
user.setNickname(nickName);
}
if(!StringTools.isEmpty(signature)) {
user.setPersonality(signature);
}
if(!StringTools.isEmpty(birthDay)) {
user.setBirthday(DateUtil.parse(birthDay, DateTimePatternEnum.YYYY_DOT_MM_DOT_DD.getPattern()));
}
if(!StringTools.isEmpty(sex)) {
user.setSex(sex);
}
userService.update(user);
return Result.success();
}
/* /*
* @ApiOperation(value = "2.上传个人头像") * @ApiOperation(value = "2.上传个人头像")
@ -82,24 +134,7 @@ public class MyController {
* appUserInfo.setAvatar(Constants.FOLDER_AVATAR + avatarName); * appUserInfo.setAvatar(Constants.FOLDER_AVATAR + avatarName);
* appUserInfoService.updateAppUserInfoByUserId(appUserInfo, * appUserInfoService.updateAppUserInfoByUserId(appUserInfo,
* userLoginDto.getUserId()); return getSuccessResponseVO(null); } * userLoginDto.getUserId()); return getSuccessResponseVO(null); }
*
* @ApiOperation(value = "1.获取个人信息")
*
* @RequestMapping("/updateUserInfo")
*
* @GlobalInterceptor(checkLogin = true) public ResponseVO
* updateUserInfo(@RequestHeader(value = "token", required = false) String
* token,
*
* @VerifyParam(required = true) Integer sex,
*
* @VerifyParam(regex = VerifyRegexEnum.PASSWORD) String passwrd) {
* AppUserLoginDto userLoginDto = getAppUserLoginfoFromToken(token);
*
* AppUserInfo updateInfo = new AppUserInfo(); updateInfo.setSex(sex); if
* (!StringTools.isEmpty(passwrd)) {
* updateInfo.setPassword(StringTools.encodeByMD5(passwrd)); }
* appUserInfoService.updateAppUserInfoByUserId(updateInfo,
* userLoginDto.getUserId()); return getSuccessResponseVO(null); }
*/ */
} }

@ -26,4 +26,6 @@ public interface UserDao extends JpaRepository<User,String>,JpaSpecificationExec
public User findByLoginname(String loginname); public User findByLoginname(String loginname);
public long countByNickname(String nickName);
} }

@ -6,7 +6,7 @@ import lombok.Data;
public class UserRespDTO { public class UserRespDTO {
@ApiModelProperty(value = "ID") @ApiModelProperty(value = "ID")
private String id;//ID private String id;//ID
@ApiModelProperty(value = "昵称,首次注册登录,登录用户随机为“雀乐-XXX”,游客为“游客-XXX”, XXX 为2~4位中文昵称",example="雀乐-XXX") @ApiModelProperty(value = "昵称,首次注册登录,登录用户随机为“雀乐-XXXX-XXXX”,游客为“游客-XXXX-XXXX”, XXXX 为2~4位中文昵称",example="雀乐-蓉江晨玥^沙顺芊润")
private String nickname;//昵称 private String nickname;//昵称
@ApiModelProperty(value = "性别0为男1 为女,首次注册登录,留空不显示",example="0") @ApiModelProperty(value = "性别0为男1 为女,首次注册登录,留空不显示",example="0")
private String sex;//性别 private String sex;//性别

@ -300,4 +300,8 @@ public class UserService {
return null; return null;
} }
} }
public long countByNickName(String nickName) {
return userDao.countByNickname(nickName);
}
} }

@ -0,0 +1,20 @@
package com.luoo.user.controller;
import static org.junit.Assert.*;
import java.util.Date;
import org.junit.Test;
import enums.DateTimePatternEnum;
import util.DateUtil;
public class MyControllerTest {
@Test
public void testBirthDay() {
String birthDay="2020.02.02";
Date date=DateUtil.parse(birthDay, DateTimePatternEnum.YYYY_DOT_MM_DOT_DD.getPattern());
assertTrue(null!=date);
}
}

@ -0,0 +1,39 @@
package com.luoo.user.util;
import java.util.stream.IntStream;
import org.junit.Test;
import org.springframework.util.StopWatch;
import com.apifan.common.random.RandomSource;
public class NickNameUtilTest {
int size = 4;
String[] content = new String[] { "~", "`", "@", "$", "%", "^", "&", "*", "+", "-", "|", ".", "<", ">" };
@Test
public void test() {
int total = 100000;
System.out.println("total: " + total);
StopWatch sw = new StopWatch();
sw.start();
IntStream.range(0, total).parallel().mapToObj(j -> getRandomNickName()).limit(100).forEach(System.out::println);
for (int i = 4; i < 5; i++) {
size = i;
long distinctNickName = IntStream.range(0, total).parallel().mapToObj(j -> getRandomNickName()).distinct()
.count();
System.out.println("length: " + i + " distinctCount: " + distinctNickName);
}
sw.stop();
System.out.println(sw.prettyPrint());
}
public String getRandomNickName() {
int index = RandomSource.numberSource().randomInt(0, content.length);
String character = content[index];
return "雀乐-" + RandomSource.personInfoSource().randomChineseNickName(4) + character
+ RandomSource.personInfoSource().randomChineseNickName(4);
}
}
Loading…
Cancel
Save