forked from GabrielNat1/SpringBootApplication
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAuthController.java
More file actions
70 lines (55 loc) · 2.62 KB
/
AuthController.java
File metadata and controls
70 lines (55 loc) · 2.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package com.example.spring_boot_project.controller;
import com.example.spring_boot_project.Security.JwtUtil;
import com.example.spring_boot_project.dto.RegisterRequest;
import com.example.spring_boot_project.model.User;
import com.example.spring_boot_project.service.UserService;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
import java.util.Optional;
@RestController
@RequestMapping("/api/auth")
public class AuthController {
private final UserService userService;
private final BCryptPasswordEncoder passwordEncoder;
private final JwtUtil jwtUtil;
public AuthController(UserService userService, BCryptPasswordEncoder passwordEncoder, JwtUtil jwtUtil) {
this.userService = userService;
this.passwordEncoder = passwordEncoder;
this.jwtUtil = jwtUtil;
}
@PostMapping("/register")
public ResponseEntity<?> registerUser(@RequestBody RegisterRequest request) {
Optional<User> existingUser = userService.findByUsername(request.getUsername());
if (existingUser.isPresent()) {
return ResponseEntity.badRequest().body("Username already exists.");
}
User user = new User();
user.setUsername(request.getUsername());
user.setPassword(passwordEncoder.encode(request.getPassword()));
user.setRole("USER");
userService.save(user);
return ResponseEntity.ok().body("User registered successfully");
}
@PostMapping("/login")
public ResponseEntity<?> loginUser(@RequestBody Map<String, String> request) {
if (!request.containsKey("username") || !request.containsKey("password")) {
return ResponseEntity.badRequest().body("Username and password are required.");
}
String username = request.get("username");
String rawPassword = request.get("password");
Optional<User> userOptional = userService.findByUsername(username);
if (userOptional.isPresent() &&
passwordEncoder.matches(rawPassword, userOptional.get().getPassword())) {
String token = jwtUtil.generateToken(userOptional.get().getUsername());
return ResponseEntity.ok(Map.of("token", token));
}
return ResponseEntity.status(401).body("Invalid username or password.");
}
@GetMapping("/login")
public ResponseEntity<?> login(Authentication authentication) {
return ResponseEntity.ok().body("Logged in as: " + authentication.getName());
}
}