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

fix: 로그인/비로그인 유저 처리 #38

Merged
merged 2 commits into from
Jun 28, 2022

Conversation

kang-jisu
Copy link
Contributor

이슈

작업 내용

  • 비로그인유저 요청 가능한 API 토큰검증 제외,처리
    • 나무숲, 나무 상세 조회는 인터셉터에서 API URI,HttpMethod로 판별하여 토큰 검증 생략시킴
    • 물주기는 LoginUser에 임시 비로그인유저데이터 (userId=-1)를 넣어 처리
    • 물주기 message.senderId에 -1이 저장될 경우 userRepository.findById(message.getSenderId())가 NOTFOUND에러가 나게됨
      • 물주기 message.getSenderId로 유저를 조회할 경우 userService.findBySenderId()메서드를 이용해서 조회해옴
      • SendUserDto를 이용해 메시지 응답값을 생성할 때 메시지 보낸사람에 대한 데이터 생성

기타 사항

  • 리팩토링 방안
    • userService가 아닌 다른 Service에서는 UserRepository말고 userService를 생성자주입받아 userRepository.findById를 직접적으로 부르지 않고 userService.findById, findByOAuthId, findBySenderId를 부르도록 나중에 수정하면 좋을 것 같음

체크리스트

  • 테스트코드 작성
    • 로그인유저 / 비로그인 유저 모두 SpringBootTest로 확인해보려고했는데 충돌나서 MessageAcceptanceTest는 DIsabled처리해둔상태

일단은 이런방식으로 구현해봤는데,, 어떤지 봐주세요!! 감사합니다~~

- 인터셉터에서 요청 api 조건에 해당하면 바로 return true하도록 변경
- 비로그인 유저일 경우 senderId(userId)가 -1로 저장
- 물주기, 메시지 관련해서 senderId 조회할 때는 userService.findBySenderId로 찾아서 SendUserDto 반환값 이용
- 비로그인 유저일 경우 SendUserDto.ofNoLogin()메서드 호출해 익명유저 값 들어감
@kang-jisu kang-jisu added 💡feature API feature 👥회원관리 회원/로그인 🌲칭찬 칭찬 labels Jun 27, 2022
@kang-jisu kang-jisu added this to the 3차 스프린트 milestone Jun 27, 2022
@kang-jisu kang-jisu added this to To do in BeTree via automation Jun 27, 2022
@kang-jisu kang-jisu self-assigned this Jun 27, 2022
// }
if (senderId == -1L && !message.isAnonymous()) {
message.updateAnonymous();
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

프론트에서 이미 익명 처리하고 보내겠지만 혹시 몰라서 넣어 놨던 건데 없어도 될 것 같으면 삭제하셔도 돼요!

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

그래도 혹시모르니 있는거도 괜찮을거같아요! 이 코드 있어서 다른데서 비로그이 유저 익명여부 검사 안해도 무조건 익명인걸로 확인이되니까요!!

User user = userRepository.findById(userId).orElseThrow(() -> new BetreeException(USER_NOT_FOUND, "senderId = " + userId));
return SendUserDto.of(user);
}

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍❤️👍 조아요

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

☺️

return null;
}
};
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

실패시 오류가 뭐예용?!?

Copy link
Contributor Author

@kang-jisu kang-jisu Jun 28, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hibernate: 
    select
        folder0_.folder_id as folder_i1_0_0_,
        folder0_.created_date as created_2_0_0_,
        folder0_.last_modified_date as last_mod3_0_0_,
        folder0_.fruit as fruit4_0_0_,
        folder0_.level as level5_0_0_,
        folder0_.name as name6_0_0_,
        folder0_.user_id as user_id7_0_0_ 
    from
        folders folder0_ 
    where
        folder0_.folder_id=?
2022-06-29 01:44:10.479 TRACE 6577 --- [           main] o.h.type.descriptor.sql.BasicBinder      : binding parameter [1] as [BIGINT] - [170]
Hibernate: 
    insert 
    into
        folders
        (created_date, last_modified_date, fruit, level, name, user_id) 
    values
        (?, ?, ?, ?, ?, ?)
2022-06-29 01:44:10.483 TRACE 6577 --- [           main] o.h.type.descriptor.sql.BasicBinder      : binding parameter [1] as [TIMESTAMP] - [2022-06-29T01:44:10.480]
2022-06-29 01:44:10.484 TRACE 6577 --- [           main] o.h.type.descriptor.sql.BasicBinder      : binding parameter [2] as [TIMESTAMP] - [2022-06-29T01:44:10.480]
2022-06-29 01:44:10.484 TRACE 6577 --- [           main] o.h.type.descriptor.sql.BasicBinder      : binding parameter [3] as [VARCHAR] - [DEFAULT]
2022-06-29 01:44:10.484 TRACE 6577 --- [           main] o.h.type.descriptor.sql.BasicBinder      : binding parameter [4] as [BIGINT] - [0]
2022-06-29 01:44:10.484 TRACE 6577 --- [           main] o.h.type.descriptor.sql.BasicBinder      : binding parameter [5] as [VARCHAR] - [기본]
2022-06-29 01:44:10.484 TRACE 6577 --- [           main] o.h.type.descriptor.sql.BasicBinder      : binding parameter [6] as [BIGINT] - [171]
2022-06-29 01:44:10.487  INFO 6577 --- [           main] c.y.betree.interceptor.TokenInterceptor  : [토큰 검증 성공] claims: com.yapp.betree.controller.MessageAcceptanceTest$1@b8f6500
2022-06-29 01:44:10.497  INFO 6577 --- [           main] c.y.betree.controller.MessageController  : 물주기 요청 유저 : LoginUserDto(id=170, nickname=닉네임, email=이메일) , 내용 : MessageRequestDto(receiverId=170, content=메시지10자이상~~~, folderId=null, anonymous=false)
Hibernate: 
    select
        user0_.user_id as user_id1_4_0_,
        user0_.created_date as created_2_4_0_,
        user0_.last_modified_date as last_mod3_4_0_,
        user0_.email as email4_4_0_,
        user0_.forest_off as forest_o5_4_0_,
        user0_.last_access_time as last_acc6_4_0_,
        user0_.nickname as nickname7_4_0_,
        user0_.oauth_id as oauth_id8_4_0_,
        user0_.only_friends as only_fri9_4_0_,
        user0_.random_message_remind as random_10_4_0_,
        user0_.url as url11_4_0_,
        user0_.user_image as user_im12_4_0_ 
    from
        users user0_ 
    where
        user0_.user_id=?
2022-06-29 01:44:10.498 TRACE 6577 --- [           main] o.h.type.descriptor.sql.BasicBinder      : binding parameter [1] as [BIGINT] - [170]
2022-06-29 01:44:10.503 ERROR 6577 --- [           main] c.y.b.exception.GlobalExceptionHandler   : handleBetreeException[ErrorResponse(status=404, code=U005, message=회원을 찾을 수 없습니다.: receiverId = 170, errors=null)]

MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /api/messages
       Parameters = {}
          Headers = [Content-Type:"application/json", Authorization:"Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6IjEiLCJuaWNrbmFtZSI6IuuLieuEpOyehCIsImVtYWlsIjoiZW1haWxAZW1haWwuY29tIn0.AY0wUUbWbsVs2lSOle0-h48RVHkh3QKkHpAEOIZPxhM", Content-Length:"72"]
             Body = <no character encoding set>
    Session Attrs = {}





     Content type = application/json
             Body = {"status":404,"code":"U005","message":"��� 찾� � ����.: receiverId = 170"}
    Forwarded URL = null

404 save한 user에 대해서 (receverId) not found 에러인거같은데 이거 돌릴때만 한글도 깨지고 잘 안나오더라구요 퓨ㅠ mock없이 진짜 해씅ㄹ때 db에 잘 들어가나 확인하고싶어서 acceptanceTest (이런 명칭이 맞는지 모르겠는데 통합테스트, 인수테스트 비스한거 하려고 했어여) 로 @SpringBootTest걸어서 한건데.. ㅠ___ㅠ 이유를 아직은 잘 모르겠어요 ㅠ 개별적으로 돌리면 성공하긴해요

Copy link
Member

@suubinkim suubinkim left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

저도 많이 달아보고 싶은데 제가 로그인쪽 완벽하게 아직 못 봤고ㅠㅠ 넘 구현 잘해주셔서 할말이 없네용 ㅎ..ㅎㅎ
dto 저는 생각도 못 했는데 좋은 것 같아욤
그런데 그럼 비로그인 기능 요청올때 토큰 검증 아예 안 하는 건가요???

@kang-jisu
Copy link
Contributor Author

kang-jisu commented Jun 28, 2022

그런데 그럼 비로그인 기능 요청올때 토큰 검증 아예 안 하는 건가요???

넵 !! 비로그인일때는 토큰검증과정 아예 생략하는거로 구현했어요! 인터셉터에서 별다른 거 없이 return true로 넘어가는게 헤더에 있는 토큰에 대한 검사 없이 진행되는거니간요!! 나무숲관련해서는 파라미터로 LoginUserDto쓰는것도 없어서 바로 true이고 물주기에서는 DTO 넣어주느라고 처리!!

@kang-jisu kang-jisu merged commit 15067db into YAPP-Github:develop Jun 28, 2022
BeTree automation moved this from To do to Done Jun 28, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
🌲칭찬 칭찬 👥회원관리 회원/로그인 💡feature API feature
Projects
Development

Successfully merging this pull request may close these issues.

None yet

2 participants