Skip to content

Commit

Permalink
oauth
Browse files Browse the repository at this point in the history
  • Loading branch information
dPwls0125 committed Feb 29, 2024
1 parent 6862aef commit 0335af7
Show file tree
Hide file tree
Showing 13 changed files with 330 additions and 256 deletions.
2 changes: 1 addition & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ dependencies {
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
implementation 'org.springframework.boot:spring-boot-starter-security'
// implementation "org.springframework.boot:spring-boot-starter-oauth2-client"
implementation "org.springframework.boot:spring-boot-starter-oauth2-client"
}

tasks.named('test') {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
package GDG.whatssue.domain.user.controller;

import GDG.whatssue.domain.user.dto.UserDto;
import GDG.whatssue.global.auth.PrincipalDetails;
import GDG.whatssue.domain.user.service.UserService;
//import GDG.whatssue.domain.user.entity.PrincipalDetails;
//import GDG.whatssue.domain.user.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
Expand All @@ -18,13 +18,13 @@
@Slf4j
@RequiredArgsConstructor
public class UserController {
private final UserService userService;
@PostMapping("/signUp")
@Operation(summary = "회원가입")
public ResponseEntity signUp(UserDto userDto) {
userService.signUp(userDto);
return ResponseEntity.status(200).body("회원가입 성공");
}
// private final UserService userService;
// @PostMapping("/signUp")
// @Operation(summary = "회원가입")
// public ResponseEntity signUp(UserDto userDto) {
// userService.signUp(userDto);
// return ResponseEntity.status(200).body("회원가입 성공");
// }
@Secured("ROLE_MANAGER")
@GetMapping("/manager")
public @ResponseBody String manager() {
Expand All @@ -39,9 +39,9 @@ public String index() {
return "index";
}

@GetMapping("/currentUser")
public ResponseEntity currentUser(@AuthenticationPrincipal PrincipalDetails principalDetails) {
UserDto userDto = userService.getUserInfo(principalDetails);
return ResponseEntity.status(200).body(userDto);
}
// @GetMapping("/currentUser")
// public ResponseEntity currentUser(@AuthenticationPrincipal PrincipalDetails principalDetails) {
// UserDto userDto = userService.getUserInfo(principalDetails);
// return ResponseEntity.status(200).body(userDto);
// }
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
//package GDG.whatssue.domain.user.entity;
//
//import GDG.whatssue.domain.member.entity.ClubMember;
//import GDG.whatssue.domain.user.entity.User;
//import GDG.whatssue.global.common.Role;
//import jakarta.transaction.Transactional;
//import lombok.Getter;
//import org.springframework.security.core.GrantedAuthority;
//import org.springframework.security.core.userdetails.UserDetails;
//
//import java.util.ArrayList;
//import java.util.Collection;
//import java.util.List;
//
///*
//* 시큐리티가 /login 주소 요청이 오면 낚아채서 로그인을 진행시킨다.
//* 로그인을 진행이 완료가 되면 시큐리티 session을 만들어준다. (Security ContextHolder)
//* 오브젝트 => Authentication 타입 객체
//* Authentication 안에 User 정보가 있어야 됨.
//* User 오브젝트 타입 => UserDetails 타입 객체
//*
//* Security Session => Authentication => UserDetails(PrincipalDetails)
// */
//@Getter
//@Transactional
//public class PrincipalDetails implements UserDetails {
//
// private User user;
//
// public PrincipalDetails(User user) {
// this.user = user;
// // 추가: 세션을 열고 연관된 엔티티를 즉시 로딩
// this.user.getClubMemberList().size();
// }
//
// @Override
// public Collection<? extends GrantedAuthority> getAuthorities() {
// List<ClubMember> clubMemberList = user.getClubMemberList();
// Collection<GrantedAuthority> authorities = new ArrayList<>();
// for (ClubMember clubMember : clubMemberList) {
// authorities.add((GrantedAuthority) () -> {
// Long clubId = clubMember.getClub().getId();
// Role role = clubMember.getRole();
// System.out.println("ROLE_" + clubId + role);
// return "ROLE_" + clubId + role;
// });
// }
// return authorities;
// }
//
// @Override
// public String getPassword() {
// return null;
// }
//
// @Override
// public String getUsername() {
// return user.getUserName();
// }
//
// @Override
// public boolean isAccountNonExpired() {
// return true;
// }
//
// @Override
// public boolean isAccountNonLocked() {
// return true;
// }
//
// @Override
// public boolean isCredentialsNonExpired() {
// return true;
// }
//
// @Override
// public boolean isEnabled() {
// // 우리 사이트 1년동안 회원이 로그인을 안하면 휴먼 계정으로 하기로 함.
// // 현재시간 - 로긴시간 => 1년을 초과하면 return false;
// return true;
// }
//}
30 changes: 18 additions & 12 deletions src/main/java/GDG/whatssue/domain/user/entity/User.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
import GDG.whatssue.domain.member.entity.ClubJoinRequest;
import GDG.whatssue.domain.member.entity.ClubMember;
import jakarta.persistence.*;

import java.util.ArrayList;
import java.util.List;

import lombok.*;
Expand All @@ -19,28 +21,32 @@ public class User extends BaseEntity {
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long userId;

@Column(nullable = false, unique = true)
private String userNick;
// @Column( unique = true, nullable = false)
// private String userNick;

@Column(nullable = false)
private String userPw;
// @Column
// private String userPw;

@Column(nullable = false)
private String userEmail;
// @Column
// private String userEmail;

@Column(nullable = false)
@Column
private String userName;

@Column(nullable = false)
private String userPhone;
// @Column
// private String userPhone;

@Column(nullable = false)
@Column
private String role;

@Column( nullable = false, unique = true)
private String oauth2Id;


@OneToMany(mappedBy = "user")
private List<ClubJoinRequest> clubJoinRequestList;
private List<ClubJoinRequest> clubJoinRequestList = new ArrayList<>();

@OneToMany(mappedBy = "user")
private List<ClubMember> clubMemberList;
private List<ClubMember> clubMemberList = new ArrayList<>();

}
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@
import GDG.whatssue.domain.user.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<User, Long> {
import java.util.Optional;

public User findByUserNick(String userNick);
public interface UserRepository extends JpaRepository<User, Long> {

// public User findByUserNick(String userNick);
public Optional<User> findByOauth2Id(String oauth2Id);

}
130 changes: 65 additions & 65 deletions src/main/java/GDG/whatssue/domain/user/service/UserService.java
Original file line number Diff line number Diff line change
@@ -1,65 +1,65 @@
package GDG.whatssue.domain.user.service;
import GDG.whatssue.domain.user.dto.UserDto;
import GDG.whatssue.global.auth.PrincipalDetails;
import GDG.whatssue.domain.user.entity.User;
import GDG.whatssue.domain.user.repository.UserRepository;
import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@RequiredArgsConstructor
@Service
@Slf4j
@Transactional
//시큐리티 설정에서 loginProcessingUrl("/login");
//login 요청이 오면 자동으로 UserDetailsService 타입으로 IoC되어있는 loadUserByUsername 함수가 실행
public class UserService implements UserDetailsService {

private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
public void signUp(UserDto userDto) {
User user = User.builder()
.userNick(userDto.getUserNick())
.userPw(userDto.getUserPw())
.userEmail(userDto.getUserEmail())
.userName(userDto.getUserName())
.userPhone(userDto.getUserPhone())
.role("ROLE_USER")
.build();
// 비밀번호 암호화 : 비밀번호 암호화가 안되어있으면 security로 로그인을 할 수 없음.
user.setUserPw(passwordEncoder.encode(user.getUserPw()));
userRepository.save(user);
}
@Override
@Transactional
public UserDetails loadUserByUsername(String userName) {
User user = userRepository.findByUserNick(userName);

if(userRepository.findByUserNick(userName) == null)
return null;

PrincipalDetails userDetails = new PrincipalDetails(user);
System.out.println("로그인 완료");
return userDetails;

// UserDetails가 return이 되면 시큐리티 session의 Authentication의 내부에 userDetail이 저장이 된다.
// Session(내부 Authentication(내부 UserDetails))
}

public UserDto getUserInfo(PrincipalDetails principalDetails) {
User user = principalDetails.getUser();
return UserDto.builder()
.userNick(user.getUserNick())
.userPw(user.getUserPw())
.userEmail(user.getUserEmail())
.userName(user.getUserName())
.userPhone(user.getUserPhone())
.build();
}


}
//package GDG.whatssue.domain.user.service;
//import GDG.whatssue.domain.user.dto.UserDto;
//import GDG.whatssue.domain.user.entity.PrincipalDetails;
//import GDG.whatssue.domain.user.entity.User;
//import GDG.whatssue.domain.user.repository.UserRepository;
//import jakarta.transaction.Transactional;
//import lombok.RequiredArgsConstructor;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.security.core.userdetails.UserDetailsService;
//import org.springframework.security.core.userdetails.UserDetails;
//import org.springframework.security.crypto.password.PasswordEncoder;
//import org.springframework.stereotype.Service;
//
//@RequiredArgsConstructor
//@Service
//@Slf4j
//@Transactional
////시큐리티 설정에서 loginProcessingUrl("/login");
////login 요청이 오면 자동으로 UserDetailsService 타입으로 IoC되어있는 loadUserByUsername 함수가 실행
//public class UserService implements UserDetailsService {
//
// private final UserRepository userRepository;
// private final PasswordEncoder passwordEncoder;
// public void signUp(UserDto userDto) {
// User user = User.builder()
//// .userNick(userDto.getUserNick())
//// .userPw(userDto.getUserPw())
//// .userEmail(userDto.getUserEmail())
// .userName(userDto.getUserName())
//// .userPhone(userDto.getUserPhone())
// .role("ROLE_USER")
// .build();
// // 비밀번호 암호화 : 비밀번호 암호화가 안되어있으면 security로 로그인을 할 수 없음.
// user.setUserPw(passwordEncoder.encode(user.getUserPw()));
// userRepository.save(user);
// }
// @Override
// @Transactional
// public UserDetails loadUserByUsername(String userName) {
// User user = userRepository.findByUserNick(userName);
//
// if(userRepository.findByUserNick(userName) == null)
// return null;
//
// PrincipalDetails userDetails = new PrincipalDetails(user);
// System.out.println("로그인 완료");
// return userDetails;
//
// // UserDetails가 return이 되면 시큐리티 session의 Authentication의 내부에 userDetail이 저장이 된다.
// // Session(내부 Authentication(내부 UserDetails))
// }
//
// public UserDto getUserInfo(PrincipalDetails principalDetails) {
// User user = principalDetails.getUser();
// return UserDto.builder()
// .userNick(user.getUserNick())
// .userPw(user.getUserPw())
// .userEmail(user.getUserEmail())
// .userName(user.getUserName())
// .userPhone(user.getUserPhone())
// .build();
// }
//
//
//}
Loading

0 comments on commit 0335af7

Please sign in to comment.