Skip to content

Commit

Permalink
集成Authing,添加推荐功能
Browse files Browse the repository at this point in the history
  • Loading branch information
YunlongChen committed Jan 8, 2024
1 parent c70a986 commit e1c612c
Show file tree
Hide file tree
Showing 55 changed files with 902 additions and 180 deletions.
41 changes: 41 additions & 0 deletions qing-domain/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,3 +78,44 @@
| `utils` | 工具包 | 工具函数封装 |
| `--timer` | timer | 定时器接口封装 |
| `--upload` | oss | oss接口封装 |

### 快速执行

#### 快速创建功能

可以通过创建一下带注解的类,快速创建一个功能。待注解类完成后,执行`编译`命令即可实现简单的 CRUD 功能。
注意功能创建好之后,尽量不要提交带注解的类到 Git 因为注解处理器会影响其他人的启动项目

```java

@GenVo
@GenCreator
@GenUpdater
@GenQuery
@GenCreateRequest
@GenUpdateRequest
@GenQueryRequest
@GenResponse
@GenRepository
@GenService
@GenServiceImpl
@GenController
@GenMapper
@GenFeign(serverName = "stanic")
@Getter
@Setter
@ToString
@Entity
@Table(name = "anime_recommend")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public class Recommend extends BaseJpaAggregate {

@NotBlank(message = "名称不能为空")
@FieldDesc(description = "名称")
private String name;

@FieldDesc(description = "介绍")
private String instruction;

}
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package cn.chenyunlong.qing.aspect;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
public class HttpLogInterceptor implements HandlerInterceptor {

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 记录请求日志
log.info("用户访问地址:{}, 请求方式: {},请求地址:{}", request.getRemoteAddr(), request.getMethod(), request.getServletPath());
log.info("----------------请求头.start.....");
return HandlerInterceptor.super.preHandle(request, response, handler);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,13 @@

package cn.chenyunlong.qing.config;

import cn.chenyunlong.qing.aspect.HttpLogInterceptor;
import cn.chenyunlong.qing.infrastructure.config.properties.QingProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
Expand All @@ -29,7 +30,6 @@
@Slf4j
@Configuration
@RequiredArgsConstructor
@ComponentScan(basePackages = {"cn.chenyunlong.common"})
public class WebMvcConfig implements WebMvcConfigurer {

private final QingProperties qingProperties;
Expand All @@ -46,4 +46,10 @@ public void addCorsMappings(CorsRegistry registry) {
.allowedOriginPatterns("*")
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS");
}

@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new HttpLogInterceptor());
WebMvcConfigurer.super.addInterceptors(registry);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

import cn.chenyunlong.qing.config.security.filter.MyAuthenticationProcessingFilter;
import cn.chenyunlong.qing.config.security.jwt.MySecurityContextRepository;
import cn.chenyunlong.qing.config.security.password.MyCustomDsl;
import cn.chenyunlong.qing.config.security.utils.JwtTokenUtil;
import cn.chenyunlong.security.base.extension.DummyUserContextAware;
import cn.chenyunlong.security.base.extension.UserContextAware;
Expand Down Expand Up @@ -48,6 +49,7 @@ public class SecurityConfig {
private final JwtTokenUtil jwtTokenUtil;
private final UserDetailsService userDetailsService;
private final AuthingLoginConfigurer authingLoginConfigurer;
private final MyCustomDsl customPasswordDsl;
private final AccessDeniedHandler accessDeniedHandler;
private final AuthenticationEntryPoint authenticationEntryPoint;

Expand All @@ -59,29 +61,30 @@ UserContextAware dummyUserContext() {

@Bean
public SecurityFilterChain userLoginFilterChain(HttpSecurity http) throws Exception {
http.csrf().disable();
http.cors().disable();
http.authorizeHttpRequests()
.requestMatchers(
authingProperties.getRedirectUrlPrefix(),
"/swagger-ui/**",
"/doc.html",
"/v3/api-docs/**",
"/login",
"/favicon.ico",
"/auth/passLogin",
"api/authorize/authing/login")
.permitAll();
http.authorizeHttpRequests()
.anyRequest().hasRole("USER");
http.formLogin(formLogin -> formLogin.usernameParameter("username")
.loginProcessingUrl("/auth/passLogin")
);
http.addFilterAt(new MyAuthenticationProcessingFilter(), UsernamePasswordAuthenticationFilter.class);
http.logout().logoutSuccessUrl("/login.html");
http.securityContext(httpSecuritySecurityContextConfigurer ->
httpSecuritySecurityContextConfigurer.securityContextRepository(securityContextRepository()));
http.apply(authingLoginConfigurer);
http.apply(customPasswordDsl);
http.securityMatcher("/**")
.authorizeHttpRequests(authorize -> {
authorize.requestMatchers(
authingProperties.getRedirectUrlPrefix(),
"/swagger-ui/**",
"/doc.html",
"/v3/api-docs/**",
"/login",
"/favicon.ico",
"/auth/passLogin",
"/api/authorize/authing/login").permitAll();
authorize.anyRequest().hasRole("USER");
})
.formLogin(formLogin -> formLogin.usernameParameter("username")
.loginProcessingUrl("/auth/passLogin")
.permitAll()
)
.addFilterBefore(new MyAuthenticationProcessingFilter(), UsernamePasswordAuthenticationFilter.class)
.logout(logout -> logout.logoutSuccessUrl("/login.html"))
.securityContext(httpSecuritySecurityContextConfigurer ->
httpSecuritySecurityContextConfigurer.securityContextRepository(securityContextRepository()))
;
http.exceptionHandling()
.accessDeniedHandler(accessDeniedHandler)
.authenticationEntryPoint(authenticationEntryPoint);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,10 +71,10 @@ private String resolveToken(HttpServletRequest request) {
if (cookies == null) {
return null;
}
Optional<Cookie> zhangliToken =
Optional<Cookie> cookieOptional =
Arrays.stream(cookies).filter(cookie -> cookie.getName().equals(AUTHORIZATION_COOKIES))
.findFirst();
return zhangliToken.map(Cookie::getValue).orElse(null);
return cookieOptional.map(Cookie::getValue).orElse(null);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -36,15 +36,14 @@ public SecurityContext loadContext(HttpRequestResponseHolder requestResponseHold
token = token.replaceFirst("Bearer ", "");
// 拿到 用户名
String username = jwtTokenUtil.getUserNameFromToken(token);
if (StrUtil.isBlank(username)) {
return securityContext;
}
// 查询用户
UserDetails user = userService.loadUserByUsername(username);
if (user == null) {
return securityContext;
}
// 验证 token
if (!jwtTokenUtil.validateToken(token, user)) {
return securityContext;
}
UsernamePasswordAuthenticationToken authenticationToken = UsernamePasswordAuthenticationToken.authenticated(user.getUsername(), user.getPassword(), user.getAuthorities());
authenticationToken.setDetails(user);
securityContext.setAuthentication(authenticationToken);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package cn.chenyunlong.qing.config.security.password;

import lombok.RequiredArgsConstructor;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
public class MyCustomDsl extends AbstractHttpConfigurer<MyCustomDsl, HttpSecurity> {

private final UserDetailsService userDetailsService;

@Override
public void init(HttpSecurity http) throws Exception {
// any method that adds another configurer
// must be done in the init method
http.csrf().disable();
http.formLogin();
}

@Override
public void configure(HttpSecurity http) throws Exception {
// myFilter.setFlag(flag);
http.addFilterBefore(new PasswordLoginFilter(), UsernamePasswordAuthenticationFilter.class);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,18 @@
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import java.io.IOException;

public class PasswordLoginFilter extends AbstractAuthenticationProcessingFilter {

public PasswordLoginFilter(AuthenticationManager authenticationManager) {
super("/auth/passLogin", authenticationManager);
public PasswordLoginFilter() {
super(new AntPathRequestMatcher("/auth/passLogin", "POST"));
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,11 @@
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
Expand All @@ -28,7 +27,6 @@ public class JwtTokenUtil {
private String secret;
private Long expiration;
private String header = "jwt";
private static final Logger LOGGER = LoggerFactory.getLogger(JwtTokenUtil.class);

/**
* 根据负责生成JWT的token
Expand All @@ -51,8 +49,10 @@ private Claims getClaimsFromToken(String token) {
.setSigningKey(secret)
.parseClaimsJws(token)
.getBody();
} catch (ExpiredJwtException exception) {
log.info("JWT已过期:{},jwt:{}", exception.getMessage(), token);
} catch (Exception e) {
LOGGER.info("JWT格式验证失败:{}", token);
log.info("JWT格式验证失败:{}", token);
}
return claims;
}
Expand Down Expand Up @@ -157,9 +157,6 @@ private boolean tokenRefreshJustBefore(String token, int time) {
Date created = claims.get(CLAIM_KEY_CREATED, Date.class);
Date refreshDate = new Date();
//刷新时间在创建时间的指定时间内
if (refreshDate.after(created) && refreshDate.before(DateUtil.offsetSecond(created, time))) {
return true;
}
return false;
return refreshDate.after(created) && refreshDate.before(DateUtil.offsetSecond(created, time));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,15 @@
import cn.chenyunlong.qing.domain.anime.attachement.dto.vo.AttachmentVO;
import cn.chenyunlong.qing.domain.anime.attachement.mapper.AttachmentMapper;
import cn.chenyunlong.qing.domain.anime.attachement.service.IAttachmentService;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.util.stream.Collectors;

@Tag(name = "附件管理")
@RestController
@Slf4j
@RequestMapping("api/v1/attachment")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,15 @@
import cn.chenyunlong.qing.domain.anime.district.dto.vo.DistrictVO;
import cn.chenyunlong.qing.domain.anime.district.mapper.DistrictConverter;
import cn.chenyunlong.qing.domain.anime.district.service.IDistrictService;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.util.stream.Collectors;

@Tag(name = "地区管理")
@RestController
@Slf4j
@RequestMapping("api/v1/district")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
*
*/

package cn.chenyunlong.qing.domain.episode;
package cn.chenyunlong.qing.domain.anime.episode;

import cn.chenyunlong.common.annotation.FieldDesc;
import cn.chenyunlong.jpa.support.BaseJpaAggregate;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,25 +1,28 @@
package cn.chenyunlong.qing.domain.episode.controller;
package cn.chenyunlong.qing.domain.anime.episode.controller;

import cn.chenyunlong.common.constants.CodeEnum;
import cn.chenyunlong.common.model.JsonResult;
import cn.chenyunlong.common.model.PageRequestWrapper;
import cn.chenyunlong.common.model.PageResult;
import cn.chenyunlong.qing.domain.episode.dto.creator.EpisodeCreator;
import cn.chenyunlong.qing.domain.episode.dto.query.EpisodeQuery;
import cn.chenyunlong.qing.domain.episode.dto.request.EpisodeCreateRequest;
import cn.chenyunlong.qing.domain.episode.dto.request.EpisodeQueryRequest;
import cn.chenyunlong.qing.domain.episode.dto.request.EpisodeUpdateRequest;
import cn.chenyunlong.qing.domain.episode.dto.response.EpisodeResponse;
import cn.chenyunlong.qing.domain.episode.dto.updater.EpisodeUpdater;
import cn.chenyunlong.qing.domain.episode.dto.vo.EpisodeVO;
import cn.chenyunlong.qing.domain.episode.mapper.EpisodeMapper;
import cn.chenyunlong.qing.domain.episode.service.IEpisodeService;
import java.util.stream.Collectors;
import cn.chenyunlong.qing.domain.anime.episode.dto.creator.EpisodeCreator;
import cn.chenyunlong.qing.domain.anime.episode.dto.query.EpisodeQuery;
import cn.chenyunlong.qing.domain.anime.episode.dto.request.EpisodeCreateRequest;
import cn.chenyunlong.qing.domain.anime.episode.dto.request.EpisodeQueryRequest;
import cn.chenyunlong.qing.domain.anime.episode.dto.request.EpisodeUpdateRequest;
import cn.chenyunlong.qing.domain.anime.episode.dto.response.EpisodeResponse;
import cn.chenyunlong.qing.domain.anime.episode.dto.updater.EpisodeUpdater;
import cn.chenyunlong.qing.domain.anime.episode.dto.vo.EpisodeVO;
import cn.chenyunlong.qing.domain.anime.episode.mapper.EpisodeMapper;
import cn.chenyunlong.qing.domain.anime.episode.service.IEpisodeService;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.util.stream.Collectors;

@Tag(name = "单集管理")
@RestController
@Slf4j
@RequestMapping("api/v1/episode")
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package cn.chenyunlong.qing.domain.episode.dto.creator;
package cn.chenyunlong.qing.domain.anime.episode.dto.creator;

import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package cn.chenyunlong.qing.domain.episode.dto.query;
package cn.chenyunlong.qing.domain.anime.episode.dto.query;

import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package cn.chenyunlong.qing.domain.episode.dto.request;
package cn.chenyunlong.qing.domain.anime.episode.dto.request;

import cn.chenyunlong.common.model.Request;
import io.swagger.v3.oas.annotations.media.Schema;
Expand Down
Loading

0 comments on commit e1c612c

Please sign in to comment.