瀏覽代碼

AuthController for user login added

JaseG256 6 年之前
父節點
當前提交
61722ac635
共有 1 個文件被更改,包括 98 次插入0 次删除
  1. 98
    0
      ZipTeamOrange-server/src/main/java/ZipTeamOrange/controller/AuthController.java

+ 98
- 0
ZipTeamOrange-server/src/main/java/ZipTeamOrange/controller/AuthController.java 查看文件

@@ -0,0 +1,98 @@
1
+package ZipTeamOrange.controller;
2
+
3
+import ZipTeamOrange.exception.AppException;
4
+import ZipTeamOrange.model.Role;
5
+import ZipTeamOrange.model.RoleName;
6
+import ZipTeamOrange.model.User;
7
+import ZipTeamOrange.payload.ApiResponse;
8
+import ZipTeamOrange.payload.JwtAuthenticationResponse;
9
+import ZipTeamOrange.payload.LoginRequest;
10
+import ZipTeamOrange.payload.SignUpRequest;
11
+import ZipTeamOrange.repository.RoleRepository;
12
+import ZipTeamOrange.repository.UserRepository;
13
+import ZipTeamOrange.security.JwtTokenProvider;
14
+import org.springframework.beans.factory.annotation.Autowired;
15
+import org.springframework.http.HttpStatus;
16
+import org.springframework.http.ResponseEntity;
17
+import org.springframework.security.authentication.AuthenticationManager;
18
+import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
19
+import org.springframework.security.core.Authentication;
20
+import org.springframework.security.core.context.SecurityContextHolder;
21
+import org.springframework.security.crypto.password.PasswordEncoder;
22
+import org.springframework.web.bind.annotation.PostMapping;
23
+import org.springframework.web.bind.annotation.RequestBody;
24
+import org.springframework.web.bind.annotation.RequestMapping;
25
+import org.springframework.web.bind.annotation.RestController;
26
+import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
27
+
28
+import javax.validation.Valid;
29
+import java.net.URI;
30
+import java.util.Collections;
31
+
32
+@RestController
33
+@RequestMapping("/api/auth")
34
+public class AuthController {
35
+
36
+    @Autowired
37
+    AuthenticationManager authenticationManager;
38
+
39
+    @Autowired
40
+    UserRepository userRepository;
41
+
42
+    @Autowired
43
+    RoleRepository roleRepository;
44
+
45
+    @Autowired
46
+    PasswordEncoder passwordEncoder;
47
+
48
+    @Autowired
49
+    JwtTokenProvider tokenProvider;
50
+
51
+    @PostMapping("/signin")
52
+    public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) {
53
+
54
+        Authentication authentication = authenticationManager.authenticate(
55
+                new UsernamePasswordAuthenticationToken(
56
+                        loginRequest.getUsernameOrEmail(),
57
+                        loginRequest.getPassword()
58
+                )
59
+        );
60
+
61
+        SecurityContextHolder.getContext().setAuthentication(authentication);
62
+
63
+        String jwt = tokenProvider.generateToken(authentication);
64
+        return ResponseEntity.ok(new JwtAuthenticationResponse(jwt));
65
+    }
66
+
67
+    @PostMapping("/signup")
68
+    public ResponseEntity<?> registerUser(@Valid @RequestBody SignUpRequest signUpRequest) {
69
+        if(userRepository.existsByUsername(signUpRequest.getUsername())) {
70
+            return new ResponseEntity(new ApiResponse(false, "Username is already taken!"),
71
+                    HttpStatus.BAD_REQUEST);
72
+        }
73
+
74
+        if(userRepository.existsByEmail(signUpRequest.getEmail())) {
75
+            return new ResponseEntity(new ApiResponse(false, "Email Address already in use!"),
76
+                    HttpStatus.BAD_REQUEST);
77
+        }
78
+
79
+        // Creating user's account
80
+        User user = new User(signUpRequest.getUsername(),
81
+                signUpRequest.getEmail(), signUpRequest.getPassword());
82
+
83
+        user.setPassword(passwordEncoder.encode(user.getPassword()));
84
+
85
+        Role userRole = roleRepository.findByName(RoleName.ROLE_USER)
86
+                .orElseThrow(() -> new AppException("User Role not set."));
87
+
88
+        user.setRoles(Collections.singleton(userRole));
89
+
90
+        User result = userRepository.save(user);
91
+
92
+        URI location = ServletUriComponentsBuilder
93
+                .fromCurrentContextPath().path("/api/users/{username}")
94
+                .buildAndExpand(result.getUsername()).toUri();
95
+
96
+        return ResponseEntity.created(location).body(new ApiResponse(true, "User registered successfully"));
97
+    }
98
+}