Skip to content

Commit

Permalink
패스워드 인코더/커뮤니티 추천수
Browse files Browse the repository at this point in the history
시큐리티에서 패스워드 인코더 오류로 로그인 안되는 문제와 커뮤니티 추천수 메소드 생성
  • Loading branch information
duhwan05 committed Aug 13, 2024
1 parent cf75d00 commit ee1244b
Show file tree
Hide file tree
Showing 8 changed files with 90 additions and 132 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,12 @@
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
public class PasswordEncoderConfig {

//비밀번호 암호화 작업
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}

15 changes: 14 additions & 1 deletion src/main/java/com/example/healthylife/config/SecurityConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@

import com.example.healthylife.config.jwt.JwtAuthenticationFilter;
import com.example.healthylife.config.jwt.JwtUtil;
import com.example.healthylife.config.security.MyUserDetailsService;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

Expand All @@ -17,6 +18,8 @@
public class SecurityConfig extends WebSecurityConfigurerAdapter {

private final JwtUtil jwtUtil;
private final MyUserDetailsService myUserDetailsService;
private final PasswordEncoder passwordEncoder;

@Override
protected void configure(HttpSecurity http) throws Exception {
Expand All @@ -32,6 +35,16 @@ protected void configure(HttpSecurity http) throws Exception {
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
// AuthenticationManager를 빈으로 등록하여 인증 관련 작업을 수행할 수 있도록 설정
return super.authenticationManagerBean();
}

@Bean
public DaoAuthenticationProvider authenticationProvider() {
// DaoAuthenticationProvider를 설정하여 사용자 세부 정보와 비밀번호 암호화 설정을 Spring Security에 통합
DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
authProvider.setUserDetailsService(myUserDetailsService); // 사용자 세부 정보를 제공하는 서비스 설정
authProvider.setPasswordEncoder(passwordEncoder); // 비밀번호 암호화 설정
return authProvider;
}
}
40 changes: 4 additions & 36 deletions src/main/java/com/example/healthylife/config/SwaggerConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,37 +20,19 @@
@Configuration
@EnableSwagger2
public class SwaggerConfig {

@Bean
public Docket api() {
return new Docket(DocumentationType.OAS_30)
// .consumes(getConsumeContentTypes())
// .produces(getProduceContentTypes())
.apiInfo(getApiInfo())
.useDefaultResponseMessages(false)
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.healthylife"))
.paths(PathSelectors.ant("/**"))
.paths(PathSelectors.any())
.build()
.pathMapping("/")
// .host("localhost:8081")
.securityContexts(List.of(securityContext()))
.securitySchemes(List.of(apiKey()));

.apiInfo(getApiInfo());

}

// private Set<String> getConsumeContentTypes() {
// Set<String> consumes = new HashSet<>();
// consumes.add("application/json;charset=UTF-8");
// consumes.add("application/x-www-form-urlencoded");
// return consumes;
// }
//
// private Set<String> getProduceContentTypes() {
// Set<String> produces = new HashSet<>();
// produces.add("application/json;charset=UTF-8");
// return produces;
// }

private ApiInfo getApiInfo() {
return new ApiInfoBuilder()
.title("API")
Expand All @@ -59,20 +41,6 @@ private ApiInfo getApiInfo() {
.version("1.0")
.build();
}
private SecurityScheme apiKey() {
return new ApiKey("Authorization", "Authorization", "header");
}

private SecurityContext securityContext() {
return SecurityContext.builder()
.securityReferences(defaultAuth())
.build();
}
private List<SecurityReference> defaultAuth() {
AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
return List.of(new SecurityReference("Authorization", authorizationScopes));
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,10 @@ public class CommunityController {
@ApiOperation(value = "커뮤니티 글 전체 조회")
@GetMapping("/all")
public List<CommunityEntity> communityList() {
// validate
// (http)param binding
// service call
List<CommunityEntity> communityEntities = communityService.communityList();
// return result
return communityEntities;
}


//커뮤니티 단일조회 (userId가지고 내가 쓴 글 조회)
@ApiOperation(value = "커뮤니티 내가 쓴 글 조회")
@GetMapping("/myCommunityContents")
public ResponseEntity<List<CommunityEntity>> myCommunityContentsList(@RequestHeader("Authorization") String authorizationHeader) {
Expand All @@ -56,20 +50,19 @@ public CommunityEntity register(@RequestBody CommunityEntity communityEntity) {
}

@ApiOperation(value = "커뮤니티 글 수정")
@PostMapping("/update")
@PutMapping("/update")
public CommunityEntity update(@RequestBody CommunityEntity communityEntity) {
return communityService.updateCommunity(communityEntity);
}


@ApiOperation(value = "커뮤니티 글 삭제")
@PostMapping("/delete")
public Boolean delete(@RequestParam long communitySq) {
@DeleteMapping("/delete/{communitySq}")
public ResponseEntity<Void> delete(@PathVariable("communitySq") Long communitySq) {
communityService.deleteBySq(communitySq);
return true;
return ResponseEntity.noContent().build();
}

@ApiOperation(value = "커뮤니티 단일조회")
@ApiOperation(value = "커뮤니티 상세보기")
@GetMapping("/communityDetail/{communitySq}")
public ResponseEntity<CommunityEntity> getCommunityBySq(@PathVariable("communitySq") Long communitySq) {
try {
Expand All @@ -80,13 +73,18 @@ public ResponseEntity<CommunityEntity> getCommunityBySq(@PathVariable("community
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
} catch (Exception e) {
// 로그를 남기거나 필요한 조치를 취합니다
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}

// 커뮤니티 글 조회수
@ApiOperation(value = "커뮤니티 글 추천")
@ApiOperation(value = "커뮤니티 글 추천수")
@PostMapping("/recommend/{sq}")
public ResponseEntity<?> communityRecommend(@PathVariable("sq") Long sq) {
long updatedCount = communityService.toggleRecommendation(sq);
return ResponseEntity.ok(updatedCount);
}

@ApiOperation(value = "커뮤니티 글 조회수")
@PostMapping("/view/{sq}")
public ResponseEntity<Void> Communityview(@PathVariable("sq") Long sq) {
communityService.incrementview(sq);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
Expand Down Expand Up @@ -61,38 +60,30 @@ public ResponseEntity<String> authenticate(@RequestBody LoginRequest loginReques
}
}

@GetMapping("/refresh")
public ResponseEntity<String> refresh(@RequestParam("refresh-token") String refreshToken){
try {
String accessToken = jwtAuthService.refresh(refreshToken);
//사용자 이름(아이디)과 비번으로 인증


Map result = Map.of("access-token", accessToken,
"refresh-token", refreshToken);

//생성된 토큰을 ResponseEntity로 반환
return ResponseEntity.ok()
.body(objectMapper.writeValueAsString(result));
} catch (Exception e) {
log.error("refresh failed! - refresh-token: {}", refreshToken, e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("Exception : " + e.getMessage());
}

}
// 현재 사용안함
// @GetMapping("/refresh")
// public ResponseEntity<String> refresh(@RequestParam("refresh-token") String refreshToken){
// try {
// String accessToken = jwtAuthService.refresh(refreshToken);
// //사용자 이름(아이디)과 비번으로 인증
//
//
// Map result = Map.of("access-token", accessToken,
// "refresh-token", refreshToken);
//
// //생성된 토큰을 ResponseEntity로 반환
// return ResponseEntity.ok()
// .body(objectMapper.writeValueAsString(result));
// } catch (Exception e) {
// log.error("refresh failed! - refresh-token: {}", refreshToken, e);
// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
// .body("Exception : " + e.getMessage());
// }
//
// }


@ApiOperation("로그아웃 컨트롤러")
@GetMapping("/logout")
public ResponseEntity<String> logout(@RequestParam("username") String username) {
// 클라이언트 측에서 토큰을 삭제하도록 처리
// response.setHeader("Set-Cookie", "accessToken=; HttpOnly; Path=/; Max-Age=0");
// response.setHeader("Set-Cookie", "refreshToken=; HttpOnly; Path=/; Max-Age=0");
jwtAuthService.logout(username);

return ResponseEntity.ok().body("Logout Successful");
}


}
13 changes: 10 additions & 3 deletions src/main/java/com/example/healthylife/entity/CommunityEntity.java
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public class CommunityEntity implements Serializable {
private String communityTitle;

//글내용
@Column(name = "community_contents",length = 500)
@Column(name = "community_contents",length = 1000)
private String communityContents;

//커뮤니티 게시글 작성일
Expand All @@ -37,7 +37,7 @@ public class CommunityEntity implements Serializable {

//커뮤니티 글 조회수
//communityview
@Column(name = "communityview", length = 200 )
@Column(name = "community_view", length = 200 )
private int communityview;

//커뮤니티 글 추천수
Expand Down Expand Up @@ -67,7 +67,14 @@ public CommunityEntity(long communitySq, String communityTitle, String community
this.user = user;
}


// 추천수
public void toggleRecommendation(boolean currentlyRecommended) {
if (currentlyRecommended) {
this.communityRecommend--;
} else {
this.communityRecommend++;
}
}


}
30 changes: 13 additions & 17 deletions src/main/java/com/example/healthylife/service/CommunityService.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
public class CommunityService {

private final CommunityRepository communityRepository;
private final UserRepository userRepository;
private final CommunityCommentsService communityCommentsService;


Expand All @@ -26,26 +25,23 @@ public List<CommunityEntity> communityList() {
return communityRepository.findAll();
}


//커뮤니티 글 작성
public CommunityEntity registerCommunity(CommunityEntity communityEntity) {
return communityRepository.save(communityEntity);
}


//커뮤니티 글 수정
@Transactional
public CommunityEntity updateCommunity(CommunityEntity communityEntity) {

return communityRepository.save(communityEntity);
}

//커뮤니티 글 삭제
public void deleteBySq(long communitySq) {

communityRepository.deleteById(communitySq);
}

//커뮤니티 내가 쓴글 조회
public List<CommunityEntity> findMyContents(String userId) {
return communityRepository.findByUserUserId(userId);
}
Expand All @@ -60,6 +56,18 @@ public Optional<CommunityEntity> findCommunityBySq(Long communitySq) {
return community;
}

//커뮤니티 추천수
@Transactional
public long toggleRecommendation(Long sq) {
CommunityEntity community = communityRepository.findById(sq)
.orElseThrow(() -> new RuntimeException("커뮤니티가 없습니다."));

boolean isRecommended = community.getCommunityRecommend() > 0;
community.toggleRecommendation(isRecommended);
CommunityEntity updatedCommunity = communityRepository.save(community);
return updatedCommunity.getCommunityRecommend();
}

// 커뮤니티 조회수
@Transactional
public void incrementview(Long communitySq) {
Expand All @@ -69,15 +77,3 @@ public void incrementview(Long communitySq) {

}


//커뮤니티 내가 쓴 글 조회
// @Override
// public List<CommunityEntity> findMyContents(long userSq) {
// return communityRepository.findByUserUserId(userSq);
// }






Loading

0 comments on commit ee1244b

Please sign in to comment.