Skip to content

Commit

Permalink
chore: beta
Browse files Browse the repository at this point in the history
  • Loading branch information
bs32g1038 committed Apr 21, 2024
1 parent 9aa0941 commit d3a29fa
Show file tree
Hide file tree
Showing 39 changed files with 495 additions and 239 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,6 @@ public class MyWebMvcConfig implements WebMvcConfigurer {
public void addResourceHandlers(ResourceHandlerRegistry registry) {
System.out.println(getJarFilePath());
System.out.println("getJarFilePath()");
registry.addResourceHandler("/static/**").addResourceLocations("file:" + getJarFilePath() + "/static/");
registry.addResourceHandler("/static/**").addResourceLocations("file:" + getJarFilePath() + "/static/").addResourceLocations("file:" + getJarFilePath() + "/classes/static/");
}
}
14 changes: 9 additions & 5 deletions server/src/main/java/com/jixialunbi/config/SecurityConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import com.jixialunbi.security.AuthTokenFilter;
import com.jixialunbi.service.UserDetailsServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
Expand Down Expand Up @@ -37,7 +38,9 @@ public class SecurityConfig {
"/swagger-ui.html"
};
private final UserDetailsServiceImpl userDetailsService;
private final AuthEntryPointJwt authEntryPointJwt;

@Autowired
private AuthEntryPointJwt unauthorizedHandler;

@Bean
public AuthTokenFilter authenticationJwtTokenFilter() {
Expand All @@ -49,6 +52,7 @@ public DaoAuthenticationProvider authenticationProvider() {
final DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
authProvider.setUserDetailsService(userDetailsService);
authProvider.setPasswordEncoder(passwordEncoder());
authProvider.setHideUserNotFoundExceptions(false);
return authProvider;
}

Expand All @@ -67,11 +71,11 @@ public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Excepti
httpSecurity
.cors().and()
.csrf().disable()
.exceptionHandling().authenticationEntryPoint(authEntryPointJwt).and()
.exceptionHandling(exception -> exception.authenticationEntryPoint(unauthorizedHandler))
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeHttpRequests()
.requestMatchers(AUTH_WHITELIST).permitAll()
.anyRequest().authenticated();
.authorizeHttpRequests(auth ->
auth.requestMatchers(AUTH_WHITELIST).permitAll().anyRequest().authenticated()
);

httpSecurity.authenticationProvider(authenticationProvider());
httpSecurity.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
Expand Down
25 changes: 10 additions & 15 deletions server/src/main/java/com/jixialunbi/controllers/PostController.java
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
package com.jixialunbi.controllers;

import cn.hutool.core.util.StrUtil;
import com.jixialunbi.common.R;
import com.jixialunbi.common.utils.PageUtil;
import com.jixialunbi.dto.request.IdRequest;
import com.jixialunbi.dto.request.PostRequest;
import com.jixialunbi.model.*;
import com.jixialunbi.repository.*;
import com.jixialunbi.security.UserDetailsImpl;
import com.jixialunbi.service.CategoryService;
import com.jixialunbi.service.FollowUserService;
import com.jixialunbi.service.UserService;
Expand All @@ -23,14 +23,14 @@
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;

import static io.jsonwebtoken.lang.Collections.isEmpty;

Expand Down Expand Up @@ -87,19 +87,13 @@ public R fetchPosts(
@RequestParam(required = false, defaultValue = "0") int page,
@RequestParam(required = false, defaultValue = "10") int pageSize,
@RequestParam(required = false) Long categoryId,
@RequestParam(required = false) String account,
@RequestParam(required = false) Long userId,
@RequestParam(required = false, defaultValue = "false") boolean isHot,
Principal principal
) {
User user;
if (principal == null) {
user = null;
} else {
user = userService.getByAccount(principal.getName());
}
@AuthenticationPrincipal UserDetailsImpl userDetails
) {
Long authorId = null;
if (account != null) {
authorId = userService.getByAccount(account).getId();
if (userId != null) {
authorId = userService.getById(userId.longValue()).getId();
}
List<Sort.Order> orders = new ArrayList<Sort.Order>();
if (isHot) {
Expand Down Expand Up @@ -132,7 +126,7 @@ public Predicate toPredicate(Root<Post> root, CriteriaQuery<?> query, CriteriaBu
arr.toList().forEach(postId -> {
var a = test.getContent().get(i[0]);
String regex = "<.*?>";
if(a.getContent() != null){
if (a.getContent() != null) {
a.setContent(a.getContent().replaceAll(regex, ""));
}
// 组合评论数据
Expand All @@ -150,7 +144,8 @@ public Predicate toPredicate(Root<Comment> root, CriteriaQuery<?> query, Criteri
return item.getAuthor();
}).toList());
// 点赞数据,收藏数据
if (user != null) {
if (userDetails != null) {
User user = userService.getById(userDetails.getId());
var like = postLikeRepository.findOneByPostIdAndAuthorId(postId, user.getId());
a.setLiked(like != null && like.getDeleted() == null);
var cn = postCollectionRepository.findOneByPostIdAndAuthorId(postId, user.getId());
Expand Down
41 changes: 19 additions & 22 deletions server/src/main/java/com/jixialunbi/controllers/UserController.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import com.jixialunbi.enums.HttpReponseResultCodeEnum;
import com.jixialunbi.model.User;
import com.jixialunbi.repository.UserRepository;
import com.jixialunbi.security.UserDetailsImpl;
import com.jixialunbi.service.FollowUserService;
import com.jixialunbi.service.UserService;
import jakarta.validation.Valid;
Expand All @@ -14,11 +15,9 @@
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;


@RestController
@RequestMapping("/api/v1")
public class UserController {
Expand Down Expand Up @@ -48,34 +47,33 @@ public R fetchUsers(@RequestParam int page, @RequestParam int pageSize) {

@PreAuthorize("hasRole('ROLE_USER')")
@GetMapping("/login-user-info")
public R loginUserInfo(Principal principal) {
return R.ok().data(userRepository.findByAccount(principal.getName()));
public R loginUserInfo(@AuthenticationPrincipal UserDetailsImpl userDetails) {
return R.ok().data(userRepository.findById(userDetails.getId()));
}

@PostMapping("/user/create")
public R create(@Valid @RequestBody UserRequest request) {
if (userRepository.existsByUsernameIgnoreCase(request.getAccount())) {
return R.error().message("用户名已存在!");
if (userRepository.existsByEmailIgnoreCase(request.getEmail())) {
return R.error().message("用户已存在!");
}
return R.ok().data(userService.create(request));
}

@GetMapping("/user-info/{account}")
public R getUserInfo(@PathVariable String account, Principal principal) {
if (principal == null) {
var user = userRepository.findByAccount(account);
@GetMapping("/user-info/{id}")
public R getUserInfo(@PathVariable Long id, @AuthenticationPrincipal UserDetailsImpl userDetails) {
if (userDetails == null) {
var user = userRepository.findById(id);
return R.ok().data(user);
}
var login_user = userService.getByAccount(principal.getName());
var user = userRepository.findByAccount(account);
boolean followed = followUserService.isFollow(login_user.getId(), user.get().getId());
user.get().setFollowed(followed);
User user = userService.getById(id);
boolean followed = followUserService.isFollow(userDetails.getId(), id);
user.setFollowed(followed);
return R.ok().data(user);
}

@PostMapping("/user/update")
public R update(@Valid @RequestBody UserUpdateRequest request, Principal principal) {
var user = userService.getByAccount(principal.getName());
public R update(@Valid @RequestBody UserUpdateRequest request, @AuthenticationPrincipal UserDetailsImpl userDetails) {
var user = userService.getById(userDetails.getId());
if (request.getImage() != null) {
user.setImage(request.getImage());
}
Expand All @@ -92,11 +90,10 @@ public R update(@Valid @RequestBody UserUpdateRequest request, Principal princip
return R.ok().data(true);
}

@PostMapping("/follow-user/{account}")
public R followUser(@PathVariable String account, Principal principal) {
var user = userService.getByAccount(principal.getName());
var followUser = userService.getByAccount(account);
boolean res = followUserService.followUser(user.getId(), followUser.getId());
@PreAuthorize("hasRole('ROLE_USER')")
@PostMapping("/follow-user/{userId}")
public R followUser(@PathVariable Long userId, @AuthenticationPrincipal UserDetailsImpl userDetails) {
boolean res = followUserService.followUser(userDetails.getId(), userId);
return R.ok().data(res);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,7 @@
public class LoginRequest {

@NotBlank
@Size(min = 3, max = 20)
private String account;
private String email;

@NotBlank
@Size(min = 6, max = 100)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ public class UserRequest {
private Long id;

@NotBlank
@Size(min = 3, max = 20)
private String account;
@Size(min = 6, max = 40)
private String email;

@NotBlank
@Size(min = 6, max = 100)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,6 @@ public class JwtResponse {
private String token;
private Long id;
private String username;
private String email;
private List<String> roles;
}
2 changes: 0 additions & 2 deletions server/src/main/java/com/jixialunbi/model/Tag.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,7 @@

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Getter
@Setter
Expand Down
2 changes: 1 addition & 1 deletion server/src/main/java/com/jixialunbi/model/User.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
public class User {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@JsonFormat(shape = JsonFormat.Shape.STRING)
private long id;

@Column(name = "account")
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package com.jixialunbi.repository;

import com.jixialunbi.model.Category;
import com.jixialunbi.model.Tag;
import org.springframework.data.jpa.repository.JpaRepository;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,16 @@
@Repository
public interface UserRepository extends JpaRepository<User, Long> {

boolean existsByUsernameIgnoreCase(String name);
boolean existsByEmailIgnoreCase(String name);

Optional<User> findByUsername(String username);

Optional<User> findByAccount(String account);

Optional<User> findByEmail(String account);

Optional<User> findById(String id);

@Transactional
@Modifying
@Query("update User p set p.followCount = p.followCount + :followCount where p.id = :id")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
Expand All @@ -14,18 +15,15 @@
import java.util.HashMap;
import java.util.Map;

/**
* Implements AuthenticationEntryPoint interface that is used for catching authentication errors
*/
@Slf4j(topic = "AuthEntryPointJwt")
@Component
public class AuthEntryPointJwt implements AuthenticationEntryPoint {

private static final Logger logger = LoggerFactory.getLogger(AuthEntryPointJwt.class);

@Override
public void commence(HttpServletRequest request,
HttpServletResponse response,
AuthenticationException authException) throws IOException, ServletException {
log.error("Unauthorized error: {}", authException.getMessage());
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException)
throws IOException, ServletException {
logger.error("Unauthorized error: {}", authException.getMessage());

response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
Expand All @@ -39,4 +37,5 @@ public void commence(HttpServletRequest request,
final ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(response.getOutputStream(), body);
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,11 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
try {
String jwt = parseJwt(request);
if (jwt != null && jwtUtils.validateJwtToken(jwt)) {
final String username = jwtUtils.getUsernameFromJwtToken(jwt);
if (username == null) {
final String email = jwtUtils.getUsernameFromJwtToken(jwt);
if (email == null) {
return;
}
final UserDetails userDetails = userDetailsService.loadUserByUsername(username);
final UserDetails userDetails = userDetailsService.loadUserByUsername(email);
final UsernamePasswordAuthenticationToken authentication =
new UsernamePasswordAuthenticationToken(
userDetails,
Expand Down
2 changes: 1 addition & 1 deletion server/src/main/java/com/jixialunbi/security/JwtUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public class JwtUtils {
public String generateJwtToken(Authentication authentication) {
final UserDetailsImpl userPrincipal = (UserDetailsImpl) authentication.getPrincipal();
return Jwts.builder()
.setSubject((userPrincipal.getUsername()))
.setSubject((userPrincipal.getEmail()))
.setIssuedAt(new Date())
.setExpiration(new Date((new Date()).getTime() + jwtExpirationMs))
.signWith(SignatureAlgorithm.HS512, jwtSecret)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package com.jixialunbi.security;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class MyAccessDeniedHandler implements AuthenticationFailureHandler {
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json");
response.getWriter().println("禁止访问");
response.getWriter().flush();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

@Getter
@AllArgsConstructor
@EqualsAndHashCode(of = {"username"})
@EqualsAndHashCode(of = {"id"})
public class UserDetailsImpl implements UserDetails {

private static final long serialVersionUID = 1L;
Expand All @@ -23,6 +23,8 @@ public class UserDetailsImpl implements UserDetails {

private String username;

private String email;

@JsonIgnore
private String password;

Expand All @@ -36,6 +38,7 @@ public static UserDetailsImpl build(User user) {
return new UserDetailsImpl(
user.getId(),
user.getUsername(),
user.getEmail(),
user.getPassword(),
authorities);
}
Expand Down
Loading

0 comments on commit d3a29fa

Please sign in to comment.