Auth.java

  1. package no.nav.data.common.security.domain;

  2. import jakarta.persistence.*;
  3. import lombok.AllArgsConstructor;
  4. import lombok.Builder;
  5. import lombok.Data;
  6. import lombok.NoArgsConstructor;
  7. import no.nav.data.common.security.Encryptor;
  8. import org.springframework.util.Assert;

  9. import java.time.LocalDateTime;
  10. import java.util.UUID;

  11. @Data
  12. @Builder
  13. @AllArgsConstructor
  14. @NoArgsConstructor
  15. @Entity
  16. @Table(name = "AUTH")
  17. public class Auth {

  18.     @Id
  19.     @Column(name = "ID")
  20.     private UUID id;

  21.     @Column(name = "USER_ID")
  22.     private String userId;
  23.     @Column(name = "REFRESH_TOKEN")
  24.     // Doubles as CodeVerifier before session is created
  25.     private String encryptedRefreshToken;
  26.     @Column(name = "INITIATED")
  27.     private LocalDateTime initiated;
  28.     @Column(name = "LAST_ACTIVE")
  29.     private LocalDateTime lastActive;

  30.     @Transient
  31.     private transient Encryptor encryptor;
  32.     @Transient
  33.     private transient String sessionKey;
  34.     @Transient
  35.     private transient String accessToken;

  36.     public Auth addSecret(Encryptor encryptor, String sessionKey) {
  37.         this.encryptor = encryptor;
  38.         this.sessionKey = sessionKey;
  39.         return this;
  40.     }

  41.     public void addAccessToken(String accessToken) {
  42.         this.accessToken = accessToken;
  43.     }

  44.     public String decryptRefreshToken() {
  45.         Assert.notNull(encryptor, "not initialized");
  46.         Assert.notNull(sessionKey, "not initialized");
  47.         return encryptor.decrypt(sessionKey + encryptedRefreshToken);
  48.     }

  49.     public String session() {
  50.         return getId().toString().replace("-", "") + sessionKey;
  51.     }

  52.     public String getCodeVerifier() {
  53.         Assert.isTrue(encryptedRefreshToken.length() <= 128, "This session does not contain a CodeVerifier");
  54.         return encryptedRefreshToken;
  55.     }

  56.     public static class AuthBuilder {

  57.         public AuthBuilder generateId() {
  58.             id = UUID.randomUUID();
  59.             return this;
  60.         }
  61.     }
  62. }