관리 메뉴

막내의 막무가내 프로그래밍 & 일상

[Spring Boot] 스프링부트 프로젝트 로그인 구현 (AWS -> Naver Cloud 변경) 본문

웹/Spring Boot

[Spring Boot] 스프링부트 프로젝트 로그인 구현 (AWS -> Naver Cloud 변경)

막무가내막내 2020. 6. 20. 18:54
728x90

 

막무가내 스프링부트 개발하며 배워가는 중 입니다.ㅎㅎ 

 

예전에 아이티 기사를 분야별로 보여주고 스크랩할 수 있는 팀프로젝트를 진행 중이었는데요.

AWS 서버 과금 폭탄 먹고(부들부들..) 중단된 걸 네이버 클라우드 서버로 변경 후 다시 조금씩 진행중에 있습니다. (완성은 해야져..)

https://github.com/mtjin/springboot-itarticle

 

mtjin/springboot-itarticle

스프링부트 토이프로젝트. Contribute to mtjin/springboot-itarticle development by creating an account on GitHub.

github.com

로그인 쪽을 구현해봤습니다.

 

[프로젝트 구조]

 

[Entity]

package com.mtjin.itarticle.domain.entity;

import lombok.AccessLevel;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;

import javax.persistence.*;

@NoArgsConstructor(access = AccessLevel.PROTECTED)
@Getter
@Entity
@Table(name = "user")
public class UserEntity{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(length = 20, nullable = false)
    private String name;

    @Column(length = 20, nullable = false)
    private String email;

    @Column(length = 20, nullable = false)
    private String password;

    @Builder
    public UserEntity(Long id,String name, String email, String password) {
        this.id = id;
        this.name = name;
        this.email = email;
        this.password = password;
    }
}

 

 

[Dto]

package com.mtjin.itarticle;

import com.mtjin.itarticle.domain.entity.UserEntity;
import lombok.*;

@Getter
@Setter
@ToString
@NoArgsConstructor
public class UserDto {
    private long id;
    private String name;
    private String email;
    private String password;

    public UserEntity toEntity() {
        UserEntity boardEntity = UserEntity.builder()
                .id(id)
                .name(name)
                .email(email)
                .password(password)
                .build();
        return boardEntity;
    }

    @Builder
    public UserDto(long id, String name, String email, String password) {
        this.id = id;
        this.name = name;
        this.email = email;
        this.password = password;
    }
}

 

 

[Repository] 

package com.mtjin.itarticle.domain.repository;

import com.mtjin.itarticle.domain.entity.UserEntity;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;


public interface UserRepository extends JpaRepository<UserEntity, Long> {

    List<UserEntity> findUserEntityByEmail(String email);

    List<UserEntity> findUserEntityByName(String name);

    UserEntity findUserEntityByEmailAndPassword(String email, String name);
}

 

 

 

[Service]

package com.mtjin.itarticle.service;

import com.mtjin.itarticle.UserDto;
import com.mtjin.itarticle.domain.entity.UserEntity;
import com.mtjin.itarticle.domain.repository.UserRepository;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


@AllArgsConstructor
@Service
public class UserService {
    private UserRepository userRepository;

    @Transactional
    public Long saveUser(UserDto userDto) {
        return userRepository.save(userDto.toEntity()).getId();
    }

    @Transactional
    public boolean isExistEmail(UserDto userDto) {
        return !userRepository.findUserEntityByEmail(userDto.toEntity().getEmail()).isEmpty();
    }

    @Transactional
    public boolean isExistName(UserDto userDto) {
        return !userRepository.findUserEntityByName(userDto.toEntity().getName()).isEmpty();
    }

    @Transactional
    public UserEntity login(UserDto userDto) {
        return userRepository.findUserEntityByEmailAndPassword(userDto.toEntity().getEmail(), userDto.toEntity().getPassword());
    }

}

 

 

[login.js] => 로그인 유효성 검사 및 ajax 통신 구현

function ajax_register() {
    var validate = true;
    var form = $(".my-register-validation");
    if (form[0].checkValidity() === false) {
        event.preventDefault();
        event.stopPropagation();
        validate = false;
    }
    form.addClass('was-validated');
    if (validate) {
        var register_form = $("#register_form").serialize();
        $.ajax({
            type: 'POST',
            url: 'do_register',
            data: register_form,
            dataType: 'json',
            success: function (json) {
                if (json.success === "true") {
                    Swal.fire({
                        title: "Success!",
                        text: "Congratulations, Register Success",
                        icon: "success"
                    }).then(function () {
                        // 성공시 확인 버튼 클릭 후 login 페이지로 리다이렉트
                        window.location.href = "login";
                    });
                } else {
                    if (json.name === "false") {
                        //이미 존재하는 이름
                        Swal.fire({
                            title: 'Fail', /*상단 타이틀*/
                            text: 'Name is already Exist', /*내용*/
                            icon: 'error' /*아이콘 타입*/
                        });
                    } else if (json.email === "false") {
                        //이미 존재하는 이메일
                        Swal.fire({
                            title: 'Fail', /*상단 타이틀*/
                            text: 'Email is already Exist', /*내용*/
                            icon: 'error' /*아이콘 타입*/
                        });
                    } else {
                        Swal.fire({
                            title: 'Fail', /*상단 타이틀*/
                            text: 'Fail To Register', /*내용*/
                            icon: 'error'/*아이콘 타입*/
                        });
                    }
                }
            }
        });
    }
}

 

 

 

[login.html]

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
	<meta charset="utf-8">
	<meta name="author" content="Kodinger">
	<meta name="viewport" content="width=device-width,initial-scale=1">
	<title>My Login Page</title>
	<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
	<link rel="stylesheet" type="text/css" href="/static/css/my-login.css">
	<script src="https://cdn.jsdelivr.net/npm/sweetalert2@9"></script>
	<!-- Optional: include a polyfill for ES6 Promises for IE11 -->
	<script src="https://cdn.jsdelivr.net/npm/promise-polyfill"></script>
	<!--jquery-->
	<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
	<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
	<script src="https://code.jquery.com/jquery-3.4.1.min.js"
			integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
</head>

<body class="my-login-page">
<section class="h-100">
	<div class="container h-100">
		<div class="row justify-content-md-center h-100">
			<div class="card-wrapper">
				<div class="brand">
					<img src="/static/img/logo.jpg" alt="logo">
				</div>
				<div class="card fat">
					<div class="card-body">
						<h4 class="card-title">Login</h4>
						<form method="POST" id="login_form" class="my-login-validation2" novalidate="">
							<div class="form-group">
								<input th:name="name" type="hidden" value =""  name="name"/>
								<label for="email">E-Mail Address</label>
								<input id="email" type="email" class="form-control" th:name="email" name="email" value="" required autofocus>
								<div class="invalid-feedback">
									Email is invalid
								</div>
							</div>

							<div class="form-group">
								<label for="password">Password
									<a th:href="@{'/forgot'}" class="float-right">
										Forgot Password?
									</a>
								</label>
								<input id="password" type="password" class="form-control" th:name="password" name="password" required data-eye>
								<div class="invalid-feedback">
									Password is required
								</div>
							</div>

							<div class="form-group">
								<div class="custom-checkbox custom-control">
									<input type="checkbox" name="remember" id="remember" class="custom-control-input">
									<label for="remember" class="custom-control-label">Remember Me</label>
								</div>
							</div>

							<div class="form-group m-0">
								<button type="button" class="btn btn-primary btn-block" id="login_btn" onclick="return ajax_login()">
									Login
								</button>
							</div>
							<div class="mt-4 text-center">
								Don't have an account? <a th:href="@{'/register'}">Create One</a>
							</div>
						</form>
					</div>
				</div>
				<div class="footer">
					Copyright &copy; 2020 &mdash; ITARTICLE
				</div>
			</div>
		</div>
	</div>
</section>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="/static/js/login/login.js"></script>
<script src="/static/js/my-login.js"></script>
</body>
</html>

 

 

 

 

[결과 화면]

 

728x90
Comments