본문 바로가기
프레임워크/스프링

[Spring] Spring Boot, React, Redux 회원가입 구현 (백엔드)

by Yikanghee 2022. 4. 26.
  • 백엔드
    • domain
    package com.mobee.movie.domain;
    
    import lombok.*;
    import org.springframework.data.annotation.CreatedDate;
    import org.springframework.data.annotation.LastModifiedDate;
    import org.springframework.data.jpa.domain.support.AuditingEntityListener;
    import javax.persistence.*;
    import java.time.LocalDateTime;
    import java.util.*;
    
    @Entity
    @EqualsAndHashCode(of = "id")
    @Getter
    @Setter
    @Builder
    @AllArgsConstructor
    @NoArgsConstructor
    @EntityListeners(AuditingEntityListener.class)
    public class Account {
    
        @Id
        @GeneratedValue
        private Long id;
    
        @Column(unique = true)
        private String username;
    
        @Column(nullable = false)
        private String password;
    
        @CreatedDate
        private LocalDateTime createdAt;
    
        @LastModifiedDate
        private LocalDateTime modifiedAt;
    
        public Account(String username, String password) {
            this.username = username;
            this.password = password;
        }
    
        @ElementCollection(fetch = FetchType.EAGER)
        @Builder.Default
        private List<String> roles = new ArrayList<>();
    
    }
    
    • DTO
    package com.mobee.movie.dto;
    
    import lombok.Getter;
    
    @Getter
    public class AccountRequestDto {
    
        private String username;
    
        private String password;
    
        private String passwordConfirm;
    }
    
    • Repository
    package com.mobee.movie.repository;
    
    import com.mobee.movie.domain.Account;
    import org.springframework.data.jpa.repository.JpaRepository;
    
    import java.util.Optional;
    
    public interface AccountRepository extends JpaRepository<Account, Long> {
        Optional<Account> findByUsername(String username);
    }
    
    • Controller
    package com.mobee.movie.controller;
    
    import com.google.gson.JsonObject;
    import com.mobee.movie.config.JwtTokenProvider;
    import com.mobee.movie.domain.Account;
    import com.mobee.movie.dto.AccountRequestDto;
    import com.mobee.movie.repository.AccountRepository;
    import com.mobee.movie.service.AccountService;
    import lombok.RequiredArgsConstructor;
    
    import org.springframework.http.ResponseEntity;
    import org.springframework.security.crypto.password.PasswordEncoder;
    import org.springframework.web.bind.annotation.*;
    
    import java.util.Map;
    import java.util.Optional;
    
    @RequiredArgsConstructor
    @RestController
    public class AccountController {
    
        private final AccountService accountService;
        private final PasswordEncoder passwordEncoder;
        private final JwtTokenProvider jwtTokenProvider;
        private final AccountRepository accountRepository;
    
        @PostMapping("/api/signup")
        public ResponseEntity registerAccount(@RequestBody AccountRequestDto requestDto){
            Optional<Account> found = accountRepository.findByUsername(requestDto.getUsername());
            if(found.isPresent()){
                return ResponseEntity.badRequest().build();
    //                    throw new IllegalArgumentException("중복된 사용자 ID가 존재합니다.");
            }
            if(!requestDto.getPassword().equals(requestDto.getPasswordConfirm())){
                return ResponseEntity.badRequest().build();
                //throw new IllegalArgumentException("pw가 일치하지 않습니다.");
            }
    
            accountService.registerAccount(requestDto);
            return ResponseEntity.ok().build();
        }
    
        // 로그인
        @PostMapping("/api/login")
        public String login(@RequestBody Map<String, String> account) {
    
            Account acc = accountRepository.findByUsername(account.get("username")).orElseThrow(() -> new IllegalArgumentException("가입되지 않은 E-MAIL 입니다."));
    
            if (!passwordEncoder.matches(account.get("password"), acc.getPassword())) {
                throw new IllegalArgumentException("잘못된 비밀번호입니다.");
            }
    
            JsonObject obj = new JsonObject();
            obj.addProperty("token", jwtTokenProvider.createToken(acc.getUsername(), acc.getRoles()));
            return obj.toString();
        }
    }
    

+  추가로 JWT 로직

댓글