Skip to content

Commit

Permalink
Feat: User Login & Join
Browse files Browse the repository at this point in the history
  • Loading branch information
su-hwani committed May 28, 2024
1 parent dc588a4 commit fc13dbf
Show file tree
Hide file tree
Showing 5 changed files with 143 additions and 49 deletions.
5 changes: 5 additions & 0 deletions server/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,11 @@ dependencies {
implementation 'org.springframework.kafka:spring-kafka'
implementation 'org.hibernate:hibernate-spatial:6.4.4.Final'
implementation 'net.nurigo:sdk:4.2.7' //sms 발송 관련 sdk
implementation 'org.springframework.boot:spring-boot-starter-security' // login
implementation 'io.jsonwebtoken:jjwt:0.9.1' // JWT
implementation 'com.sun.xml.bind:jaxb-impl:4.0.1' // com.sun.xml.bind
implementation 'com.sun.xml.bind:jaxb-core:4.0.1' // com.sun.xml.bind
implementation 'javax.xml.bind:jaxb-api:2.4.0-b180830.0359' // javax.xml.bind
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package com.capstone.server.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.capstone.server.dto.login.JoinRequestDto;
import com.capstone.server.dto.login.LoginRequestDto;
import com.capstone.server.dto.login.LoginResponseDto;
import com.capstone.server.model.UserEntity;
import com.capstone.server.response.SuccessResponse;
import com.capstone.server.service.JwtTokenService;
import com.capstone.server.service.UserService;

import lombok.RequiredArgsConstructor;

@RestController
@RequiredArgsConstructor
@RequestMapping("/api/user")
public class JwtLoginApiController {
@Value("${jwt.secretKey}")
private String secretKey;
@Value("${jwt.expireTime}")
private long expireTime;

@Autowired
private UserService userService;
@Autowired
private JwtTokenService jwtTokenService;

@PostMapping("/join")
public ResponseEntity<?> join(@RequestBody JoinRequestDto joinRequestDto) {

// loginId 중복 체크
userService.checkLoginIdDuplicate(joinRequestDto.getLoginId());

// 회원가입
userService.join(joinRequestDto);
return ResponseEntity.ok().body(new SuccessResponse("Join Success"));
}

@PostMapping("/login")
public ResponseEntity<?> login(@RequestBody LoginRequestDto loginRequestDto) {
// 로그인
UserEntity user = userService.login(loginRequestDto);

// Jwt Token 발급
String jwtToken = jwtTokenService.createToken(user.getLoginId(), secretKey, expireTime);

LoginResponseDto loginResponseDto = new LoginResponseDto(user, jwtToken);
return ResponseEntity.ok().body(new SuccessResponse(loginResponseDto));
}

@GetMapping("/info")
public ResponseEntity<?> userInfo(Authentication auth) {
UserEntity loginUser = userService.getLoginUserByLoginId(auth.getName());

return ResponseEntity.ok().body(new SuccessResponse(String.format("loginId : %s, role : %s",
loginUser.getLoginId(), loginUser.getRole().name())));
}
}
48 changes: 17 additions & 31 deletions server/src/main/java/com/capstone/server/model/UserEntity.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.capstone.server.model;

import com.capstone.server.model.enums.UserRole;
import com.capstone.server.model.enums.userEnum;
import jakarta.persistence.*;
import lombok.AllArgsConstructor;
Expand All @@ -17,50 +18,35 @@
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Entity(name = "test_user")
@Entity(name = "users")
@EntityListeners(AuditingEntityListener.class)
public class UserEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "user_id")
private Long id;

@Column(name = "login_id", nullable = false)
private String loginId;

private String name;
@Column(nullable = false)
private String password;

@Enumerated(EnumType.STRING)
@Column(name = "role", nullable = false)
private UserRole role;

private Integer age;


private String email;

private BigDecimal latitude;

private BigDecimal longitude;

private userEnum userEnum;


private Date createdAt;


private Date updatedAt;

@CreatedDate
private LocalDateTime localDate;


private LocalDateTime whenCreatedAt;
private LocalDateTime createdAt;
private LocalDateTime updatedAt;

@PrePersist
protected void onCreate() {
createdAt = new Date();
updatedAt = new Date();
localDate = LocalDateTime.now();
createdAt = LocalDateTime.now();
updatedAt = LocalDateTime.now();
}

@PreUpdate // 업데이트가 발생할 때 호출되는 메소드
@PreUpdate
protected void onUpdate() {
updatedAt = new Date();
updatedAt = LocalDateTime.now();
}

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,11 @@
import org.springframework.data.jpa.repository.JpaRepository;

import com.capstone.server.model.UserEntity;
import java.util.List;
import java.util.Optional;

public interface UserRepository extends JpaRepository<UserEntity, Long>{

public interface UserRepository extends JpaRepository<UserEntity, Long>{
boolean existsByLoginId(String loginId);
Optional<UserEntity> findByLoginId(String loginId);
}
66 changes: 49 additions & 17 deletions server/src/main/java/com/capstone/server/service/UserService.java
Original file line number Diff line number Diff line change
@@ -1,42 +1,74 @@
package com.capstone.server.service;

import java.util.List;
import java.util.Map;
import java.util.Optional;

import org.postgresql.shaded.com.ongres.scram.common.message.ServerFinalMessage.Error;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.capstone.server.code.ErrorCode;
import com.capstone.server.dto.UserUpdateRequestDto;
import com.capstone.server.dto.login.JoinRequestDto;
import com.capstone.server.dto.login.LoginRequestDto;
import com.capstone.server.exception.CustomException;
import com.capstone.server.model.UserEntity;
import com.capstone.server.model.enums.UserRole;
import com.capstone.server.repository.UserRepository;

@Service
public class UserService {
@Autowired
private UserRepository userRepository;
@Autowired
private PasswordEncoder passwordEncoder;
@Value("${admin.loginId}")
private String adminLoginId;

public UserEntity createUser(UserEntity userEntity) {
try {
return userRepository.save(userEntity);
} catch (Exception e) {
throw new CustomException(ErrorCode.USER_EXISTS, e);
// 중복된 ID 체크
public void checkLoginIdDuplicate(String loginId) {

if (userRepository.existsByLoginId(loginId)) {
throw new CustomException(ErrorCode.DUPLICATE_USER_LOGIN_ID);
}
}

public List<UserEntity> getAllUsers() {
return userRepository.findAll();
// 회원가입
@Transactional
public UserEntity join(JoinRequestDto joinRequestDto) {
if (!joinRequestDto.getLoginId().contains(adminLoginId)) {
throw new CustomException(ErrorCode.USER_NOT_ADMIN);
}
UserEntity user = userRepository.save(joinRequestDto.toEntity(passwordEncoder.encode(joinRequestDto.getPassword())));

user.setRole(UserRole.ADMIN);
return user;
}

public UserEntity updateUserNameById(Long userId, UserUpdateRequestDto userUpdateRequestDto) {
Optional<UserEntity> existingUserOptional = userRepository.findById(userId);
if (existingUserOptional.isPresent()) {
UserEntity existingUser = existingUserOptional.get();
existingUser.setName(userUpdateRequestDto.getName());
return userRepository.save(existingUser);
} else {
// 로그인
public UserEntity login(LoginRequestDto loginRequestDto) {
Optional<UserEntity> optionalUser = userRepository.findByLoginId(loginRequestDto.getLoginId());
if (optionalUser.isEmpty()) {
throw new CustomException(ErrorCode.USER_NOT_FOUND);
}

UserEntity user = optionalUser.get();

if (!passwordEncoder.matches(loginRequestDto.getPassword(), user.getPassword())) {
throw new CustomException(ErrorCode.USER_NOT_MATCH_PASSWORD);
}

return user;
}

// user 찾기
public UserEntity getLoginUserByLoginId(String loginId) {
if (loginId == null) return null;

Optional<UserEntity> optionalUser = userRepository.findByLoginId(loginId);
if (optionalUser.isEmpty()) return null;

return optionalUser.get();
}
}

0 comments on commit fc13dbf

Please sign in to comment.