15 Commits

Auteur SHA1 Bericht Datum
  JaseG256 8371758f57 Merge branch 'lost' of https://git.zipcode.rocks/hallinanc/ZipTeam into lost 6 jaren geleden
  JaseG256 c2c537ee32 Roles not being set upon signup 6 jaren geleden
  JaseG256 36c94a8069 Udated Message Class 6 jaren geleden
  JaseG256 c928a5e936 Updated Chat class 6 jaren geleden
  JaseG256 d87e3ecf3f About to change the Chat class 6 jaren geleden
  JaseG256 0febee3706 Config for user auditing added 6 jaren geleden
  JaseG256 f67ba31b24 User authentication working but role not being set upon signup 6 jaren geleden
  JaseG256 61722ac635 AuthController for user login added 6 jaren geleden
  JaseG256 f8b4d4a179 Custom Runtime Exception classes added 6 jaren geleden
  JaseG256 797d1950fc Request and response payloads added 6 jaren geleden
  JaseG256 c0beff4c37 Data.sql file loads roles into DB 6 jaren geleden
  JaseG256 9d50f731f1 DateAudit class added 6 jaren geleden
  JaseG256 1524d4c5a0 User model working fine 6 jaren geleden
  JaseG256 647eee84b5 Merge branch 'dev' of https://git.zipcode.rocks/hallinanc/ZipTeam into dev 6 jaren geleden
  JaseG256 f696e9614b Merge branch 'dev' of https://git.zipcode.rocks/hallinanc/ZipTeam into dev 6 jaren geleden
47 gewijzigde bestanden met toevoegingen van 1423 en 265 verwijderingen
  1. 13
    1
      ZipTeamOrange-server/pom.xml
  2. 42
    0
      ZipTeamOrange-server/src/main/java/ZipTeamOrange/Config/AuditingConfig.java
  3. 96
    0
      ZipTeamOrange-server/src/main/java/ZipTeamOrange/Config/SecurityConfig.java
  4. 30
    0
      ZipTeamOrange-server/src/main/java/ZipTeamOrange/Controller/ChatController.java
  5. 33
    0
      ZipTeamOrange-server/src/main/java/ZipTeamOrange/Controller/MessageController.java
  6. 4
    3
      ZipTeamOrange-server/src/main/java/ZipTeamOrange/Controller/UserController.java
  7. 45
    0
      ZipTeamOrange-server/src/main/java/ZipTeamOrange/Model/Audit/DateAudit.java
  8. 68
    0
      ZipTeamOrange-server/src/main/java/ZipTeamOrange/Model/Chat.java
  9. 55
    0
      ZipTeamOrange-server/src/main/java/ZipTeamOrange/Model/Message.java
  10. 42
    0
      ZipTeamOrange-server/src/main/java/ZipTeamOrange/Model/Role.java
  11. 6
    0
      ZipTeamOrange-server/src/main/java/ZipTeamOrange/Model/RoleName.java
  12. 106
    0
      ZipTeamOrange-server/src/main/java/ZipTeamOrange/Model/User.java
  13. 27
    0
      ZipTeamOrange-server/src/main/java/ZipTeamOrange/Payload/ApiResponse.java
  14. 26
    0
      ZipTeamOrange-server/src/main/java/ZipTeamOrange/Payload/JwtAuthenticationResponse.java
  15. 27
    0
      ZipTeamOrange-server/src/main/java/ZipTeamOrange/Payload/LoginRequest.java
  16. 45
    0
      ZipTeamOrange-server/src/main/java/ZipTeamOrange/Payload/SignUpRequest.java
  17. 25
    0
      ZipTeamOrange-server/src/main/java/ZipTeamOrange/Repository/ChatRepository.java
  18. 30
    0
      ZipTeamOrange-server/src/main/java/ZipTeamOrange/Repository/MessageRepository.java
  19. 13
    0
      ZipTeamOrange-server/src/main/java/ZipTeamOrange/Repository/RoleRepository.java
  20. 23
    0
      ZipTeamOrange-server/src/main/java/ZipTeamOrange/Repository/UserRepository.java
  21. 13
    0
      ZipTeamOrange-server/src/main/java/ZipTeamOrange/Security/CurrentUser.java
  22. 41
    0
      ZipTeamOrange-server/src/main/java/ZipTeamOrange/Security/CustomUserDetailsService.java
  23. 26
    0
      ZipTeamOrange-server/src/main/java/ZipTeamOrange/Security/JwtAuthenticationEntryPoint.java
  24. 58
    0
      ZipTeamOrange-server/src/main/java/ZipTeamOrange/Security/JwtAuthenticationFilter.java
  25. 64
    0
      ZipTeamOrange-server/src/main/java/ZipTeamOrange/Security/JwtTokenProvider.java
  26. 107
    0
      ZipTeamOrange-server/src/main/java/ZipTeamOrange/Security/UserPrincipal.java
  27. 14
    0
      ZipTeamOrange-server/src/main/java/ZipTeamOrange/ZipTeamOrangeApplication.java
  28. 0
    52
      ZipTeamOrange-server/src/main/java/ZipTeamOrange/chat/Chat.java
  29. 0
    28
      ZipTeamOrange-server/src/main/java/ZipTeamOrange/chat/ChatController.java
  30. 0
    6
      ZipTeamOrange-server/src/main/java/ZipTeamOrange/chat/ChatRepository.java
  31. 19
    0
      ZipTeamOrange-server/src/main/java/ZipTeamOrange/config/WebMvcConfig.java
  32. 98
    0
      ZipTeamOrange-server/src/main/java/ZipTeamOrange/controller/AuthController.java
  33. 15
    0
      ZipTeamOrange-server/src/main/java/ZipTeamOrange/exception/AppException.java
  34. 16
    0
      ZipTeamOrange-server/src/main/java/ZipTeamOrange/exception/BadRequestException.java
  35. 30
    0
      ZipTeamOrange-server/src/main/java/ZipTeamOrange/exception/ResourceNotFoundException.java
  36. 0
    54
      ZipTeamOrange-server/src/main/java/ZipTeamOrange/message/Message.java
  37. 0
    31
      ZipTeamOrange-server/src/main/java/ZipTeamOrange/message/MessageController.java
  38. 0
    8
      ZipTeamOrange-server/src/main/java/ZipTeamOrange/message/MessageRepository.java
  39. 38
    0
      ZipTeamOrange-server/src/main/java/ZipTeamOrange/model/Audit/UserDateAudit.java
  40. 46
    0
      ZipTeamOrange-server/src/main/java/ZipTeamOrange/payload/ChatRequest.java
  41. 18
    0
      ZipTeamOrange-server/src/main/java/ZipTeamOrange/payload/MessageRequest.java
  42. 17
    0
      ZipTeamOrange-server/src/main/java/ZipTeamOrange/payload/UserIdentityAvailability.java
  43. 28
    0
      ZipTeamOrange-server/src/main/java/ZipTeamOrange/payload/UserSummary.java
  44. 0
    70
      ZipTeamOrange-server/src/main/java/ZipTeamOrange/user/User.java
  45. 0
    8
      ZipTeamOrange-server/src/main/java/ZipTeamOrange/user/UserRepository.java
  46. 16
    4
      ZipTeamOrange-server/src/main/resources/application.properties
  47. 3
    0
      ZipTeamOrange-server/src/main/resources/data.sql

+ 13
- 1
ZipTeamOrange-server/pom.xml Bestand weergeven

@@ -30,10 +30,22 @@
30 30
 			<artifactId>spring-boot-starter-data-jpa</artifactId>
31 31
 		</dependency>
32 32
 		<dependency>
33
+			<groupId>io.jsonwebtoken</groupId>
34
+			<artifactId>jjwt</artifactId>
35
+			<version>0.9.0</version>
36
+		</dependency>
37
+		<dependency>
38
+			<groupId>com.fasterxml.jackson.datatype</groupId>
39
+			<artifactId>jackson-datatype-jsr310</artifactId>
40
+		</dependency>
41
+		<dependency>
33 42
 			<groupId>org.springframework.boot</groupId>
34 43
 			<artifactId>spring-boot-starter-web</artifactId>
35 44
 		</dependency>
36
-
45
+		<dependency>
46
+			<groupId>org.springframework.boot</groupId>
47
+			<artifactId>spring-boot-starter-security</artifactId>
48
+		</dependency>
37 49
 		<dependency>
38 50
 			<groupId>org.springframework.boot</groupId>
39 51
 			<artifactId>spring-boot-starter-data-rest</artifactId>

+ 42
- 0
ZipTeamOrange-server/src/main/java/ZipTeamOrange/Config/AuditingConfig.java Bestand weergeven

@@ -0,0 +1,42 @@
1
+package ZipTeamOrange.config;
2
+
3
+
4
+import ZipTeamOrange.security.UserPrincipal;
5
+import org.springframework.context.annotation.Bean;
6
+import org.springframework.context.annotation.Configuration;
7
+import org.springframework.data.domain.AuditorAware;
8
+import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
9
+import org.springframework.security.authentication.AnonymousAuthenticationToken;
10
+import org.springframework.security.core.Authentication;
11
+import org.springframework.security.core.context.SecurityContextHolder;
12
+
13
+import java.util.Optional;
14
+
15
+@Configuration
16
+@EnableJpaAuditing
17
+public class AuditingConfig {
18
+
19
+    @Bean
20
+    public AuditorAware<Long> auditorProvider() {
21
+        return new SpringSecurityAuditAwareImpl();
22
+    }
23
+
24
+
25
+    class SpringSecurityAuditAwareImpl implements AuditorAware<Long> {
26
+
27
+        @Override
28
+        public Optional<Long> getCurrentAuditor() {
29
+            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
30
+
31
+            if (authentication == null ||
32
+                    !authentication.isAuthenticated() ||
33
+                    authentication instanceof AnonymousAuthenticationToken) {
34
+                return Optional.empty();
35
+            }
36
+
37
+            UserPrincipal userPrincipal = (UserPrincipal) authentication.getPrincipal();
38
+
39
+            return Optional.ofNullable(userPrincipal.getId());
40
+        }
41
+    }
42
+}

+ 96
- 0
ZipTeamOrange-server/src/main/java/ZipTeamOrange/Config/SecurityConfig.java Bestand weergeven

@@ -0,0 +1,96 @@
1
+package ZipTeamOrange.config;
2
+
3
+import ZipTeamOrange.security.CustomUserDetailsService;
4
+import ZipTeamOrange.security.JwtAuthenticationEntryPoint;
5
+import ZipTeamOrange.security.JwtAuthenticationFilter;
6
+import org.springframework.beans.factory.annotation.Autowired;
7
+import org.springframework.context.annotation.Bean;
8
+import org.springframework.context.annotation.Configuration;
9
+import org.springframework.http.HttpMethod;
10
+import org.springframework.security.authentication.AuthenticationManager;
11
+import org.springframework.security.config.BeanIds;
12
+import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
13
+import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
14
+import org.springframework.security.config.annotation.web.builders.HttpSecurity;
15
+import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
16
+import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
17
+import org.springframework.security.config.http.SessionCreationPolicy;
18
+import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
19
+import org.springframework.security.crypto.password.PasswordEncoder;
20
+import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
21
+
22
+@Configuration
23
+@EnableWebSecurity
24
+@EnableGlobalMethodSecurity(
25
+        securedEnabled = true,
26
+        jsr250Enabled = true,
27
+        prePostEnabled = true
28
+)
29
+public class SecurityConfig extends WebSecurityConfigurerAdapter {
30
+    @Autowired
31
+    CustomUserDetailsService customUserDetailsService;
32
+
33
+    @Autowired
34
+    private JwtAuthenticationEntryPoint unauthorizedHandler;
35
+
36
+    @Bean
37
+    public JwtAuthenticationFilter jwtAuthenticationFilter() {
38
+        return new JwtAuthenticationFilter();
39
+    }
40
+
41
+    @Override
42
+    public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
43
+        authenticationManagerBuilder
44
+                .userDetailsService(customUserDetailsService)
45
+                .passwordEncoder(passwordEncoder());
46
+    }
47
+
48
+    @Bean(BeanIds.AUTHENTICATION_MANAGER)
49
+    @Override
50
+    public AuthenticationManager authenticationManagerBean() throws Exception {
51
+        return super.authenticationManagerBean();
52
+    }
53
+
54
+    @Bean
55
+    public PasswordEncoder passwordEncoder() {
56
+        return new BCryptPasswordEncoder();
57
+    }
58
+
59
+    @Override
60
+    protected void configure(HttpSecurity http) throws Exception {
61
+        http
62
+                .cors()
63
+                .and()
64
+                .csrf()
65
+                .disable()
66
+                .exceptionHandling()
67
+                .authenticationEntryPoint(unauthorizedHandler)
68
+                .and()
69
+                .sessionManagement()
70
+                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
71
+                .and()
72
+                .authorizeRequests()
73
+                .antMatchers("/",
74
+                        "/favicon.ico",
75
+                        "/**/*.png",
76
+                        "/**/*.gif",
77
+                        "/**/*.svg",
78
+                        "/**/*.jpg",
79
+                        "/**/*.html",
80
+                        "/**/*.css",
81
+                        "/**/*.js")
82
+                .permitAll()
83
+                .antMatchers("/api/auth/**")
84
+                .permitAll()
85
+                .antMatchers("/api/user/checkUsernameAvailability", "/api/user/checkEmailAvailability")
86
+                .permitAll()
87
+                .antMatchers(HttpMethod.GET, "/api/polls/**", "/api/users/**")
88
+                .permitAll()
89
+                .anyRequest()
90
+                .authenticated();
91
+
92
+        // Add our custom JWT security filter
93
+        http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
94
+
95
+    }
96
+}

+ 30
- 0
ZipTeamOrange-server/src/main/java/ZipTeamOrange/Controller/ChatController.java Bestand weergeven

@@ -0,0 +1,30 @@
1
+//package ZipTeamOrange.controller;
2
+//
3
+//import ZipTeamOrange.model.Chat;
4
+//import ZipTeamOrange.repository.ChatRepository;
5
+//import org.springframework.beans.factory.annotation.Autowired;
6
+//import org.springframework.stereotype.controller;
7
+//import org.springframework.web.bind.annotation.*;
8
+//
9
+//@controller
10
+//@RequestMapping(path = "/chat")
11
+//@CrossOrigin(origins = {"http://localhost:8103"})
12
+//public class ChatController {
13
+//
14
+//    @Autowired
15
+//    private ChatRepository chatRepository;
16
+//
17
+//    @PostMapping(path="/add")
18
+//    public @ResponseBody
19
+//    Chat addNewChat(@RequestBody Chat chat){
20
+//        chatRepository.save(chat);
21
+//        return  chat;
22
+//    }
23
+//
24
+//    @GetMapping(path="/all")
25
+//    public @ResponseBody Iterable<Chat> getAllChat() {
26
+//        //this returns a JSON or XML with chats
27
+//        return chatRepository.findAll();
28
+//
29
+//    }
30
+//}

+ 33
- 0
ZipTeamOrange-server/src/main/java/ZipTeamOrange/Controller/MessageController.java Bestand weergeven

@@ -0,0 +1,33 @@
1
+//package ZipTeamOrange.controller;
2
+//
3
+//import ZipTeamOrange.model.Message;
4
+//import ZipTeamOrange.repository.MessageRepository;
5
+//import com.fasterxml.jackson.core.JsonProcessingException;
6
+//import com.fasterxml.jackson.databind.ObjectMapper;
7
+//import org.springframework.beans.factory.annotation.Autowired;
8
+//import org.springframework.web.bind.annotation.*;
9
+//
10
+//@RestController
11
+//@RequestMapping(path = "/message")
12
+//@CrossOrigin("http://localhost:8100")
13
+//public class MessageController {
14
+//    ObjectMapper ob = new ObjectMapper();
15
+//
16
+//    @Autowired
17
+//    private MessageRepository messageRepository;
18
+//    @PostMapping(path = "/add")
19
+//    public String postMessage(@RequestBody Message message) throws JsonProcessingException {
20
+//
21
+//        messageRepository.save(message);
22
+//
23
+//        return ob.writeValueAsString(message);
24
+//
25
+//    }
26
+//
27
+//    @GetMapping(path = "/all")
28
+//    public @ResponseBody Iterable<Message> getAllMessages(){
29
+//        return messageRepository.findAll();
30
+//    }
31
+//
32
+//
33
+//}

ZipTeamOrange-server/src/main/java/ZipTeamOrange/user/UserController.java → ZipTeamOrange-server/src/main/java/ZipTeamOrange/Controller/UserController.java Bestand weergeven

@@ -1,12 +1,13 @@
1
-package ZipTeamOrange.user;
1
+package ZipTeamOrange.controller;
2 2
 
3
+import ZipTeamOrange.model.User;
4
+import ZipTeamOrange.repository.UserRepository;
3 5
 import com.fasterxml.jackson.core.JsonProcessingException;
4 6
 import com.fasterxml.jackson.databind.ObjectMapper;
5 7
 import org.springframework.beans.factory.annotation.Autowired;
6
-import org.springframework.stereotype.Controller;
7 8
 import org.springframework.web.bind.annotation.*;
8 9
 
9
-@Controller
10
+@RestController
10 11
 @RequestMapping(path = "/user")
11 12
 public class UserController {
12 13
 

+ 45
- 0
ZipTeamOrange-server/src/main/java/ZipTeamOrange/Model/Audit/DateAudit.java Bestand weergeven

@@ -0,0 +1,45 @@
1
+package ZipTeamOrange.model.Audit;
2
+
3
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
4
+import org.springframework.data.annotation.CreatedDate;
5
+import org.springframework.data.annotation.LastModifiedDate;
6
+import org.springframework.data.jpa.domain.support.AuditingEntityListener;
7
+
8
+import javax.persistence.Column;
9
+import javax.persistence.EntityListeners;
10
+import javax.persistence.MappedSuperclass;
11
+import java.io.Serializable;
12
+import java.time.Instant;
13
+
14
+@MappedSuperclass
15
+@EntityListeners(AuditingEntityListener.class)
16
+@JsonIgnoreProperties(
17
+        value = {"createdAt", "updatedAt"},
18
+        allowGetters = true
19
+)
20
+public abstract class DateAudit implements Serializable {
21
+
22
+    @CreatedDate
23
+    @Column(nullable = false, updatable = false)
24
+    private Instant createdAt;
25
+
26
+    @LastModifiedDate
27
+    @Column(nullable = false)
28
+    private Instant updatedAt;
29
+
30
+    public Instant getCreatedAt() {
31
+        return createdAt;
32
+    }
33
+
34
+    public void setCreatedAt(Instant createdAt) {
35
+        this.createdAt = createdAt;
36
+    }
37
+
38
+    public Instant getUpdatedAt() {
39
+        return updatedAt;
40
+    }
41
+
42
+    public void setUpdatedAt(Instant updatedAt) {
43
+        this.updatedAt = updatedAt;
44
+    }
45
+}

+ 68
- 0
ZipTeamOrange-server/src/main/java/ZipTeamOrange/Model/Chat.java Bestand weergeven

@@ -0,0 +1,68 @@
1
+package ZipTeamOrange.model;
2
+
3
+import ZipTeamOrange.model.Audit.UserDateAudit;
4
+import ZipTeamOrange.model.Message;
5
+import ZipTeamOrange.model.User;
6
+import javax.persistence.*;
7
+import javax.validation.constraints.NotBlank;
8
+import java.util.Set;
9
+
10
+@Entity
11
+@Table(name = "chats")
12
+public class Chat extends UserDateAudit {
13
+
14
+    @Id
15
+    @GeneratedValue(strategy = GenerationType.IDENTITY)
16
+    private Long id;
17
+
18
+    @NotBlank
19
+    private String topic;
20
+
21
+    @OneToMany(mappedBy = "chat",
22
+    cascade = CascadeType.ALL,
23
+    fetch = FetchType.EAGER,
24
+    orphanRemoval = true)
25
+    private Set<Message> messages;
26
+
27
+//    @ManyToMany(mappedBy = "chat")
28
+//    private Set<User> users;
29
+
30
+    public Chat(String topic, Set<Message> messages) {
31
+        this.topic = topic;
32
+        this.messages = messages;
33
+    }
34
+
35
+    public Chat() { }
36
+
37
+    public Long getId() {
38
+        return id;
39
+    }
40
+
41
+    public void setId(Long id) {
42
+        this.id = id;
43
+    }
44
+
45
+    public String getTopic() {
46
+        return topic;
47
+    }
48
+
49
+    public void setTopic(String topic) {
50
+        this.topic = topic;
51
+    }
52
+
53
+    public Set<Message> getMessages() {
54
+        return messages;
55
+    }
56
+
57
+    public void setMessages(Set<Message> messages) {
58
+        this.messages = messages;
59
+    }
60
+
61
+    //    public Set<User> getUsers() {
62
+//        return users;
63
+//    }
64
+//
65
+//    public void setUsers(Set<User> users) {
66
+//        this.users = users;
67
+//    }
68
+}

+ 55
- 0
ZipTeamOrange-server/src/main/java/ZipTeamOrange/Model/Message.java Bestand weergeven

@@ -0,0 +1,55 @@
1
+package ZipTeamOrange.model;
2
+
3
+import ZipTeamOrange.model.Audit.DateAudit;
4
+import ZipTeamOrange.model.Audit.UserDateAudit;
5
+
6
+import javax.persistence.*;
7
+
8
+@Entity
9
+public class Message extends UserDateAudit {
10
+
11
+    @Id
12
+    @GeneratedValue(strategy = GenerationType.IDENTITY)
13
+    private long id;
14
+
15
+    String text;
16
+
17
+//    @ManyToOne
18
+//    @JoinColumn(name="user_id")
19
+//    User user;
20
+
21
+    @ManyToOne(fetch = FetchType.LAZY, optional = false)
22
+    @JoinColumn(name = "chat_id", nullable = false)
23
+    private Chat chat;
24
+
25
+    public Message() { }
26
+
27
+    public Message(String text) {
28
+        this.text = text;
29
+        //this.user = user;
30
+    }
31
+
32
+    public long getId() {
33
+        return id;
34
+    }
35
+
36
+    public void setId(long id) {
37
+        this.id = id;
38
+    }
39
+
40
+    public String getText() {
41
+        return text;
42
+    }
43
+
44
+    public void setText(String text) {
45
+        this.text = text;
46
+    }
47
+
48
+//    public User getUser() {
49
+//        return user;
50
+//    }
51
+//
52
+//    public void setUser(User user) {
53
+//        this.user = user;
54
+//    }
55
+}

+ 42
- 0
ZipTeamOrange-server/src/main/java/ZipTeamOrange/Model/Role.java Bestand weergeven

@@ -0,0 +1,42 @@
1
+package ZipTeamOrange.model;
2
+
3
+import org.hibernate.annotations.NaturalId;
4
+
5
+import javax.persistence.*;
6
+
7
+@Entity
8
+@Table(name = "roles")
9
+public class Role {
10
+    @Id
11
+    @GeneratedValue(strategy = GenerationType.IDENTITY)
12
+    private Long id;
13
+
14
+    @Enumerated(EnumType.STRING)
15
+    @NaturalId
16
+    @Column(length = 60)
17
+    private RoleName name;
18
+
19
+    public Role() {
20
+
21
+    }
22
+
23
+    public Role(RoleName name) {
24
+        this.name = name;
25
+    }
26
+
27
+    public Long getId() {
28
+        return id;
29
+    }
30
+
31
+    public void setId(Long id) {
32
+        this.id = id;
33
+    }
34
+
35
+    public RoleName getName() {
36
+        return name;
37
+    }
38
+
39
+    public void setName(RoleName name) {
40
+        this.name = name;
41
+    }
42
+}

+ 6
- 0
ZipTeamOrange-server/src/main/java/ZipTeamOrange/Model/RoleName.java Bestand weergeven

@@ -0,0 +1,6 @@
1
+package ZipTeamOrange.model;
2
+
3
+public enum  RoleName {
4
+    ROLE_USER,
5
+    ROLE_ADMIN
6
+}

+ 106
- 0
ZipTeamOrange-server/src/main/java/ZipTeamOrange/Model/User.java Bestand weergeven

@@ -0,0 +1,106 @@
1
+package ZipTeamOrange.model;
2
+
3
+import org.hibernate.annotations.NaturalId;
4
+
5
+import javax.persistence.*;
6
+import javax.validation.constraints.Email;
7
+import javax.validation.constraints.NotBlank;
8
+import java.util.HashSet;
9
+import java.util.Set;
10
+
11
+
12
+@Entity
13
+@Table(name = "users", uniqueConstraints = {
14
+        @UniqueConstraint(columnNames = {
15
+                "username"
16
+        }),
17
+        @UniqueConstraint(columnNames = {
18
+                "email"
19
+        })
20
+})
21
+public class User {
22
+
23
+    @Id
24
+    @GeneratedValue(strategy = GenerationType.IDENTITY)
25
+    private Long id;
26
+
27
+    @NotBlank
28
+    private String username;
29
+
30
+    @NotBlank
31
+    @NaturalId
32
+    @Email
33
+    private String email;
34
+
35
+    @NotBlank
36
+    private String password;
37
+
38
+    @ManyToMany(fetch = FetchType.LAZY)
39
+    @JoinTable(name = "user_roles",
40
+            joinColumns = @JoinColumn(name = "user_id"),
41
+            inverseJoinColumns = @JoinColumn(name = "role_id"))
42
+    private Set<Role> roles = new HashSet<>();
43
+
44
+
45
+//    @OneToMany(mappedBy = "user")
46
+//    private Set<Message> messages;
47
+//
48
+//    @ManyToMany
49
+//    @JoinTable(
50
+//            name = "USER_CHAT",
51
+//            joinColumns = { @JoinColumn(name = "user_id") },
52
+//            inverseJoinColumns = { @JoinColumn(name = "chat_id") }
53
+//    )
54
+//    private Set<Chat> chat;
55
+
56
+
57
+    public User() {
58
+    }
59
+
60
+
61
+    public User(String username, String email, String password) {
62
+        this.username = username;
63
+        this.email = email;
64
+        this.password = password;
65
+    }
66
+
67
+    public Long getId() {
68
+        return id;
69
+    }
70
+
71
+    public void setId(Long id) {
72
+        this.id = id;
73
+    }
74
+
75
+    public String getUsername() {
76
+        return username;
77
+    }
78
+
79
+    public void setUsername(String userName) {
80
+        this.username = userName;
81
+    }
82
+
83
+    public String getEmail() {
84
+        return email;
85
+    }
86
+
87
+    public void setEmail(String email) {
88
+        this.email = email;
89
+    }
90
+
91
+    public String getPassword() {
92
+        return password;
93
+    }
94
+
95
+    public void setPassword(String password) {
96
+        this.password = password;
97
+    }
98
+
99
+    public Set<Role> getRoles() {
100
+        return roles;
101
+    }
102
+
103
+    public void setRoles(Set<Role> roles) {
104
+        this.roles = roles;
105
+    }
106
+}

+ 27
- 0
ZipTeamOrange-server/src/main/java/ZipTeamOrange/Payload/ApiResponse.java Bestand weergeven

@@ -0,0 +1,27 @@
1
+package ZipTeamOrange.payload;
2
+
3
+public class ApiResponse {
4
+    private Boolean success;
5
+    private String message;
6
+
7
+    public ApiResponse(Boolean success, String message) {
8
+        this.success = success;
9
+        this.message = message;
10
+    }
11
+
12
+    public Boolean getSuccess() {
13
+        return success;
14
+    }
15
+
16
+    public void setSuccess(Boolean success) {
17
+        this.success = success;
18
+    }
19
+
20
+    public String getMessage() {
21
+        return message;
22
+    }
23
+
24
+    public void setMessage(String message) {
25
+        this.message = message;
26
+    }
27
+}

+ 26
- 0
ZipTeamOrange-server/src/main/java/ZipTeamOrange/Payload/JwtAuthenticationResponse.java Bestand weergeven

@@ -0,0 +1,26 @@
1
+package ZipTeamOrange.payload;
2
+
3
+public class JwtAuthenticationResponse {
4
+    private String accessToken;
5
+    private String tokenType = "Bearer";
6
+
7
+    public JwtAuthenticationResponse(String accessToken) {
8
+        this.accessToken = accessToken;
9
+    }
10
+
11
+    public String getAccessToken() {
12
+        return accessToken;
13
+    }
14
+
15
+    public void setAccessToken(String accessToken) {
16
+        this.accessToken = accessToken;
17
+    }
18
+
19
+    public String getTokenType() {
20
+        return tokenType;
21
+    }
22
+
23
+    public void setTokenType(String tokenType) {
24
+        this.tokenType = tokenType;
25
+    }
26
+}

+ 27
- 0
ZipTeamOrange-server/src/main/java/ZipTeamOrange/Payload/LoginRequest.java Bestand weergeven

@@ -0,0 +1,27 @@
1
+package ZipTeamOrange.payload;
2
+
3
+import javax.validation.constraints.NotBlank;
4
+
5
+public class LoginRequest {
6
+    @NotBlank
7
+    private String usernameOrEmail;
8
+
9
+    @NotBlank
10
+    private String password;
11
+
12
+    public String getUsernameOrEmail() {
13
+        return usernameOrEmail;
14
+    }
15
+
16
+    public void setUsernameOrEmail(String usernameOrEmail) {
17
+        this.usernameOrEmail = usernameOrEmail;
18
+    }
19
+
20
+    public String getPassword() {
21
+        return password;
22
+    }
23
+
24
+    public void setPassword(String password) {
25
+        this.password = password;
26
+    }
27
+}

+ 45
- 0
ZipTeamOrange-server/src/main/java/ZipTeamOrange/Payload/SignUpRequest.java Bestand weergeven

@@ -0,0 +1,45 @@
1
+package ZipTeamOrange.payload;
2
+
3
+import javax.validation.constraints.Email;
4
+import javax.validation.constraints.NotBlank;
5
+import javax.validation.constraints.Size;
6
+
7
+public class SignUpRequest {
8
+
9
+    @NotBlank
10
+    @Size(min = 3, max = 15)
11
+    private String username;
12
+
13
+    @NotBlank
14
+    @Size(max = 40)
15
+    @Email
16
+    private String email;
17
+
18
+    @NotBlank
19
+    @Size(min = 6, max = 20)
20
+    private String password;
21
+
22
+    public String getUsername() {
23
+        return username;
24
+    }
25
+
26
+    public void setUsername(String username) {
27
+        this.username = username;
28
+    }
29
+
30
+    public String getEmail() {
31
+        return email;
32
+    }
33
+
34
+    public void setEmail(String email) {
35
+        this.email = email;
36
+    }
37
+
38
+    public String getPassword() {
39
+        return password;
40
+    }
41
+
42
+    public void setPassword(String password) {
43
+        this.password = password;
44
+    }
45
+}

+ 25
- 0
ZipTeamOrange-server/src/main/java/ZipTeamOrange/Repository/ChatRepository.java Bestand weergeven

@@ -0,0 +1,25 @@
1
+package ZipTeamOrange.repository;
2
+
3
+import ZipTeamOrange.model.Chat;
4
+import org.springframework.data.domain.Page;
5
+import org.springframework.data.domain.Pageable;
6
+import org.springframework.data.domain.Sort;
7
+import org.springframework.data.jpa.repository.JpaRepository;
8
+
9
+import java.util.List;
10
+import java.util.Optional;
11
+
12
+public interface ChatRepository extends JpaRepository<Chat, Long> {
13
+
14
+    Optional<Chat> findById(Long chatId);
15
+
16
+    Page<Chat> findByCreatedBy(Long userId, Pageable pageable);
17
+
18
+    long countByCreatedBy(Long userId);
19
+
20
+    List<Chat> findByIdIn(List<Long> chatIds);
21
+
22
+    List<Chat> findByIdIn(List<Long> chatIds, Sort sort);
23
+
24
+}
25
+

+ 30
- 0
ZipTeamOrange-server/src/main/java/ZipTeamOrange/Repository/MessageRepository.java Bestand weergeven

@@ -0,0 +1,30 @@
1
+package ZipTeamOrange.repository;
2
+
3
+import ZipTeamOrange.model.Chat;
4
+import ZipTeamOrange.model.Message;
5
+import org.springframework.data.domain.Page;
6
+import org.springframework.data.domain.Pageable;
7
+import org.springframework.data.domain.Sort;
8
+import org.springframework.data.jpa.repository.JpaRepository;
9
+import org.springframework.data.jpa.repository.Query;
10
+import org.springframework.data.repository.query.Param;
11
+
12
+import java.util.List;
13
+import java.util.Optional;
14
+
15
+public interface MessageRepository extends JpaRepository<Message, Long> {
16
+
17
+    Optional<Message> findById(Long messageId);
18
+
19
+    Page<Message> findByCreatedBy(Long userId, Pageable pageable);
20
+
21
+    long countByCreatedBy(Long userId);
22
+
23
+//    @Query("SELECT COUNT(m.id) from Message v where v.user.id = :userId")
24
+//    long countByUserId(@Param("userId") Long userId);
25
+
26
+    List<Message> findByIdIn(List<Long> messageIds);
27
+
28
+    List<Message> findByIdIn(List<Long> messageIds, Sort sort);
29
+
30
+}

+ 13
- 0
ZipTeamOrange-server/src/main/java/ZipTeamOrange/Repository/RoleRepository.java Bestand weergeven

@@ -0,0 +1,13 @@
1
+package ZipTeamOrange.repository;
2
+
3
+import ZipTeamOrange.model.Role;
4
+import ZipTeamOrange.model.RoleName;
5
+import org.springframework.data.jpa.repository.JpaRepository;
6
+import org.springframework.stereotype.Repository;
7
+
8
+import java.util.Optional;
9
+
10
+@Repository
11
+public interface RoleRepository extends JpaRepository<Role, Long> {
12
+    Optional<Role> findByName(RoleName roleName);
13
+}

+ 23
- 0
ZipTeamOrange-server/src/main/java/ZipTeamOrange/Repository/UserRepository.java Bestand weergeven

@@ -0,0 +1,23 @@
1
+package ZipTeamOrange.repository;
2
+
3
+import ZipTeamOrange.model.User;
4
+import org.springframework.data.jpa.repository.JpaRepository;
5
+import org.springframework.stereotype.Repository;
6
+
7
+import java.util.List;
8
+import java.util.Optional;
9
+
10
+
11
+@Repository
12
+public interface UserRepository extends JpaRepository<User, Long> {
13
+    Optional<User> findByEmail(String email);
14
+
15
+    Optional<User> findByUsernameOrEmail(String username, String email);
16
+
17
+    List<User> findByIdIn(List<Long> userIds);
18
+
19
+    Optional<User> findByUsername(String username);
20
+
21
+    Boolean existsByUsername(String username);
22
+
23
+    Boolean existsByEmail(String email);}

+ 13
- 0
ZipTeamOrange-server/src/main/java/ZipTeamOrange/Security/CurrentUser.java Bestand weergeven

@@ -0,0 +1,13 @@
1
+package ZipTeamOrange.security;
2
+
3
+import org.springframework.security.core.annotation.AuthenticationPrincipal;
4
+
5
+import java.lang.annotation.*;
6
+
7
+@Target({ElementType.PARAMETER, ElementType.TYPE})
8
+@Retention(RetentionPolicy.RUNTIME)
9
+@Documented
10
+@AuthenticationPrincipal
11
+public @interface CurrentUser {
12
+
13
+}

+ 41
- 0
ZipTeamOrange-server/src/main/java/ZipTeamOrange/Security/CustomUserDetailsService.java Bestand weergeven

@@ -0,0 +1,41 @@
1
+package ZipTeamOrange.security;
2
+
3
+import ZipTeamOrange.model.User;
4
+import ZipTeamOrange.repository.UserRepository;
5
+import org.springframework.beans.factory.annotation.Autowired;
6
+import org.springframework.security.core.userdetails.UserDetails;
7
+import org.springframework.security.core.userdetails.UserDetailsService;
8
+import org.springframework.security.core.userdetails.UsernameNotFoundException;
9
+import org.springframework.stereotype.Service;
10
+import org.springframework.transaction.annotation.Transactional;
11
+
12
+@Service
13
+public class CustomUserDetailsService implements UserDetailsService {
14
+
15
+    @Autowired
16
+    UserRepository userRepository;
17
+
18
+    @Override
19
+    @Transactional
20
+    public UserDetails loadUserByUsername(String usernameOrEmail)
21
+            throws UsernameNotFoundException {
22
+        // Let people login with either username or email
23
+        User user = userRepository.findByUsernameOrEmail(usernameOrEmail, usernameOrEmail)
24
+                .orElseThrow(() ->
25
+                        new UsernameNotFoundException("User not found with username or email : " + usernameOrEmail)
26
+                );
27
+
28
+        return UserPrincipal.create(user);
29
+    }
30
+
31
+    // This method is used by JWTAuthenticationFilter
32
+    @Transactional
33
+    public UserDetails loadUserById(Long id) {
34
+        User user = userRepository.findById(id).orElseThrow(
35
+                () -> new UsernameNotFoundException("User not found with id : " + id)
36
+        );
37
+
38
+        return UserPrincipal.create(user);
39
+    }
40
+}
41
+

+ 26
- 0
ZipTeamOrange-server/src/main/java/ZipTeamOrange/Security/JwtAuthenticationEntryPoint.java Bestand weergeven

@@ -0,0 +1,26 @@
1
+package ZipTeamOrange.security;
2
+
3
+import org.slf4j.Logger;
4
+import org.slf4j.LoggerFactory;
5
+import org.springframework.security.core.AuthenticationException;
6
+import org.springframework.security.web.AuthenticationEntryPoint;
7
+import org.springframework.stereotype.Component;
8
+
9
+import javax.servlet.ServletException;
10
+import javax.servlet.http.HttpServletRequest;
11
+import javax.servlet.http.HttpServletResponse;
12
+import java.io.IOException;
13
+
14
+@Component
15
+public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
16
+
17
+    private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationEntryPoint.class);
18
+    @Override
19
+    public void commence(HttpServletRequest httpServletRequest,
20
+                         HttpServletResponse httpServletResponse,
21
+                         AuthenticationException e) throws IOException, ServletException {
22
+        logger.error("Responding with unauthorized error. Message - {}", e.getMessage());
23
+        httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED,
24
+                "Sorry, You're not authorized to access this resource.");
25
+    }
26
+}

+ 58
- 0
ZipTeamOrange-server/src/main/java/ZipTeamOrange/Security/JwtAuthenticationFilter.java Bestand weergeven

@@ -0,0 +1,58 @@
1
+package ZipTeamOrange.security;
2
+
3
+import org.slf4j.Logger;
4
+import org.slf4j.LoggerFactory;
5
+import org.springframework.beans.factory.annotation.Autowired;
6
+import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
7
+import org.springframework.security.core.context.SecurityContextHolder;
8
+import org.springframework.security.core.userdetails.UserDetails;
9
+import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
10
+import org.springframework.util.StringUtils;
11
+import org.springframework.web.filter.OncePerRequestFilter;
12
+
13
+import javax.servlet.FilterChain;
14
+import javax.servlet.ServletException;
15
+import javax.servlet.http.HttpServletRequest;
16
+import javax.servlet.http.HttpServletResponse;
17
+import java.io.IOException;
18
+
19
+public class JwtAuthenticationFilter extends OncePerRequestFilter {
20
+
21
+    @Autowired
22
+    private JwtTokenProvider tokenProvider;
23
+
24
+    @Autowired
25
+    private CustomUserDetailsService customUserDetailsService;
26
+
27
+    private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationFilter.class);
28
+
29
+    @Override
30
+    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
31
+        try {
32
+            String jwt = getJwtFromRequest(request);
33
+
34
+            if (StringUtils.hasText(jwt) && tokenProvider.validateToken(jwt)) {
35
+                Long userId = tokenProvider.getUserIdFromJWT(jwt);
36
+
37
+                UserDetails userDetails = customUserDetailsService.loadUserById(userId);
38
+                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
39
+                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
40
+
41
+                SecurityContextHolder.getContext().setAuthentication(authentication);
42
+            }
43
+        } catch (Exception ex) {
44
+            logger.error("Could not set user authentication in security context", ex);
45
+        }
46
+
47
+        filterChain.doFilter(request, response);
48
+    }
49
+
50
+    private String getJwtFromRequest(HttpServletRequest request) {
51
+        String bearerToken = request.getHeader("Authorization");
52
+        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
53
+            return bearerToken.substring(7, bearerToken.length());
54
+        }
55
+        return null;
56
+    }
57
+}
58
+

+ 64
- 0
ZipTeamOrange-server/src/main/java/ZipTeamOrange/Security/JwtTokenProvider.java Bestand weergeven

@@ -0,0 +1,64 @@
1
+package ZipTeamOrange.security;
2
+
3
+import io.jsonwebtoken.*;
4
+import org.slf4j.Logger;
5
+import org.slf4j.LoggerFactory;
6
+import org.springframework.beans.factory.annotation.Value;
7
+import org.springframework.security.core.Authentication;
8
+import org.springframework.stereotype.Component;
9
+
10
+import java.util.Date;
11
+
12
+@Component
13
+public class JwtTokenProvider {
14
+
15
+    private static final Logger logger = LoggerFactory.getLogger(JwtTokenProvider.class);
16
+
17
+    @Value("${app.jwtSecret}")
18
+    private String jwtSecret;
19
+
20
+    @Value("${app.jwtExpirationInMs}")
21
+    private int jwtExpirationInMs;
22
+
23
+    public String generateToken(Authentication authentication) {
24
+
25
+        UserPrincipal userPrincipal = (UserPrincipal) authentication.getPrincipal();
26
+
27
+        Date now = new Date();
28
+        Date expiryDate = new Date(now.getTime() + jwtExpirationInMs);
29
+
30
+        return Jwts.builder()
31
+                .setSubject(Long.toString(userPrincipal.getId()))
32
+                .setIssuedAt(new Date())
33
+                .setExpiration(expiryDate)
34
+                .signWith(SignatureAlgorithm.HS512, jwtSecret)
35
+                .compact();
36
+    }
37
+
38
+    public Long getUserIdFromJWT(String token) {
39
+        Claims claims = Jwts.parser()
40
+                .setSigningKey(jwtSecret)
41
+                .parseClaimsJws(token)
42
+                .getBody();
43
+
44
+        return Long.parseLong(claims.getSubject());
45
+    }
46
+
47
+    public boolean validateToken(String authToken) {
48
+        try {
49
+            Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(authToken);
50
+            return true;
51
+        } catch (SignatureException ex) {
52
+            logger.error("Invalid JWT signature");
53
+        } catch (MalformedJwtException ex) {
54
+            logger.error("Invalid JWT token");
55
+        } catch (ExpiredJwtException ex) {
56
+            logger.error("Expired JWT token");
57
+        } catch (UnsupportedJwtException ex) {
58
+            logger.error("Unsupported JWT token");
59
+        } catch (IllegalArgumentException ex) {
60
+            logger.error("JWT claims string is empty.");
61
+        }
62
+        return false;
63
+    }
64
+}

+ 107
- 0
ZipTeamOrange-server/src/main/java/ZipTeamOrange/Security/UserPrincipal.java Bestand weergeven

@@ -0,0 +1,107 @@
1
+package ZipTeamOrange.security;
2
+
3
+import ZipTeamOrange.model.User;
4
+import com.fasterxml.jackson.annotation.JsonIgnore;
5
+import org.springframework.security.core.GrantedAuthority;
6
+import org.springframework.security.core.authority.SimpleGrantedAuthority;
7
+import org.springframework.security.core.userdetails.UserDetails;
8
+
9
+import java.util.Collection;
10
+import java.util.List;
11
+import java.util.Objects;
12
+import java.util.stream.Collectors;
13
+
14
+public class UserPrincipal implements UserDetails {
15
+    private Long id;
16
+
17
+    private String name;
18
+
19
+    private String username;
20
+
21
+    @JsonIgnore
22
+    private String email;
23
+
24
+    @JsonIgnore
25
+    private String password;
26
+
27
+    private Collection<? extends GrantedAuthority> authorities;
28
+
29
+    public UserPrincipal(Long id, String username, String email, String password, Collection<? extends GrantedAuthority> authorities) {
30
+        this.id = id;
31
+        this.username = username;
32
+        this.email = email;
33
+        this.password = password;
34
+        this.authorities = authorities;
35
+    }
36
+
37
+    public static UserPrincipal create(User user) {
38
+        List<GrantedAuthority> authorities = user.getRoles().stream().map(role ->
39
+                new SimpleGrantedAuthority(role.getName().name())
40
+        ).collect(Collectors.toList());
41
+
42
+        return new UserPrincipal(
43
+                user.getId(),
44
+                user.getUsername(),
45
+                user.getEmail(),
46
+                user.getPassword(),
47
+                authorities
48
+        );
49
+    }
50
+
51
+    public Long getId() {
52
+        return id;
53
+    }
54
+
55
+    public String getEmail() {
56
+        return email;
57
+    }
58
+
59
+    @Override
60
+    public String getUsername() {
61
+        return username;
62
+    }
63
+
64
+    @Override
65
+    public String getPassword() {
66
+        return password;
67
+    }
68
+
69
+    @Override
70
+    public Collection<? extends GrantedAuthority> getAuthorities() {
71
+        return authorities;
72
+    }
73
+
74
+    @Override
75
+    public boolean isAccountNonExpired() {
76
+        return true;
77
+    }
78
+
79
+    @Override
80
+    public boolean isAccountNonLocked() {
81
+        return true;
82
+    }
83
+
84
+    @Override
85
+    public boolean isCredentialsNonExpired() {
86
+        return true;
87
+    }
88
+
89
+    @Override
90
+    public boolean isEnabled() {
91
+        return true;
92
+    }
93
+
94
+    @Override
95
+    public boolean equals(Object o) {
96
+        if (this == o) return true;
97
+        if (o == null || getClass() != o.getClass()) return false;
98
+        UserPrincipal that = (UserPrincipal) o;
99
+        return Objects.equals(id, that.id);
100
+    }
101
+
102
+    @Override
103
+    public int hashCode() {
104
+
105
+        return Objects.hash(id);
106
+    }
107
+}

+ 14
- 0
ZipTeamOrange-server/src/main/java/ZipTeamOrange/ZipTeamOrangeApplication.java Bestand weergeven

@@ -2,10 +2,24 @@ package ZipTeamOrange;
2 2
 
3 3
 import org.springframework.boot.SpringApplication;
4 4
 import org.springframework.boot.autoconfigure.SpringBootApplication;
5
+import org.springframework.boot.autoconfigure.domain.EntityScan;
6
+import org.springframework.data.jpa.convert.threeten.Jsr310JpaConverters;
7
+
8
+import javax.annotation.PostConstruct;
9
+import java.util.TimeZone;
5 10
 
6 11
 @SpringBootApplication
12
+@EntityScan(basePackageClasses = {
13
+
14
+		ZipTeamOrangeApplication.class,
15
+		Jsr310JpaConverters.class
16
+})
7 17
 public class ZipTeamOrangeApplication {
8 18
 
19
+	@PostConstruct
20
+	void init() {
21
+		TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
22
+	}
9 23
 
10 24
 	public static void main(String[] args) {
11 25
 		SpringApplication.run(ZipTeamOrangeApplication.class, args);

+ 0
- 52
ZipTeamOrange-server/src/main/java/ZipTeamOrange/chat/Chat.java Bestand weergeven

@@ -1,52 +0,0 @@
1
-package ZipTeamOrange.chat;
2
-
3
-import ZipTeamOrange.message.Message;
4
-import ZipTeamOrange.user.User;
5
-import javax.persistence.*;
6
-import java.util.Set;
7
-
8
-@Entity
9
-public class Chat {
10
-
11
-    @Id
12
-    @GeneratedValue(strategy = GenerationType.IDENTITY)
13
-    private Long id;
14
-    private String name;
15
-
16
-    @OneToMany(mappedBy = "chat")
17
-    private Set<Message> messages;
18
-
19
-    @ManyToMany(mappedBy = "chat")
20
-    private Set<User> users;
21
-
22
-    public Chat(String name, Set<User> users) {
23
-        this.name = name;
24
-        this.users = users;
25
-    }
26
-
27
-    public Chat(){}
28
-
29
-    public Long getId() {
30
-        return id;
31
-    }
32
-
33
-    public void setId(Long id) {
34
-        this.id = id;
35
-    }
36
-
37
-    public String getName() {
38
-        return name;
39
-    }
40
-
41
-    public void setName(String name) {
42
-        this.name = name;
43
-    }
44
-
45
-    public Set<User> getUsers() {
46
-        return users;
47
-    }
48
-
49
-    public void setUsers(Set<User> users) {
50
-        this.users = users;
51
-    }
52
-}

+ 0
- 28
ZipTeamOrange-server/src/main/java/ZipTeamOrange/chat/ChatController.java Bestand weergeven

@@ -1,28 +0,0 @@
1
-package ZipTeamOrange.chat;
2
-
3
-import org.springframework.beans.factory.annotation.Autowired;
4
-import org.springframework.stereotype.Controller;
5
-import org.springframework.web.bind.annotation.*;
6
-
7
-@Controller
8
-@RequestMapping(path = "/chat")
9
-@CrossOrigin(origins = {"http://localhost:8103"})
10
-public class ChatController {
11
-
12
-    @Autowired
13
-    private ChatRepository chatRepository;
14
-
15
-    @PostMapping(path="/add")
16
-    public @ResponseBody
17
-    Chat addNewChat(@RequestBody Chat chat){
18
-        chatRepository.save(chat);
19
-        return  chat;
20
-    }
21
-
22
-    @GetMapping(path="/all")
23
-    public @ResponseBody Iterable<Chat> getAllChat() {
24
-        //this returns a JSON or XML with chats
25
-        return chatRepository.findAll();
26
-
27
-    }
28
-}

+ 0
- 6
ZipTeamOrange-server/src/main/java/ZipTeamOrange/chat/ChatRepository.java Bestand weergeven

@@ -1,6 +0,0 @@
1
-package ZipTeamOrange.chat;
2
-
3
-import org.springframework.data.jpa.repository.JpaRepository;
4
-
5
-public interface ChatRepository extends JpaRepository<Chat, Long> {
6
-}

+ 19
- 0
ZipTeamOrange-server/src/main/java/ZipTeamOrange/config/WebMvcConfig.java Bestand weergeven

@@ -0,0 +1,19 @@
1
+package ZipTeamOrange.config;
2
+
3
+import org.springframework.context.annotation.Configuration;
4
+import org.springframework.web.servlet.config.annotation.CorsRegistry;
5
+import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
6
+
7
+@Configuration
8
+public class WebMvcConfig implements WebMvcConfigurer {
9
+
10
+    private final long MAX_AGE_SECS = 3600;
11
+
12
+    @Override
13
+    public void addCorsMappings(CorsRegistry registry) {
14
+        registry.addMapping("/**")
15
+                .allowedOrigins("*")
16
+                .allowedMethods("HEAD", "OPTIONS", "GET", "POST", "PUT", "PATCH", "DELETE")
17
+                .maxAge(MAX_AGE_SECS);
18
+    }
19
+}

+ 98
- 0
ZipTeamOrange-server/src/main/java/ZipTeamOrange/controller/AuthController.java Bestand weergeven

@@ -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
+}

+ 15
- 0
ZipTeamOrange-server/src/main/java/ZipTeamOrange/exception/AppException.java Bestand weergeven

@@ -0,0 +1,15 @@
1
+package ZipTeamOrange.exception;
2
+
3
+import org.springframework.http.HttpStatus;
4
+import org.springframework.web.bind.annotation.ResponseStatus;
5
+
6
+@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
7
+public class AppException extends RuntimeException {
8
+    public AppException(String message) {
9
+        super(message);
10
+    }
11
+
12
+    public AppException(String message, Throwable cause) {
13
+        super(message, cause);
14
+    }
15
+}

+ 16
- 0
ZipTeamOrange-server/src/main/java/ZipTeamOrange/exception/BadRequestException.java Bestand weergeven

@@ -0,0 +1,16 @@
1
+package ZipTeamOrange.exception;
2
+
3
+import org.springframework.http.HttpStatus;
4
+import org.springframework.web.bind.annotation.ResponseStatus;
5
+
6
+@ResponseStatus(HttpStatus.BAD_REQUEST)
7
+public class BadRequestException extends RuntimeException {
8
+
9
+    public BadRequestException(String message) {
10
+        super(message);
11
+    }
12
+
13
+    public BadRequestException(String message, Throwable cause) {
14
+        super(message, cause);
15
+    }
16
+}

+ 30
- 0
ZipTeamOrange-server/src/main/java/ZipTeamOrange/exception/ResourceNotFoundException.java Bestand weergeven

@@ -0,0 +1,30 @@
1
+package ZipTeamOrange.exception;
2
+
3
+import org.springframework.http.HttpStatus;
4
+import org.springframework.web.bind.annotation.ResponseStatus;
5
+
6
+@ResponseStatus(HttpStatus.NOT_FOUND)
7
+public class ResourceNotFoundException extends RuntimeException {
8
+    private String resourceName;
9
+    private String fieldName;
10
+    private Object fieldValue;
11
+
12
+    public ResourceNotFoundException( String resourceName, String fieldName, Object fieldValue) {
13
+        super(String.format("%s not found with %s : '%s'", resourceName, fieldName, fieldValue));
14
+        this.resourceName = resourceName;
15
+        this.fieldName = fieldName;
16
+        this.fieldValue = fieldValue;
17
+    }
18
+
19
+    public String getResourceName() {
20
+        return resourceName;
21
+    }
22
+
23
+    public String getFieldName() {
24
+        return fieldName;
25
+    }
26
+
27
+    public Object getFieldValue() {
28
+        return fieldValue;
29
+    }
30
+}

+ 0
- 54
ZipTeamOrange-server/src/main/java/ZipTeamOrange/message/Message.java Bestand weergeven

@@ -1,54 +0,0 @@
1
-package ZipTeamOrange.message;
2
-
3
-import ZipTeamOrange.chat.Chat;
4
-import ZipTeamOrange.user.User;
5
-import javax.persistence.*;
6
-
7
-@Entity
8
-public class Message {
9
-
10
-    @Id
11
-    @GeneratedValue(strategy = GenerationType.IDENTITY)
12
-    private long id;
13
-    String message;
14
-    @ManyToOne
15
-    @JoinColumn(name="user_id")
16
-    User user;
17
-
18
-    @ManyToOne
19
-    @JoinColumn(name = "chat_id")
20
-    private Chat chat;
21
-
22
-
23
-    public Message(String message) {
24
-        this.message = message;
25
-        //this.user = user;
26
-    }
27
-
28
-
29
-    public Message(){}
30
-
31
-    public long getId() {
32
-        return id;
33
-    }
34
-
35
-    public void setId(long id) {
36
-        this.id = id;
37
-    }
38
-
39
-    public String getMessage() {
40
-        return message;
41
-    }
42
-
43
-    public void setMessage(String message) {
44
-        this.message = message;
45
-    }
46
-
47
-    public User getUser() {
48
-        return user;
49
-    }
50
-
51
-    public void setUser(User user) {
52
-        this.user = user;
53
-    }
54
-}

+ 0
- 31
ZipTeamOrange-server/src/main/java/ZipTeamOrange/message/MessageController.java Bestand weergeven

@@ -1,31 +0,0 @@
1
-package ZipTeamOrange.message;
2
-
3
-import com.fasterxml.jackson.core.JsonProcessingException;
4
-import com.fasterxml.jackson.databind.ObjectMapper;
5
-import org.springframework.beans.factory.annotation.Autowired;
6
-import org.springframework.web.bind.annotation.*;
7
-
8
-@RestController
9
-@RequestMapping(path = "/message")
10
-@CrossOrigin("http://localhost:8100")
11
-public class MessageController {
12
-    ObjectMapper ob = new ObjectMapper();
13
-
14
-    @Autowired
15
-    private MessageRepository messageRepository;
16
-    @PostMapping(path = "/add")
17
-    public String postMessage(@RequestBody Message message) throws JsonProcessingException {
18
-
19
-        messageRepository.save(message);
20
-
21
-        return ob.writeValueAsString(message);
22
-
23
-    }
24
-
25
-    @GetMapping(path = "/all")
26
-    public @ResponseBody Iterable<Message> getAllMessages(){
27
-        return messageRepository.findAll();
28
-    }
29
-
30
-
31
-}

+ 0
- 8
ZipTeamOrange-server/src/main/java/ZipTeamOrange/message/MessageRepository.java Bestand weergeven

@@ -1,8 +0,0 @@
1
-package ZipTeamOrange.message;
2
-
3
-import org.springframework.data.jpa.repository.JpaRepository;
4
-
5
-public interface MessageRepository extends JpaRepository<Message, Long> {
6
-
7
-
8
-}

+ 38
- 0
ZipTeamOrange-server/src/main/java/ZipTeamOrange/model/Audit/UserDateAudit.java Bestand weergeven

@@ -0,0 +1,38 @@
1
+package ZipTeamOrange.model.Audit;
2
+
3
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
4
+import org.springframework.data.annotation.CreatedBy;
5
+import org.springframework.data.annotation.LastModifiedBy;
6
+
7
+import javax.persistence.Column;
8
+import javax.persistence.MappedSuperclass;
9
+
10
+@MappedSuperclass
11
+@JsonIgnoreProperties(
12
+        value = {"createdBy", "updatedBy"},
13
+        allowGetters = true
14
+)
15
+public abstract class UserDateAudit extends DateAudit {
16
+    @CreatedBy
17
+    @Column(updatable = false)
18
+    private Long createdBy;
19
+
20
+    @LastModifiedBy
21
+    private Long updatedBy;
22
+
23
+    public Long getCreatedBy() {
24
+        return createdBy;
25
+    }
26
+
27
+    public void setCreatedBy(Long createdBy) {
28
+        this.createdBy = createdBy;
29
+    }
30
+
31
+    public Long getUpdatedBy() {
32
+        return updatedBy;
33
+    }
34
+
35
+    public void setUpdatedBy(Long updatedBy) {
36
+        this.updatedBy = updatedBy;
37
+    }
38
+}

+ 46
- 0
ZipTeamOrange-server/src/main/java/ZipTeamOrange/payload/ChatRequest.java Bestand weergeven

@@ -0,0 +1,46 @@
1
+package ZipTeamOrange.payload;
2
+
3
+import javax.validation.Valid;
4
+import javax.validation.constraints.NotBlank;
5
+import javax.validation.constraints.NotNull;
6
+import javax.validation.constraints.Size;
7
+import java.util.List;
8
+
9
+public class ChatRequest {
10
+    @NotBlank
11
+    @Size(max = 140)
12
+    private String topic;
13
+
14
+    @NotNull
15
+    @Size(min = 2, max = 6)
16
+    @Valid
17
+    private List<MessageRequest> choices;
18
+
19
+//    @NotNull
20
+//    @Valid
21
+//    private PollLength pollLength;
22
+
23
+    public String getTopic() {
24
+        return topic;
25
+    }
26
+
27
+    public void setTopic(String topic) {
28
+        this.topic = topic;
29
+    }
30
+
31
+    public List<MessageRequest> getChoices() {
32
+        return choices;
33
+    }
34
+
35
+    public void setChoices(List<MessageRequest> choices) {
36
+        this.choices = choices;
37
+    }
38
+
39
+//    public PollLength getPollLength() {
40
+//        return pollLength;
41
+//    }
42
+//
43
+//    public void setPollLength(PollLength pollLength) {
44
+//        this.pollLength = pollLength;
45
+//    }
46
+}

+ 18
- 0
ZipTeamOrange-server/src/main/java/ZipTeamOrange/payload/MessageRequest.java Bestand weergeven

@@ -0,0 +1,18 @@
1
+package ZipTeamOrange.payload;
2
+
3
+import javax.validation.constraints.NotBlank;
4
+import javax.validation.constraints.Size;
5
+
6
+public class MessageRequest {
7
+    @NotBlank
8
+    @Size(max = 40)
9
+    private String text;
10
+
11
+    public String getText() {
12
+        return text;
13
+    }
14
+
15
+    public void setText(String text) {
16
+        this.text = text;
17
+    }
18
+}

+ 17
- 0
ZipTeamOrange-server/src/main/java/ZipTeamOrange/payload/UserIdentityAvailability.java Bestand weergeven

@@ -0,0 +1,17 @@
1
+package ZipTeamOrange.payload;
2
+
3
+public class UserIdentityAvailability {
4
+    private Boolean available;
5
+
6
+    public UserIdentityAvailability(Boolean available) {
7
+        this.available = available;
8
+    }
9
+
10
+    public Boolean getAvailable() {
11
+        return available;
12
+    }
13
+
14
+    public void setAvailable(Boolean available) {
15
+        this.available = available;
16
+    }
17
+}

+ 28
- 0
ZipTeamOrange-server/src/main/java/ZipTeamOrange/payload/UserSummary.java Bestand weergeven

@@ -0,0 +1,28 @@
1
+package ZipTeamOrange.payload;
2
+
3
+public class UserSummary {
4
+    private Long id;
5
+    private String username;
6
+
7
+    public UserSummary(Long id, String username, String name) {
8
+        this.id = id;
9
+        this.username = username;
10
+    }
11
+
12
+    public Long getId() {
13
+        return id;
14
+    }
15
+
16
+    public void setId(Long id) {
17
+        this.id = id;
18
+    }
19
+
20
+    public String getUsername() {
21
+        return username;
22
+    }
23
+
24
+    public void setUsername(String username) {
25
+        this.username = username;
26
+    }
27
+
28
+}

+ 0
- 70
ZipTeamOrange-server/src/main/java/ZipTeamOrange/user/User.java Bestand weergeven

@@ -1,70 +0,0 @@
1
-package ZipTeamOrange.user;
2
-
3
-import ZipTeamOrange.chat.Chat;
4
-import ZipTeamOrange.message.Message;
5
-import javax.persistence.*;
6
-import java.util.Set;
7
-
8
-
9
-@Entity
10
-public class User {
11
-
12
-    @Id
13
-    @GeneratedValue(strategy = GenerationType.IDENTITY)
14
-    private Long id;
15
-    private String userName;
16
-    private String email;
17
-    private String password;
18
-    @OneToMany(mappedBy = "user")
19
-    private Set<Message> messages;
20
-    @ManyToMany
21
-    @JoinTable(
22
-            name = "USER_CHAT",
23
-            joinColumns = { @JoinColumn(name = "user_id") },
24
-            inverseJoinColumns = { @JoinColumn(name = "chat_id") }
25
-    )
26
-    private Set<Chat> chat;
27
-
28
-
29
-    public User() {
30
-    }
31
-
32
-
33
-    public User(String userName, String email, String password) {
34
-        this.userName = userName;
35
-        this.email = email;
36
-        this.password = password;
37
-    }
38
-
39
-    public Long getId() {
40
-        return id;
41
-    }
42
-
43
-    public void setId(Long id) {
44
-        this.id = id;
45
-    }
46
-
47
-    public String getUserName() {
48
-        return userName;
49
-    }
50
-
51
-    public void setUserName(String userName) {
52
-        this.userName = userName;
53
-    }
54
-
55
-    public String getEmail() {
56
-        return email;
57
-    }
58
-
59
-    public void setEmail(String email) {
60
-        this.email = email;
61
-    }
62
-
63
-    public String getPassword() {
64
-        return password;
65
-    }
66
-
67
-    public void setPassword(String password) {
68
-        this.password = password;
69
-    }
70
-}

+ 0
- 8
ZipTeamOrange-server/src/main/java/ZipTeamOrange/user/UserRepository.java Bestand weergeven

@@ -1,8 +0,0 @@
1
-package ZipTeamOrange.user;
2
-
3
-import org.springframework.data.jpa.repository.JpaRepository;
4
-
5
-
6
-public interface UserRepository extends JpaRepository<User, Long>{
7
-
8
-}

+ 16
- 4
ZipTeamOrange-server/src/main/resources/application.properties Bestand weergeven

@@ -1,7 +1,19 @@
1 1
 #spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
2
+spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
2 3
 spring.jpa.hibernate.ddl-auto=create-drop
3
-spring.datasource.url=jdbc:mysql://localhost:3306/ZipTeamOrange?useSSL=false
4
+
5
+spring.datasource.url=jdbc:mysql://localhost:3306/ZipTeamOrange?useSSL=false&serverTimezone=UTC&useLegacyDatetimeCode=false
4 6
 spring.datasource.username=root
5
-#spring.datasource.password=password
6
-logging.level.org.hibernate.SQL=DEBUG
7
-logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
7
+spring.datasource.password=password
8
+
9
+## Hibernate Logging
10
+logging.level.org.hibernate.SQL= DEBUG
11
+
12
+## Jackson Properties
13
+spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS= false
14
+spring.jackson.time-zone= UTC
15
+logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
16
+
17
+## App Properties
18
+app.jwtSecret= JWTSuperSecretKey
19
+app.jwtExpirationInMs = 604800000

+ 3
- 0
ZipTeamOrange-server/src/main/resources/data.sql Bestand weergeven

@@ -0,0 +1,3 @@
1
+insert into roles(name) values ('ROLE_ADMIN');
2
+insert into roles(name) values ('ROLE_USER');
3
+--select count (m.id) from Messages where m.userId = userId;