source: src/main/java/com/example/task/service/UserAuthenticationService.java

Last change on this file was fdfbdde, checked in by Stojilkova Sara <sara.stojilkova.students.finki.ukim.mk>, 9 months ago

Initial commit

  • Property mode set to 100644
File size: 1.1 KB
RevLine 
[fdfbdde]1package com.example.task.service;
2
3import com.example.task.entity.StudentEntity;
4import com.example.task.repository.StudentRepository;
5import lombok.AllArgsConstructor;
6import org.springframework.security.core.Authentication;
7import org.springframework.security.core.context.SecurityContextHolder;
8import org.springframework.security.core.userdetails.UserDetails;
9import org.springframework.stereotype.Service;
10
11@Service
12@AllArgsConstructor
13public class UserAuthenticationService {
14
15 private final StudentRepository studentRepository;
16
17 public StudentEntity getLoggedInUser() {
18 Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
19 if (authentication != null && authentication.isAuthenticated()) {
20
21 Object principal = authentication.getPrincipal();
22 if (principal instanceof UserDetails) {
23 String username = ((UserDetails) principal).getUsername();
24 StudentEntity user = studentRepository.findByUsername(username).get();
25 return user;
26 }
27 }
28 return null;
29 }
30}
Note: See TracBrowser for help on using the repository browser.