Merge "Stepping to springboot 3"
[nonrtric.git] / pmlog / src / main / java / org / oran / pmlog / clients / SecurityContext.java
1 /*-
2  * ========================LICENSE_START=================================
3  * O-RAN-SC
4  * %%
5  * Copyright (C) 2022 Nordix Foundation
6  * %%
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ========================LICENSE_END===================================
19  */
20
21 package org.oran.pmlog.clients;
22
23 import java.lang.invoke.MethodHandles;
24 import java.nio.file.Files;
25 import java.nio.file.Path;
26
27 import lombok.Setter;
28
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31 import org.springframework.beans.factory.annotation.Value;
32 import org.springframework.boot.context.properties.ConfigurationProperties;
33 import org.springframework.boot.context.properties.EnableConfigurationProperties;
34 import org.springframework.stereotype.Component;
35
36 @EnableConfigurationProperties
37 @ConfigurationProperties()
38 @Component
39 public class SecurityContext {
40
41     private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
42
43     private long tokenTimestamp = 0;
44
45     private String authToken = "";
46
47     @Setter
48     private Path authTokenFilePath;
49
50     public SecurityContext(@Value("${app.auth-token-file:}") String authTokenFilename) {
51         if (!authTokenFilename.isEmpty()) {
52             this.authTokenFilePath = Path.of(authTokenFilename);
53         }
54     }
55
56     public boolean isConfigured() {
57         return authTokenFilePath != null;
58     }
59
60     public synchronized String getBearerAuthToken() {
61         if (!isConfigured()) {
62             return "";
63         }
64         try {
65             long lastModified = authTokenFilePath.toFile().lastModified();
66             if (tokenTimestamp == 0 || lastModified != this.tokenTimestamp) {
67                 this.authToken = Files.readString(authTokenFilePath);
68                 this.tokenTimestamp = lastModified;
69             }
70         } catch (Exception e) {
71             logger.warn("Could not read auth token file: {}, reason: {}", authTokenFilePath, e.getMessage());
72         }
73         return this.authToken;
74     }
75
76 }