Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[BE] feat(#636) : 관리자 로그인 구현 #637

Merged
merged 4 commits into from
Oct 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.example.backend.auth.api.controller.auth;

import com.example.backend.auth.api.controller.auth.request.AdminLoginRequest;
import com.example.backend.auth.api.controller.auth.request.AuthRegisterRequest;
import com.example.backend.auth.api.controller.auth.request.UserNameRequest;
import com.example.backend.auth.api.controller.auth.request.UserUpdateRequest;
Expand Down Expand Up @@ -186,4 +187,12 @@ public ResponseEntity<Void> nickNameDuplicationCheck(@Valid @RequestBody UserNam
return ResponseEntity.ok().build();
}

@ApiResponse(responseCode = "200", description = "관리자 로그인 성공")
@PostMapping("/admin")
public ResponseEntity<AuthLoginResponse> loginAdmin(@RequestBody AdminLoginRequest request) {

AuthLoginResponse response = authService.loginAdmin(request);

return ResponseEntity.ok().body(response);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package com.example.backend.auth.api.controller.auth.request;

import jakarta.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;

@Getter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class AdminLoginRequest {
private String id;
private String password;
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.example.backend.auth.api.service.auth;

import com.example.backend.auth.api.controller.auth.request.AdminLoginRequest;
import com.example.backend.auth.api.controller.auth.request.UserNameRequest;
import com.example.backend.auth.api.controller.auth.response.AuthLoginResponse;
import com.example.backend.auth.api.controller.auth.response.ReissueAccessTokenResponse;
Expand Down Expand Up @@ -33,6 +34,7 @@
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
Expand All @@ -45,6 +47,13 @@
@Transactional(readOnly = true)
@RequiredArgsConstructor
public class AuthService {
@Value("${tester.token}")
private String testerToken;
@Value("${tester.id}")
private String testerId;
@Value("${tester.password}")
private String testerPassword;

private static final String PLATFORM_ID_CLAIM = "platformId";
private static final String PLATFORM_TYPE_CLAIM = "platformType";
private static final String ROLE_CLAIM = "role";
Expand Down Expand Up @@ -316,4 +325,23 @@ public Long findUserIdByGithubIdOrElseThrowException(String githubId) {
return new UserException(ExceptionMessage.USER_NOT_FOUND_WITH_GITHUB_ID);
}).getId();
}

// 닉네임 중복체크 메서드
public AuthLoginResponse loginAdmin(AdminLoginRequest request) {

if (!request.getId().equals(testerId)) {
log.warn(">>>> {} : {} <<<<", request.getId(), ExceptionMessage.USER_NOT_ADMIN_ID);
throw new UserException(ExceptionMessage.USER_NOT_ADMIN_ID);
}
if(!request.getPassword().equals(testerPassword)){
log.warn(">>>> {} : {} <<<<", request.getPassword(), ExceptionMessage.USER_NOT_ADMIN_PASSWORD);
throw new UserException(ExceptionMessage.USER_NOT_ADMIN_PASSWORD);
}

log.warn(">>>> [ {}님이 로그인하셨습니다 ] <<<<", request.getId());

return AuthLoginResponse.builder()
.accessToken(testerToken)
.build();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Excepti
.requestMatchers("/auth/loginPage").permitAll()
.requestMatchers("/auth/*/login").permitAll()
.requestMatchers("/auth/check-nickname").permitAll()
.requestMatchers("/auth/admin").permitAll()
// Others
.anyRequest().hasAnyAuthority("USER", "ADMIN")
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ public enum ExceptionMessage {
USER_NOT_FOUND("데이터베이스에서 사용자를 찾을 수 없습니다."),
USER_NAME_DUPLICATION("중복된 이름입니다."),
USER_NOT_FOUND_WITH_GITHUB_ID("깃허브 계정에 해당하는 사용자를 찾을 수 없습니다."),
USER_NOT_ADMIN_ID("관리자의 아이디가 아닙니다."),
USER_NOT_ADMIN_PASSWORD("관리자의 패스워드가 아닙니다.."),

// CommitException
COMMIT_NOT_FOUND("커밋 정보를 찾을 수 없습니다."),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.example.backend.auth.api.controller.auth;

import com.example.backend.MockTestConfig;
import com.example.backend.auth.api.controller.auth.request.AdminLoginRequest;
import com.example.backend.auth.api.controller.auth.request.AuthRegisterRequest;
import com.example.backend.auth.api.controller.auth.request.UserNameRequest;
import com.example.backend.auth.api.controller.auth.request.UserUpdateRequest;
Expand All @@ -16,6 +17,7 @@
import com.example.backend.auth.config.fixture.UserFixture;
import com.example.backend.common.exception.ExceptionMessage;
import com.example.backend.common.exception.auth.AuthException;
import com.example.backend.common.exception.user.UserException;
import com.example.backend.common.utils.TokenUtil;
import com.example.backend.domain.define.account.user.SocialInfo;
import com.example.backend.domain.define.account.user.User;
Expand All @@ -27,6 +29,7 @@
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
Expand All @@ -47,6 +50,13 @@
@SuppressWarnings("NonAsciiCharacters")
class AuthControllerTest extends MockTestConfig {

@Value("${tester.token}")
private String testerToken;
@Value("${tester.id}")
private String testerId;
@Value("${tester.password}")
private String testerPassword;

@Autowired
private MockMvc mockMvc;

Expand Down Expand Up @@ -477,4 +487,68 @@ void userInfoWhenInvalidAuthority() throws Exception {
.andExpect(status().isOk());
}

@Test
@DisplayName("Admin 로그인 성공 테스트")
void adminLoginSuccessTest() throws Exception {
// given
AdminLoginRequest request = AdminLoginRequest.builder()
.id("admin")
.password(testerPassword)
.build();

AuthLoginResponse response = AuthLoginResponse.builder()
.accessToken(testerToken)
.build();

when(authService.loginAdmin(any(AdminLoginRequest.class))).thenReturn(response);

// when & then
mockMvc.perform(post("/auth/admin")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(request)))
.andExpect(status().isOk())
.andExpect(jsonPath("$.access_token").value(testerToken));
}

@Test
@DisplayName("Admin 로그인 실패 테스트 - 잘못된 아이디로 로그인 시도")
void adminLoginFailDueToIncorrectId() throws Exception {
// given
AdminLoginRequest request = AdminLoginRequest.builder()
.id("not_admin") // 잘못된 아이디
.password(testerPassword) // 올바른 패스워드
.build();

doThrow(new UserException(ExceptionMessage.USER_NOT_ADMIN_ID))
.when(authService)
.loginAdmin(any(AdminLoginRequest.class));

// when & then
mockMvc.perform(post("/auth/admin")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(request)))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.message").value(ExceptionMessage.USER_NOT_ADMIN_ID.getText()));
}

@Test
@DisplayName("Admin 로그인 실패 테스트 - 잘못된 패스워드로 로그인 시도")
void adminLoginFailDueToIncorrectPassword() throws Exception {
// given
AdminLoginRequest request = AdminLoginRequest.builder()
.id(testerId) // 올바른 아이디
.password("wrongPassword") // 잘못된 패스워드
.build();

doThrow(new UserException(ExceptionMessage.USER_NOT_ADMIN_PASSWORD))
.when(authService)
.loginAdmin(any(AdminLoginRequest.class));

// when & then
mockMvc.perform(post("/auth/admin")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(request)))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.message").value(ExceptionMessage.USER_NOT_ADMIN_PASSWORD.getText()));
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.example.backend.auth.api.service.auth;

import com.example.backend.MockTestConfig;
import com.example.backend.auth.api.controller.auth.request.AdminLoginRequest;
import com.example.backend.auth.api.controller.auth.request.UserNameRequest;
import com.example.backend.auth.api.controller.auth.response.AuthLoginResponse;
import com.example.backend.auth.api.controller.auth.response.UserInfoAndRankingResponse;
Expand Down Expand Up @@ -36,6 +37,7 @@
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.mock.mockito.MockBean;

import java.util.HashMap;
Expand All @@ -52,6 +54,12 @@
import static org.mockito.Mockito.when;

class AuthServiceTest extends MockTestConfig {
@Value("${tester.token}")
private String testerToken;
@Value("${tester.id}")
private String testerId;
@Value("${tester.password}")
private String testerPassword;

@MockBean
private OAuthService oAuthService;
Expand Down Expand Up @@ -460,4 +468,57 @@ void getUserByInfoTest() {

}

@Test
@DisplayName("Admin 로그인 - 아이디 불일치로 실패 테스트")
void loginAdminFailDueToIncorrectId() {
// given
AdminLoginRequest request = AdminLoginRequest.builder()
.id("not_admin") // 잘못된 아이디
.password(testerPassword) // 올바른 패스워드
.build();

// then
UserException exception = assertThrows(UserException.class, () -> {
authService.loginAdmin(request);
});

// verify
assertEquals(ExceptionMessage.USER_NOT_ADMIN_ID.getText(), exception.getMessage());
}

@Test
@DisplayName("Admin 로그인 - 패스워드 불일치로 실패 테스트")
void loginAdminFailDueToIncorrectPassword() {
// given
AdminLoginRequest request = AdminLoginRequest.builder()
.id(testerId) // 올바른 아이디
.password("wrongPassword") // 잘못된 패스워드
.build();

// then
UserException exception = assertThrows(UserException.class, () -> {
authService.loginAdmin(request);
});

// verify
assertEquals(ExceptionMessage.USER_NOT_ADMIN_PASSWORD.getText(), exception.getMessage());
}

@Test
@DisplayName("Admin 로그인 성공 테스트")
void loginAdminSuccess() {
// given
AdminLoginRequest request = AdminLoginRequest.builder()
.id(testerId) // 올바른 아이디
.password(testerPassword) // 올바른 패스워드
.build();

// when
AuthLoginResponse response = authService.loginAdmin(request);

// then
assertNotNull(response);
assertEquals(testerToken, response.getAccessToken());
}

}
Loading