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

Feat: 관리자 인증 및 인가 기능 구현 #213

Merged
merged 18 commits into from
Nov 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
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
3 changes: 2 additions & 1 deletion src/main/java/com/example/sinitto/SinittoApplication.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.example.sinitto;

import com.example.sinitto.common.properties.AdminProperties;
import com.example.sinitto.common.properties.DummyProperties;
import com.example.sinitto.common.properties.KakaoProperties;
import org.springframework.boot.SpringApplication;
Expand All @@ -10,7 +11,7 @@

@SpringBootApplication
@EnableJpaAuditing
@EnableConfigurationProperties({KakaoProperties.class, DummyProperties.class})
@EnableConfigurationProperties({KakaoProperties.class, DummyProperties.class, AdminProperties.class})
@EnableScheduling
public class SinittoApplication {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ public ResponseEntity<LoginResponse> kakaoCallback(@RequestParam("code") String

@Operation(summary = "Redis안의 모든 데이터 제거", description = "발급된 refreshToken을 사용하지 못하게 Redis 안의 모든 데이터를 제거합니다.")
@DeleteMapping("/redis")
public ResponseEntity<Void> deleteAllDataFromRedis(){
public ResponseEntity<Void> deleteAllDataFromRedis() {
tokenService.deleteAllDataFromRedis();
return new ResponseEntity<>(HttpStatus.OK);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ public TokenResponse refreshAccessToken(String refreshToken) {
return new TokenResponse(newAccessToken, newRefreshToken);
}

public void deleteAllDataFromRedis(){
public void deleteAllDataFromRedis() {
redisTemplate.getConnectionFactory()
.getConnection()
.serverCommands()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.servers.Server;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
import io.swagger.v3.oas.models.servers.Server;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
Expand All @@ -14,10 +14,9 @@
@Configuration
public class SwaggerConfig {

private final Environment environment;

private static final String LOCAL_SERVER_URL = "http://localhost:8080";
private static final String PROD_SERVER_URL = "https://sinitto.site";
private final Environment environment;

public SwaggerConfig(Environment environment) {
this.environment = environment;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public class WebConfig implements WebMvcConfigurer {
private static final int CONNECTIONS_PER_IP_PORT_PAIR = 5;
private final JwtInterceptor jwtInterceptor;

public WebConfig(JwtInterceptor jwtInterceptor){
public WebConfig(JwtInterceptor jwtInterceptor) {
this.jwtInterceptor = jwtInterceptor;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,12 @@
public class JwtInterceptor implements HandlerInterceptor {
private final MemberTokenService memberTokenService;

public JwtInterceptor(MemberTokenService memberTokenService){
public JwtInterceptor(MemberTokenService memberTokenService) {
this.memberTokenService = memberTokenService;
}

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
Method method = handlerMethod.getMethod();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package com.example.sinitto.common.properties;

import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties(prefix = "admin")
public record AdminProperties(
String adminEmail,
String adminPassword
) {
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,14 @@
@Service
public class SlackMessageService {

private final RestTemplate restTemplate;
@Value("${slack.notice.webhook.url}")
private String slackNoticeWebhookUrl;

@Value("${slack.charge.request.url}")
private String chargeRequestUrl;

@Value("${slack.withdraw.request.url}")
private String withdrawRequestUrl;

private final RestTemplate restTemplate;

public SlackMessageService(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ public void createSenior(Long memberId, SeniorRequest seniorRequest) {
);
if (member.isSinitto()) throw new BadRequestException("보호자만 이용할 수 있습니다.");

if(seniorRepository.existsByPhoneNumber(seniorRequest.seniorPhoneNumber())) {
if (seniorRepository.existsByPhoneNumber(seniorRequest.seniorPhoneNumber())) {
throw new BadRequestException("이미 등록되어 있는 전화번호 입니다.");
}

Expand Down Expand Up @@ -90,7 +90,7 @@ public void updateSenior(Long memberId, Long seniorId, SeniorRequest seniorReque
() -> new NotFoundException("이메일에 해당하는 시니어를 찾을 수 없습니다.")
);

if(!senior.getPhoneNumber().equals(seniorRequest.seniorPhoneNumber())
if (!senior.getPhoneNumber().equals(seniorRequest.seniorPhoneNumber())
&& seniorRepository.existsByPhoneNumber(seniorRequest.seniorPhoneNumber())) {
throw new BadRequestException("이미 등록되어 있는 전화번호 입니다.");
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
package com.example.sinitto.member.controller;

import com.example.sinitto.auth.service.TokenService;
import com.example.sinitto.common.properties.AdminProperties;
import com.example.sinitto.common.properties.DummyProperties;
import com.example.sinitto.member.entity.Member;
import com.example.sinitto.member.repository.MemberRepository;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
Expand All @@ -15,32 +17,61 @@
import java.util.List;

@Controller
@RequestMapping("/dummy")
@RequestMapping
public class MemberAdminController {

private final MemberRepository memberRepository;
private final TokenService tokenService;
private final DummyProperties dummyProperties;

private final AdminProperties adminProperties;
private final List<String> dummyEmails = Arrays.asList(
"[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]",
"[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]"
);

public MemberAdminController(MemberRepository memberRepository, TokenService tokenService, DummyProperties dummyProperties) {
public MemberAdminController(MemberRepository memberRepository, TokenService tokenService, DummyProperties dummyProperties, AdminProperties adminProperties) {
this.memberRepository = memberRepository;
this.tokenService = tokenService;
this.dummyProperties = dummyProperties;
this.adminProperties = adminProperties;
}

@GetMapping
@GetMapping("/dummy")
public String showDummyLoginPage(Model model) {
List<Member> dummyMembers = memberRepository.findAllByEmailIn(dummyEmails);
model.addAttribute("members", dummyMembers);
return "dummy/login";
}

@PostMapping
@GetMapping("/admin/login")
public String showAdminLoginPage(HttpSession session) {
if (isAdmin(session)) {
return "redirect:/admin/point/charge";
}
return "point/login";
}

@PostMapping("/admin/login")
public String login(@RequestParam String email,
@RequestParam String password,
HttpSession session) {
if (adminProperties.adminEmail().equals(email) && adminProperties.adminPassword().equals(password)) {
session.setAttribute("email", email);
session.setAttribute("role", "ADMIN");
Copy link
Collaborator

@2iedo 2iedo Nov 11, 2024

Choose a reason for hiding this comment

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

여기 timeout도 추가해주면 좋을 것 같습니다!
session.setMaxInactiveInterval(1800);
요렇게 추가하면 될거에요. 위의 코드안의 숫자는 초단위라 저렇게 작성하면 만료시간이 30분임을 의미합니다.

Copy link
Collaborator

Choose a reason for hiding this comment

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

추가로 로그인할 때 sessionId가 url에 남던데,
server.servlet.session.tracking-modes = cookie
을 properties에 추가하면 url에 남지 않습니다.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

오오 좋은 정보 감사해요ㅎㅎ 적용해두었어요

session.setMaxInactiveInterval(1800);
return "redirect:/admin/point/charge";
} else {
return "redirect:/admin/login?error=true";
}
}

@PostMapping("/admin/logout")
public String logout(HttpSession session) {
session.invalidate();
return "redirect:/admin/login";
}

@PostMapping("/dummy")
public String login(
@RequestParam("email") String email,
@RequestParam("password") String password,
Expand All @@ -67,4 +98,9 @@ public String login(
String frontendRedirectUrl = env.equals("dev") ? dummyProperties.devRedirectUri() : dummyProperties.redirectUri();
return "redirect:" + frontendRedirectUrl + "?accessToken=" + accessToken + "&refreshToken=" + refreshToken + "&isSinitto=" + isSinitto;
}

private boolean isAdmin(HttpSession session) {
String role = (String) session.getAttribute("role");
return "ADMIN".equals(role);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ public class MemberTokenService {
private final TokenService tokenService;
private final MemberRepository memberRepository;

public MemberTokenService(TokenService tokenService, MemberRepository memberRepository){
public MemberTokenService(TokenService tokenService, MemberRepository memberRepository) {
this.tokenService = tokenService;
this.memberRepository = memberRepository;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import com.example.sinitto.point.dto.PointLogWithBankInfo;
import com.example.sinitto.point.dto.PointLogWithDepositMessage;
import com.example.sinitto.point.service.PointAdminService;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
Expand All @@ -21,8 +22,10 @@ public PointAdminController(PointAdminService pointAdminService) {
}

@GetMapping("/admin/point/charge")
public String showAllChargeRequest(Model model) {

public String showAllChargeRequest(Model model, HttpSession session) {
if (!isAdmin(session)) {
return "redirect:/admin/login";
}
List<PointLogWithDepositMessage> logWithDepositMessages = pointAdminService.getPointLogWithDepositMessage();

model.addAttribute("logWithDepositMessages", logWithDepositMessages);
Expand All @@ -31,28 +34,37 @@ public String showAllChargeRequest(Model model) {
}

@PostMapping("/admin/point/charge/waiting/{pointLogId}")
public String changeToWaiting(@PathVariable Long pointLogId) {

public String changeToWaiting(@PathVariable Long pointLogId, HttpSession session) {
if (!isAdmin(session)) {
return "redirect:/admin/login";
}
pointAdminService.changeChargeLogToWaiting(pointLogId);
return "redirect:/admin/point/charge";
}

@PostMapping("/admin/point/charge/complete/{pointLogId}")
public String changeToCompleteAndEarn(@PathVariable Long pointLogId) {

public String changeToCompleteAndEarn(@PathVariable Long pointLogId, HttpSession session) {
if (!isAdmin(session)) {
return "redirect:/admin/login";
}
pointAdminService.earnPointAndChangeToChargeComplete(pointLogId);
return "redirect:/admin/point/charge";
}

@PostMapping("/admin/point/charge/fail/{pointLogId}")
public String changeToFail(@PathVariable Long pointLogId) {

public String changeToFail(@PathVariable Long pointLogId, HttpSession session) {
if (!isAdmin(session)) {
return "redirect:/admin/login";
}
pointAdminService.changeChargeLogToFail(pointLogId);
return "redirect:/admin/point/charge";
}

@GetMapping("/admin/point/withdraw")
public String showAllWithdrawRequest(Model model) {
public String showAllWithdrawRequest(Model model, HttpSession session) {
if (!isAdmin(session)) {
return "redirect:/admin/login";
}

List<PointLogWithBankInfo> logWithBankInfos = pointAdminService.getPointLogWithBankInfo();

Expand All @@ -62,24 +74,35 @@ public String showAllWithdrawRequest(Model model) {
}

@PostMapping("/admin/point/withdraw/waiting/{pointLogId}")
public String changeWithdrawLogToWaiting(@PathVariable Long pointLogId) {

public String changeWithdrawLogToWaiting(@PathVariable Long pointLogId, HttpSession session) {
if (!isAdmin(session)) {
return "redirect:/admin/login";
}
pointAdminService.changeWithdrawLogToWaiting(pointLogId);
return "redirect:/admin/point/withdraw";
}

@PostMapping("/admin/point/withdraw/complete/{pointLogId}")
public String changeWithdrawLogToCompleteAndEarn(@PathVariable Long pointLogId) {

public String changeWithdrawLogToCompleteAndEarn(@PathVariable Long pointLogId, HttpSession session) {
if (!isAdmin(session)) {
return "redirect:/admin/login";
}
pointAdminService.changeWithdrawLogToComplete(pointLogId);
return "redirect:/admin/point/withdraw";
}

@PostMapping("/admin/point/withdraw/fail/{pointLogId}")
public String changeWithdrawLogToFail(@PathVariable Long pointLogId) {

public String changeWithdrawLogToFail(@PathVariable Long pointLogId, HttpSession session) {
if (!isAdmin(session)) {
return "redirect:/admin/login";
}
pointAdminService.changeWithdrawLogToFail(pointLogId);
return "redirect:/admin/point/withdraw";
}

private boolean isAdmin(HttpSession session) {
String role = (String) session.getAttribute("role");
return "ADMIN".equals(role);
}

}
12 changes: 3 additions & 9 deletions src/main/java/com/example/sinitto/review/entity/Review.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,24 +14,18 @@
@Entity
@EntityListeners(AuditingEntityListener.class)
public class Review {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@NotNull
int starCountForRequest;

@NotNull
int starCountForService;

@NotNull
int starCountForSatisfaction;

@CreatedDate
LocalDate postDate;

String content;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "member_id")
@NotNull
Expand Down
1 change: 1 addition & 0 deletions src/main/resources/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@ spring.profiles.active=dev
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect
spring.h2.console.enabled=false
server.servlet.session.tracking-modes = cookie
Loading