source: backend/web3-Ednevnik-Backend/src/main/java/com/nikola/web3ednevnikbackend/controller/AuthController.java

Last change on this file was 81cdf2d, checked in by Nikola Janev <nikolajanev57@…>, 9 days ago

initial commit

  • Property mode set to 100644
File size: 7.5 KB
Line 
1package com.nikola.web3ednevnikbackend.controller;
2
3import com.nikola.web3ednevnikbackend.config.security.CustomUserDetails;
4import com.nikola.web3ednevnikbackend.dto.security.LoginRequest;
5import com.nikola.web3ednevnikbackend.dto.users.*;
6import com.nikola.web3ednevnikbackend.model.users.Korisnik;
7import com.nikola.web3ednevnikbackend.repository.auth.LoginAttemptRepository;
8import com.nikola.web3ednevnikbackend.service.users.*;
9import jakarta.servlet.http.HttpServletRequest;
10import jakarta.servlet.http.HttpSession;
11import lombok.RequiredArgsConstructor;
12import org.springframework.http.HttpStatus;
13import org.springframework.http.ResponseEntity;
14import org.springframework.security.authentication.AuthenticationManager;
15import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
16import org.springframework.security.core.Authentication;
17import org.springframework.security.core.AuthenticationException;
18import org.springframework.security.core.context.SecurityContextHolder;
19import org.springframework.web.bind.annotation.*;
20
21import java.util.Map;
22import java.util.UUID;
23
24@RestController
25@RequestMapping("/api/auth")
26@RequiredArgsConstructor
27public class AuthController {
28
29 private final AuthenticationManager authenticationManager;
30 private final RoditelService roditelService;
31 private final BlagajnikService blagajnikService;
32 private final Direktor_AdminService direktorAdminService;
33 private final Klasen_RakovoditelService klasenRakovoditelService;
34 private final Predmeten_NastavnikService predmetenNastavnikService;
35 private final LoginAttemptRepository loginAttemptRepository;
36 private final KorisnikService korisnikService;
37
38 // @PostMapping("/login")
39// public ResponseEntity<?> login(@RequestBody LoginRequest request,
40// HttpServletRequest httpRequest) {
41// System.out.println("LOGIN HIT");
42// System.out.println("Email: " + request.getEmail());
43// System.out.println("password: " + request.getPassword()
44// );
45// String ipAddress = httpRequest.getRemoteAddr();
46// Authentication authentication =
47// authenticationManager.authenticate(
48// new UsernamePasswordAuthenticationToken(
49// request.getEmail(),
50// request.getPassword()
51// )
52// );
53//
54// SecurityContextHolder.getContext().setAuthentication(authentication);
55//
56// HttpSession session = httpRequest.getSession(true);
57// session.setAttribute(
58// "SPRING_SECURITY_CONTEXT",
59// SecurityContextHolder.getContext()
60// );
61// CustomUserDetails userDetails = (CustomUserDetails) authentication.getPrincipal();
62//
63// return ResponseEntity.ok().body(
64// Map.of(
65// "id", userDetails.getId(),
66// "email", authentication.getName(),
67// "roles", authentication.getAuthorities()
68// )
69// );
70// }
71 @PostMapping("/login")
72 public ResponseEntity<?> login(
73 @RequestBody LoginRequest request,
74 HttpServletRequest httpRequest
75 ) {
76 System.out.println("LOGIN HIT");
77 System.out.println("Email: " + request.getEmail());
78
79 String ipAddress = httpRequest.getRemoteAddr();
80
81 try {
82 Authentication authentication =
83 authenticationManager.authenticate(
84 new UsernamePasswordAuthenticationToken(
85 request.getEmail(),
86 request.getPassword()
87 )
88 );
89
90 SecurityContextHolder.getContext().setAuthentication(authentication);
91
92 HttpSession session = httpRequest.getSession(true);
93 session.setAttribute(
94 "SPRING_SECURITY_CONTEXT",
95 SecurityContextHolder.getContext()
96 );
97
98 CustomUserDetails userDetails =
99 (CustomUserDetails) authentication.getPrincipal();
100
101 boolean isAdmin = userDetails.getAuthorities().stream()
102 .anyMatch(authority ->
103 authority.getAuthority().equals("ROLE_MON_ADMIN") ||
104 authority.getAuthority().equals("ROLE_DIREKTOR_ADMIN")
105 );
106 if (!isAdmin) {
107 loginAttemptRepository.saveLoginAttempt(
108 userDetails.getId(),
109 request.getEmail(),
110 true,
111 ipAddress
112 );
113 }
114
115
116 return ResponseEntity.ok().body(
117 Map.of(
118 "id", userDetails.getId(),
119 "email", authentication.getName(),
120 "roles", authentication.getAuthorities()
121 )
122 );
123
124 } catch (AuthenticationException e) {
125
126
127 UUID userId = null;
128
129 try {
130 KorisnikResponseDTO korisnik =
131 korisnikService.findByEmail(request.getEmail());
132 if (korisnik != null) {
133 userId = korisnik.getId();
134 }
135
136 } catch (Exception ignored) {
137 throw new IllegalArgumentException("user with this email doesnt exist " + ignored.getMessage());
138 }
139
140 // Failed login -> Login_Attempt
141 loginAttemptRepository.saveLoginAttempt(
142 userId,
143 request.getEmail(),
144 false,
145 ipAddress
146 );
147
148 return ResponseEntity
149 .status(HttpStatus.UNAUTHORIZED)
150 .body(
151 Map.of(
152 "error",
153 "Invalid email or password"
154 )
155 );
156 }
157 }
158
159 @PostMapping("/logout")
160 public ResponseEntity<?> logout(HttpServletRequest request) {
161 request.getSession().invalidate();
162 SecurityContextHolder.clearContext();
163 System.out.println("LOGOUTTTTTTTTTTT");
164 return ResponseEntity.ok(Map.of("message", "Logged out"));
165 }
166
167 @GetMapping("/me")
168 public ResponseEntity<?> currentUser(Authentication authentication) {
169
170 CustomUserDetails user =
171 (CustomUserDetails) authentication.getPrincipal();
172 String role = user.getAuthorities().iterator().next().getAuthority();
173 String wallet = "Nema";
174
175
176 switch (role) {
177 case "ROLE_RODITEL" -> {
178 RoditelResponseDTO roditel = roditelService.getRoditelById(user.getId());
179 wallet = roditel.getMetamusk_adresa() != null ? roditel.getMetamusk_adresa() : "Nema";
180 }
181 case "ROLE_BLAGAJNIK" -> {
182 BlagajnikResponseDTO blagajnik = blagajnikService.getBlagajnikById(user.getId());
183 wallet = blagajnik.getMetamusk_adresa() != null ? blagajnik.getMetamusk_adresa() : "Nema";
184 }
185 // ROLE_DIREKTOR_ADMIN, ROLE_KLASEN_RAKOVODITEL, ROLE_PREDMETEN_NASTAVNIK
186 default -> wallet = "Nema";
187 }
188
189 return ResponseEntity.ok(Map.of(
190 "id", user.getId(),
191 "email", user.getUsername(),
192 "roles", user.getAuthorities(),
193 "saved_wallet", wallet
194 ));
195 }
196
197}
198
199
Note: See TracBrowser for help on using the repository browser.