Bläddra i källkod

Config for user auditing added

JaseG256 6 år sedan
förälder
incheckning
0febee3706

+ 31
- 0
ZipTeamOrange-server/src/main/java/ZipTeamOrange/Config/AuditingConfig.java Visa fil

@@ -1,10 +1,41 @@
1 1
 package ZipTeamOrange.config;
2 2
 
3 3
 
4
+import ZipTeamOrange.security.UserPrincipal;
5
+import org.springframework.context.annotation.Bean;
4 6
 import org.springframework.context.annotation.Configuration;
7
+import org.springframework.data.domain.AuditorAware;
5 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;
6 14
 
7 15
 @Configuration
8 16
 @EnableJpaAuditing
9 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
+    }
10 41
 }

+ 38
- 0
ZipTeamOrange-server/src/main/java/ZipTeamOrange/model/Audit/UserDateAudit.java Visa fil

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