Skip to content

Commit

Permalink
DEAR-125: add securityUtil to get current user
Browse files Browse the repository at this point in the history
  • Loading branch information
baurnick committed Jul 22, 2024
1 parent 1f3311b commit 59d1f05
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 4 deletions.
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
package ch.fhnw.deardevbackend.services;

import ch.fhnw.deardevbackend.dto.TeamWithMembersDTO;
import ch.fhnw.deardevbackend.entities.Role;
import ch.fhnw.deardevbackend.entities.Team;
import ch.fhnw.deardevbackend.entities.TeamMemberWithUser;
import ch.fhnw.deardevbackend.mapper.TeamWithMembersMapper;
import ch.fhnw.deardevbackend.repositories.TeamMemberWithUserRepository;
import ch.fhnw.deardevbackend.repositories.TeamRepository;
import ch.fhnw.deardevbackend.util.SecurityUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
Expand All @@ -27,8 +27,9 @@ public class TeamMemberService {
public TeamWithMembersDTO getTeamMembersByTeamId(Integer teamId) {
List<TeamMemberWithUser> members = teamMemberWithUserRepository.findByTeamId(teamId);
Team team = teamRepository.findById(teamId).orElseThrow(() -> new RuntimeException("Team not found with id: " + teamId));
Integer adminId = members.stream().filter(member -> member.getRole().equals(Role.ADMIN)).toList().getFirst().getUser().getId();
boolean isActive = adminId.equals(team.getCreatedBy());
return teamWithMembersMapper.toDTO(team, members, isActive);

boolean isAdmin = team.getCreatedBy().equals(SecurityUtil.getCurrentUserId());

return teamWithMembersMapper.toDTO(team, members, isAdmin);
}
}
16 changes: 16 additions & 0 deletions src/main/java/ch/fhnw/deardevbackend/util/SecurityUtil.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package ch.fhnw.deardevbackend.util;

import ch.fhnw.deardevbackend.entities.User;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

public class SecurityUtil {

public static Integer getCurrentUserId() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && authentication.getPrincipal() instanceof User) {
return ((User) authentication.getPrincipal()).getId();
}
return null;
}
}

0 comments on commit 59d1f05

Please sign in to comment.