格式化代码

This commit is contained in:
石皮幼鸟 2024-04-10 15:15:36 +08:00
parent 71a01cfd87
commit 73b2ddae7d
16 changed files with 112 additions and 90 deletions

View File

@ -17,8 +17,8 @@ import org.springframework.data.redis.serializer.StringRedisSerializer;
public class RedisConfig { public class RedisConfig {
@Bean @Bean
@ConditionalOnMissingBean(name = "redis template") @ConditionalOnMissingBean(name = "redis template")
public RedisTemplate<Object,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){ public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<Object,Object> template = new RedisTemplate<>(); RedisTemplate<Object, Object> template = new RedisTemplate<>();
//使用fastjson序列化 //使用fastjson序列化
FastJsonRedisSerializer fastJsonRedisSerializer = new FastJsonRedisSerializer(Object.class); FastJsonRedisSerializer fastJsonRedisSerializer = new FastJsonRedisSerializer(Object.class);
//value值的序列化采用fastJsonRedisSerializer //value值的序列化采用fastJsonRedisSerializer
@ -33,7 +33,7 @@ public class RedisConfig {
@Bean @Bean
@ConditionalOnMissingBean(StringRedisTemplate.class) @ConditionalOnMissingBean(StringRedisTemplate.class)
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory){ public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
StringRedisTemplate template = new StringRedisTemplate(); StringRedisTemplate template = new StringRedisTemplate();
template.setConnectionFactory(redisConnectionFactory); template.setConnectionFactory(redisConnectionFactory);
return template; return template;

View File

@ -1,8 +1,10 @@
package com.example.catchTheLetters.config; package com.example.catchTheLetters.config;
import org.jetbrains.annotations.NotNull;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders; import org.springframework.http.HttpHeaders;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/** /**
@ -18,7 +20,7 @@ public class WebMvcConfig {
public WebMvcConfigurer corsConfigurer() { public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() { return new WebMvcConfigurer() {
@Override @Override
public void addCorsMappings(org.springframework.web.servlet.config.annotation.CorsRegistry registry) { public void addCorsMappings(@NotNull CorsRegistry registry) {
registry registry
.addMapping("/**") .addMapping("/**")
.allowedOriginPatterns("*") // 允许所有域 .allowedOriginPatterns("*") // 允许所有域

View File

@ -11,7 +11,7 @@ public interface CommonConstant {
Integer TOKEN_EXPIRE_TIME = 7200000; Integer TOKEN_EXPIRE_TIME = 7200000;
Integer REDIS_EXPIRE_TIME = 7*24*60*60*1000; Integer REDIS_EXPIRE_TIME = 7 * 24 * 60 * 60 * 1000;
String EMAIL_REGEX = "^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$"; String EMAIL_REGEX = "^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$";

View File

@ -13,13 +13,13 @@ import lombok.Getter;
@AllArgsConstructor @AllArgsConstructor
public enum HttpStatus { public enum HttpStatus {
SUCCESS(200,"操作成功"), SUCCESS(200, "操作成功"),
BAD_REQUEST(400,"参数列表错误"), BAD_REQUEST(400, "参数列表错误"),
TOKEN_EXCEPTION(401,"token验证错误"), TOKEN_EXCEPTION(401, "token验证错误"),
ERROR(500,"系统内部错误"); ERROR(500, "系统内部错误");
private final Integer code; private final Integer code;

View File

@ -15,6 +15,7 @@ import org.springframework.web.bind.annotation.*;
/** /**
* 认证控制器 * 认证控制器
*
* @author spyn * @author spyn
*/ */
@RestController @RestController
@ -53,8 +54,8 @@ public class AuthController {
@ApiOperation(value = "用户信息查询不会返回密码查不出status为0的用户") @ApiOperation(value = "用户信息查询不会返回密码查不出status为0的用户")
@GetMapping("/info") @GetMapping("/info")
@ApiParam(name = "id", value = "用户ID不传就是拿token查自己") @ApiParam(name = "id", value = "用户ID不传就是拿token查自己")
public R<User> info(@RequestParam(required = false) Integer id, @RequestHeader("token")String token) { public R<User> info(@RequestParam(required = false) Integer id, @RequestHeader("token") String token) {
if (id != null){ if (id != null) {
return R.ok(authService.getUserInfo(id)); return R.ok(authService.getUserInfo(id));
} }
return R.ok(authService.verify(token)); return R.ok(authService.verify(token));

View File

@ -12,6 +12,7 @@ import org.springframework.web.bind.annotation.*;
/** /**
* 关卡控制器 * 关卡控制器
*
* @author spyn * @author spyn
*/ */
@RestController @RestController

View File

@ -7,6 +7,7 @@ import java.util.List;
/** /**
* 关卡类 * 关卡类
*
* @author spyn * @author spyn
*/ */
@Data @Data

View File

@ -6,6 +6,7 @@ import java.io.Serializable;
/** /**
* 关卡结算信息类 * 关卡结算信息类
*
* @author spyn * @author spyn
*/ */
@Data @Data

View File

@ -7,6 +7,7 @@ import java.io.Serializable;
/** /**
* 用户类 * 用户类
*
* @author spyn * @author spyn
*/ */
@Data @Data
@ -68,7 +69,7 @@ public class User implements Serializable {
*/ */
private Integer progress; private Integer progress;
public UserVo toVo(){ public UserVo toVo() {
UserVo userVo = new UserVo(); UserVo userVo = new UserVo();
userVo.setId(this.getId()); userVo.setId(this.getId());
userVo.setUsername(this.getUsername()); userVo.setUsername(this.getUsername());

View File

@ -6,6 +6,7 @@ import java.io.Serializable;
/** /**
* 数据表版本类用于Realm对MongoDB的数据表版本进行同步检测版本号不同则进行同步 * 数据表版本类用于Realm对MongoDB的数据表版本进行同步检测版本号不同则进行同步
*
* @author spyn * @author spyn
*/ */
@Data @Data

View File

@ -6,6 +6,7 @@ import java.io.Serializable;
/** /**
* 登录信息类 * 登录信息类
*
* @author spyn * @author spyn
*/ */
@Data @Data

View File

@ -6,6 +6,7 @@ import java.io.Serializable;
/** /**
* 注册信息类 * 注册信息类
*
* @author spyn * @author spyn
*/ */
@Data @Data

View File

@ -8,11 +8,13 @@ import com.example.catchTheLetters.utils.R;
/** /**
* 认证服务接口 * 认证服务接口
*
* @author spyn * @author spyn
*/ */
public interface AuthService { public interface AuthService {
/** /**
* 登录 * 登录
*
* @param loginDto 登录信息 * @param loginDto 登录信息
* @return token * @return token
*/ */
@ -20,6 +22,7 @@ public interface AuthService {
/** /**
* 注销 * 注销
*
* @param token token * @param token token
* @return 是否成功 * @return 是否成功
*/ */
@ -27,6 +30,7 @@ public interface AuthService {
/** /**
* 验证token * 验证token
*
* @param token token * @param token token
* @return 用户信息不可以包含密码 * @return 用户信息不可以包含密码
*/ */
@ -34,6 +38,7 @@ public interface AuthService {
/** /**
* 注册 * 注册
*
* @param registerDto 注册信息 * @param registerDto 注册信息
* @return token * @return token
*/ */
@ -41,6 +46,7 @@ public interface AuthService {
/** /**
* 获取用户信息 * 获取用户信息
*
* @param id 用户id * @param id 用户id
* @return 用户信息 * @return 用户信息
*/ */
@ -48,6 +54,7 @@ public interface AuthService {
/** /**
* 通过用户名获取信息 * 通过用户名获取信息
*
* @param username 用户名 * @param username 用户名
* @return 用户信息 * @return 用户信息
*/ */

View File

@ -18,110 +18,110 @@ import java.util.Set;
*/ */
public interface RedisService { public interface RedisService {
void set(String key, Object value, long time); void set(String key, Object value, long time);
void set(String key, Object value); void set(String key, Object value);
Object get(String key); Object get(String key);
Boolean del(String key); Boolean del(String key);
Long del(List<String> keys); Long del(List<String> keys);
Boolean expire(String key, long time); Boolean expire(String key, long time);
Long getExpire(String key); Long getExpire(String key);
Boolean hasKey(String key); Boolean hasKey(String key);
Long incr(String key, long delta); Long incr(String key, long delta);
Long incrExpire(String key, long time); Long incrExpire(String key, long time);
Long decr(String key, long delta); Long decr(String key, long delta);
Object hGet(String key, String hashKey); Object hGet(String key, String hashKey);
Boolean hSet(String key, String hashKey, Object value, long time); Boolean hSet(String key, String hashKey, Object value, long time);
void hSet(String key, String hashKey, Object value); void hSet(String key, String hashKey, Object value);
Map<String, Object> hGetAll(String key); Map<String, Object> hGetAll(String key);
Boolean hSetAll(String key, Map<String, Object> map, long time); Boolean hSetAll(String key, Map<String, Object> map, long time);
void hSetAll(String key, Map<String, ?> map); void hSetAll(String key, Map<String, ?> map);
void hDel(String key, Object... hashKey); void hDel(String key, Object... hashKey);
Boolean hHasKey(String key, String hashKey); Boolean hHasKey(String key, String hashKey);
Long hIncr(String key, String hashKey, Long delta); Long hIncr(String key, String hashKey, Long delta);
Long hDecr(String key, String hashKey, Long delta); Long hDecr(String key, String hashKey, Long delta);
Double zIncr(String key, Object value, Double score); Double zIncr(String key, Object value, Double score);
Double zDecr(String key, Object value, Double score); Double zDecr(String key, Object value, Double score);
Map<Object, Double> zReverseRangeWithScore(String key, long start, long end); Map<Object, Double> zReverseRangeWithScore(String key, long start, long end);
Double zScore(String key, Object value); Double zScore(String key, Object value);
Map<Object, Double> zAllScore(String key); Map<Object, Double> zAllScore(String key);
Set<Object> sMembers(String key); Set<Object> sMembers(String key);
Long sAdd(String key, Object... values); Long sAdd(String key, Object... values);
Long sAddExpire(String key, long time, Object... values); Long sAddExpire(String key, long time, Object... values);
Boolean sIsMember(String key, Object value); Boolean sIsMember(String key, Object value);
Long sSize(String key); Long sSize(String key);
Long sRemove(String key, Object... values); Long sRemove(String key, Object... values);
List<Object> lRange(String key, long start, long end); List<Object> lRange(String key, long start, long end);
Long lSize(String key); Long lSize(String key);
Object lIndex(String key, long index); Object lIndex(String key, long index);
Long lPush(String key, Object value); Long lPush(String key, Object value);
Long lPush(String key, Object value, long time); Long lPush(String key, Object value, long time);
Long lPushAll(String key, Object... values); Long lPushAll(String key, Object... values);
Long lPushAll(String key, Long time, Object... values); Long lPushAll(String key, Long time, Object... values);
Long lRemove(String key, long count, Object value); Long lRemove(String key, long count, Object value);
Boolean bitAdd(String key, int offset, boolean b); Boolean bitAdd(String key, int offset, boolean b);
Boolean bitGet(String key, int offset); Boolean bitGet(String key, int offset);
Long bitCount(String key); Long bitCount(String key);
List<Long> bitField(String key, int limit, int offset); List<Long> bitField(String key, int limit, int offset);
byte[] bitGetAll(String key); byte[] bitGetAll(String key);
Long hyperAdd(String key, Object... value); Long hyperAdd(String key, Object... value);
Long hyperGet(String... key); Long hyperGet(String... key);
void hyperDel(String key); void hyperDel(String key);
Long geoAdd(String key, Double x, Double y, String name); Long geoAdd(String key, Double x, Double y, String name);
List<Point> geoGetPointList(String key, Object... place); List<Point> geoGetPointList(String key, Object... place);
Distance geoCalculationDistance(String key, String placeOne, String placeTow); Distance geoCalculationDistance(String key, String placeOne, String placeTow);
GeoResults<RedisGeoCommands.GeoLocation<Object>> geoNearByPlace(String key, String place, Distance distance, long limit, Sort.Direction sort); GeoResults<RedisGeoCommands.GeoLocation<Object>> geoNearByPlace(String key, String place, Distance distance, long limit, Sort.Direction sort);
List<String> geoGetHash(String key, String... place); List<String> geoGetHash(String key, String... place);
} }

View File

@ -42,21 +42,21 @@ public class AuthServiceImpl implements AuthService {
var patternPhone = Pattern.compile(CommonConstant.PHONE_REGEX); var patternPhone = Pattern.compile(CommonConstant.PHONE_REGEX);
var matcherPhone = patternPhone.matcher(username); var matcherPhone = patternPhone.matcher(username);
User user; User user;
if (matcherEmail.matches()){ if (matcherEmail.matches()) {
user = mongoTemplate.findOne(new Query(Criteria.where(CommonConstant.EMAIL).is(username).and(CommonConstant.STATUS).ne(0)), User.class); user = mongoTemplate.findOne(new Query(Criteria.where(CommonConstant.EMAIL).is(username).and(CommonConstant.STATUS).ne(0)), User.class);
}else if (matcherPhone.matches()){ } else if (matcherPhone.matches()) {
user = mongoTemplate.findOne(new Query(Criteria.where(CommonConstant.PHONE).is(username).and(CommonConstant.STATUS).ne(0)), User.class); user = mongoTemplate.findOne(new Query(Criteria.where(CommonConstant.PHONE).is(username).and(CommonConstant.STATUS).ne(0)), User.class);
}else { } else {
user = mongoTemplate.findOne(new Query(Criteria.where(CommonConstant.USERNAME).is(username).and(CommonConstant.STATUS).ne(0)),User.class); user = mongoTemplate.findOne(new Query(Criteria.where(CommonConstant.USERNAME).is(username).and(CommonConstant.STATUS).ne(0)), User.class);
} }
if (Objects.isNull(user)){ if (Objects.isNull(user)) {
return R.fail("用户不存在"); return R.fail("用户不存在");
} }
if (!user.getPassword().equals(loginDto.getPassword())){ if (!user.getPassword().equals(loginDto.getPassword())) {
return R.fail("密码错误"); return R.fail("密码错误");
} }
Map<String, String> map = new HashMap<>(); Map<String, String> map = new HashMap<>();
map.put("id",user.getId().toString()); map.put("id", user.getId().toString());
var token = JwtUtil.getToken(map, CommonConstant.TOKEN_EXPIRE_TIME); var token = JwtUtil.getToken(map, CommonConstant.TOKEN_EXPIRE_TIME);
redisService.hSet(token, user.getId().toString(), CommonConstant.REDIS_EXPIRE_TIME); redisService.hSet(token, user.getId().toString(), CommonConstant.REDIS_EXPIRE_TIME);
return R.ok(token); return R.ok(token);
@ -74,8 +74,8 @@ public class AuthServiceImpl implements AuthService {
if (map != null) { if (map != null) {
id = map.get("id").asString().replaceAll("\"", ""); id = map.get("id").asString().replaceAll("\"", "");
} }
var user = mongoTemplate.findOne(new Query(Criteria.where("id").is(id).and(CommonConstant.STATUS).ne(0)),User.class); var user = mongoTemplate.findOne(new Query(Criteria.where("id").is(id).and(CommonConstant.STATUS).ne(0)), User.class);
if (Objects.isNull(user)){ if (Objects.isNull(user)) {
return null; return null;
} }
return user; return user;
@ -93,20 +93,20 @@ public class AuthServiceImpl implements AuthService {
user.setUsername(registerDto.getUsername()); user.setUsername(registerDto.getUsername());
user.setPassword(registerDto.getPassword()); user.setPassword(registerDto.getPassword());
var insert = mongoTemplate.insert(user); var insert = mongoTemplate.insert(user);
if (insert.getId() != null){ if (insert.getId() != null) {
return R.ok(user.toVo()); return R.ok(user.toVo());
}else { } else {
return R.fail("注册失败,请重试"); return R.fail("注册失败,请重试");
} }
} }
@Override @Override
public User getUserInfo(Integer id) { public User getUserInfo(Integer id) {
return mongoTemplate.findOne(new Query(Criteria.where("id").is(id).and(CommonConstant.STATUS).ne(0)),User.class); return mongoTemplate.findOne(new Query(Criteria.where("id").is(id).and(CommonConstant.STATUS).ne(0)), User.class);
} }
@Override @Override
public User getUserByName(String username) { public User getUserByName(String username) {
return mongoTemplate.findOne(new Query(Criteria.where("username").is(username).and(CommonConstant.STATUS).ne(0)),User.class); return mongoTemplate.findOne(new Query(Criteria.where("username").is(username).and(CommonConstant.STATUS).ne(0)), User.class);
} }
} }

View File

@ -22,16 +22,18 @@ import java.util.Map;
@Component @Component
public class JwtUtil { public class JwtUtil {
public static final Integer EXPIRE_TIME = 1; // 1天 public static final Integer EXPIRE_TIME = 1; // 1天
/** /**
* 生成token * 生成token
* @param map 传入map *
* @param map 传入map
* @param expired token存储时间 * @param expired token存储时间
* @return token * @return token
*/ */
public static String getToken(Map<String,String> map, Integer expired){ public static String getToken(Map<String, String> map, Integer expired) {
Calendar instance = Calendar.getInstance(); Calendar instance = Calendar.getInstance();
//设置过期时间单位 //设置过期时间单位
instance.add(Calendar.DATE,expired); instance.add(Calendar.DATE, expired);
//创建JWT builder //创建JWT builder
JWTCreator.Builder builder = JWT.create(); JWTCreator.Builder builder = JWT.create();
//payload //payload
@ -44,28 +46,30 @@ public class JwtUtil {
/** /**
* 验证token合法性 || 获取token信息方法 * 验证token合法性 || 获取token信息方法
*
* @param token 传入token * @param token 传入token
* @return * @return
*/ */
public static DecodedJWT verify(String token){ public static DecodedJWT verify(String token) {
return JWT.require(Algorithm.HMAC256(CommonConstant.TOKEN_SECRET)).build().verify(token); return JWT.require(Algorithm.HMAC256(CommonConstant.TOKEN_SECRET)).build().verify(token);
} }
/** /**
* 获取payload * 获取payload
*
* @param token 传入token * @param token 传入token
* @return 返回payload * @return 返回payload
*/ */
public static Map<String, Claim> getPayload(String token){ public static Map<String, Claim> getPayload(String token) {
Map<String,Claim> claims = null; Map<String, Claim> claims = null;
try{ try {
claims = JWT.require(Algorithm.HMAC256(CommonConstant.TOKEN_SECRET)).build().verify(token).getClaims(); claims = JWT.require(Algorithm.HMAC256(CommonConstant.TOKEN_SECRET)).build().verify(token).getClaims();
} catch (Exception e){ } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
try { try {
return claims; return claims;
} catch (NullPointerException e){ } catch (NullPointerException e) {
e.printStackTrace(); e.printStackTrace();
return null; return null;
} }
@ -74,19 +78,20 @@ public class JwtUtil {
/** /**
* 获取过期时间 * 获取过期时间
*/ */
public static Date getExpiresAt(String token){ public static Date getExpiresAt(String token) {
return JwtUtil.getExpiresAt(token); return JwtUtil.getExpiresAt(token);
} }
/** /**
* 判断token是否过期 * 判断token是否过期
*
* @return true:过期 false:没过期 * @return true:过期 false:没过期
*/ */
public Boolean isTokenExpired(String token){ public Boolean isTokenExpired(String token) {
try { try {
Date expiration = JwtUtil.getExpiresAt(token); Date expiration = JwtUtil.getExpiresAt(token);
return expiration.before(new Date()); return expiration.before(new Date());
} catch (TokenExpiredException e){ } catch (TokenExpiredException e) {
return true; return true;
} }
} }