Skip to content

Commit

Permalink
Tht server 223 로그아웃 api 추가 (#242)
Browse files Browse the repository at this point in the history
* add : user login 컬럼 추가

* docs : 로그아웃 api 문서

* feat : 로그아웃 기능 추가

* feat : 로그인 시 user login 컬럼 변경

* test : 로그아웃 인수테스트

* rename : 클래스명 변경

* Test : 로그아웃 후 로그인시 isLogin 값 변경 인수테스트
  • Loading branch information
thalals authored Jul 24, 2024
1 parent cac1567 commit 97c3d28
Show file tree
Hide file tree
Showing 11 changed files with 230 additions and 1 deletion.
18 changes: 18 additions & 0 deletions tht-apis/src/main/java/com/tht/thtapis/facade/LogoutFacade.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package com.tht.thtapis.facade;

import com.tht.domain.entity.user.User;
import com.tht.domain.entity.user.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Transactional;

@Facade
@Transactional
@RequiredArgsConstructor
public class LogoutFacade {

private final UserService userService;

public void logout(final User user) {
userService.logout(user);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ public TokenDto login(final UserLoginRequest request) {

final User user = userService.findByPhoneNumber(request.phoneNumber());
deviceKeyService.create(user.getUserUuid(), request.deviceKey());
user.login();

return getGenerateJWT(user);
}
Expand All @@ -47,6 +48,7 @@ public TokenDto snsLogin(final UserSNSLoginRequest request) {

final String userUuid = userSnsService.findUserUuidBySnsIdKey(request.snsType(), request.snsUniqueId());
final User user = userService.findByUserUuidForAuthToken(userUuid);
user.login();

return getGenerateJWT(user);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.tht.thtapis.ui;

import com.tht.domain.entity.user.User;
import com.tht.thtapis.facade.LogoutFacade;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequiredArgsConstructor
public class UserLogoutController {

private final LogoutFacade logoutFacade;

@PostMapping("/user/logout")
public ResponseEntity<Object> logout(@AuthenticationPrincipal User user) {

logoutFacade.logout(user);
return ResponseEntity.ok().build();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package com.tht.thtapis.acceptance;

import io.restassured.RestAssured;
import io.restassured.response.ExtractableResponse;
import io.restassured.response.Response;

class UserLogoutAcceptanceStep {

public static ExtractableResponse<Response> 로그아웃_요청(String accessToken) {

return RestAssured.given().log().all()
.auth().oauth2(accessToken)
.when().post("/user/logout")
.then().log().all()
.extract();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
package com.tht.thtapis.acceptance;

import com.tht.domain.entity.user.User;
import com.tht.enums.user.SNSType;
import com.tht.thtapis.acceptance.config.AcceptanceTest;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import static com.tht.thtapis.acceptance.UserLoginAcceptanceStep.일반로그인;
import static com.tht.thtapis.acceptance.UserLogoutAcceptanceStep.로그아웃_요청;
import static com.tht.thtapis.acceptance.UserSignUpAcceptanceStep.SNS_유저_생성;
import static com.tht.thtapis.acceptance.UserSignUpAcceptanceStep.신규유저_생성_요청__토큰추출;
import static org.assertj.core.api.Assertions.assertThat;

class UserLogoutAcceptanceTest extends AcceptanceTest {

@Test
@DisplayName("유저 로그아웃 성공 인수테스트")
void userLogout() {

String phoneNumber = "1113332222";
String username = "username";
String token = 신규유저_생성_요청__토큰추출(username, phoneNumber);

//로그아웃
var response = 로그아웃_요청(token);
assertThat(response.statusCode()).isEqualTo(200);

User user = 유저정보조회(phoneNumber);
assertThat(user.getIsLogin()).isFalse();

}

@Test
@DisplayName("로그아웃 후 일반 로그인 테스트")
void normalLoginAfterLogout() {

String phoneNumber = "1113332222";
String username = "username";
String token = 신규유저_생성_요청__토큰추출(username, phoneNumber);

로그아웃_요청(token);

//when
일반로그인(phoneNumber, "dd");

//then
User user = 유저정보조회(phoneNumber);
assertThat(user.getIsLogin()).isTrue();
}

@Test
@DisplayName("로그아웃 후 sns 로그인 테스트")
void snsLoginAfterLogout() {

//sns 유저 생성
final String phoneNumber = "01012345678";
final String email = "[email protected]";
final SNSType snsType = SNSType.KAKAO;
final String snsUniqueId = "snsUniqueId";
final String deviceKey = "deviceKey";

var response = SNS_유저_생성(phoneNumber, email, snsType, snsUniqueId, deviceKey);
String token = response.jsonPath().getString("accessToken");

로그아웃_요청(token);

//when
일반로그인(phoneNumber, "ㅇㄹ");

//then
User user = 유저정보조회(phoneNumber);
assertThat(user.getIsLogin()).isTrue();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -79,17 +79,23 @@ private static Map<String, Object> createUserJoinRequest(final String username,
public static ExtractableResponse<Response> SNS_유저_생성(final String phoneNumber, final String email, final SNSType snsType,
final String snsUniqueId, final String deviceKey) {

RestAssured.given().log().all()
return RestAssured.given().log().all()
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(createSNSUserJoinRequest(phoneNumber, email, snsType, snsUniqueId, deviceKey))
.when().post("/users/join/signup")
.then().log().all().extract();


}

public static ExtractableResponse<Response> SNS_유저_통합(final String phoneNumber, final String email, final SNSType snsType,
final String snsUniqueId, final String deviceKey) {
Map<String, Object> requestBody = new HashMap<>();
requestBody.put("email", email);
requestBody.put("snsType", snsType.name());
requestBody.put("snsUniqueId", snsUniqueId);
requestBody.put("deviceKey", deviceKey);
requestBody.put("phoneNumber", phoneNumber);

return RestAssured.given().log().all()
.contentType(MediaType.APPLICATION_JSON_VALUE)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

import com.tht.domain.entity.dailyfalling.DailyFalling;
import com.tht.domain.entity.dailyfalling.DailyFallingActiveInfo;
import com.tht.domain.entity.user.User;
import com.tht.domain.entity.user.repository.UserRepository;
import com.tht.enums.dailyfalling.DailyFallingType;
import com.tht.domain.entity.dailyfalling.repository.DailyFallingActiveTimeTableRepository;
import com.tht.domain.entity.dailyfalling.repository.DailyFallingRepository;
Expand Down Expand Up @@ -47,6 +49,9 @@ public abstract class AcceptanceTest {
@Autowired
TokenProvider tokenProvider;

@Autowired
UserRepository userRepository;

@LocalServerPort
private int port;

Expand Down Expand Up @@ -82,4 +87,12 @@ private void setUpCreateUser() {
public String getUserUuid(String accessToken) {
return tokenProvider.getAuthentication(accessToken).getCredentials().toString();
}

public User 유저정보조회(String phoneNumber) {
return userRepository.findByPhoneNumber(phoneNumber)
.orElseThrow(
() -> new RuntimeException(phoneNumber + " 유저 없음")
);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package com.tht.thtapis.documentation;

import com.epages.restdocs.apispec.ResourceSnippetParameters;
import com.tht.thtapis.controller.config.ControllerTestConfig;
import com.tht.thtapis.controller.config.WithCustomMockUser;
import com.tht.thtapis.facade.LogoutFacade;
import com.tht.thtapis.security.SecurityConst;
import com.tht.thtapis.ui.UserLogoutController;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.ResultActions;

import static com.epages.restdocs.apispec.MockMvcRestDocumentationWrapper.document;
import static com.epages.restdocs.apispec.ResourceDocumentation.resource;
import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@WebMvcTest(UserLogoutController.class)
class UserLogoutDocumentation extends ControllerTestConfig {

@MockBean
private LogoutFacade logoutFacade;

@Test
@WithCustomMockUser
@DisplayName("유저 로그아웃 api 문서생성")
void userLogoutDocs() throws Exception {

final ResultActions resultActions = mockMvc.perform(post("/user/logout")
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
.header(SecurityConst.AUTH_HEADER_NAME, "Bearer {ACCESS_TOKEN}")
).andDo(
document("로으가웃 api docs",
resource(
ResourceSnippetParameters.builder()
.tag("유저 - 로그아웃")
.description("유저 로그아웃 api")
.build()
))
);

resultActions.andExpect(status().isOk());
}

}
12 changes: 12 additions & 0 deletions tht-core/domain/src/main/java/com/tht/domain/entity/user/User.java
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,9 @@ public class User extends Auditable {
@Convert(converter = UserReligionConverter.class)
private UserReligion religion;

@Column
private Boolean isLogin;

@Builder(access = AccessLevel.PRIVATE)
public User(final Long idx, final String userUuid, final String username,
final LocalDate birthDay, final String phoneNumber,
Expand All @@ -105,6 +108,7 @@ public User(final Long idx, final String userUuid, final String username,
this.drinking = drinking;
this.smoking = smoking;
this.religion = religion;
this.isLogin = true;
}

public static User createNewUser(final String username, final LocalDate birthDay,
Expand Down Expand Up @@ -184,4 +188,12 @@ public void updatePreferGender(final Gender gender) {
public void accountWithdrawal() {
this.state = EntityState.DELETED;
}

public void logout() {
this.isLogin = false;
}

public void login() {
this.isLogin = true;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -100,4 +100,10 @@ public void withDraw(final User user, final String reason, final String feedBack
userWithDrawLogRepository.save(UserWithDrawLog.of(user.getUserUuid(), reason, feedBack));
save(user);
}

public void logout(final User user) {

user.logout();
save(user);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,17 @@ void createNewUserMethod() {
assertThat(newUser.getUserUuid()).isNotNull();
}

@Test
@DisplayName("유저 생성 시 login true")
void loginMethod() {
User newUser = UserFixture.make();
assertThat(newUser.getLogin()).isTrue();
}

@Test
@DisplayName("유저 번호 수정")
void updatePhoneNumber() {

User newUser = UserFixture.make();

String updateNumber = "123456780";
Expand Down

0 comments on commit 97c3d28

Please sign in to comment.