ba26106c961e0484660794b2a71b1f0f7395998f
[ccsdk/features.git] /
1 /*
2  * ============LICENSE_START=======================================================
3  * ONAP : ccsdk features
4  * ================================================================================
5  * Copyright (C) 2020 highstreet technologies GmbH Intellectual Property.
6  * All rights reserved.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *     http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  *
21  */
22 package org.onap.ccsdk.features.sdnr.wt.oauthprovider.data;
23
24 import com.fasterxml.jackson.annotation.JsonIgnore;
25 import java.io.File;
26 import java.io.FileNotFoundException;
27 import java.io.IOException;
28 import java.nio.file.Files;
29 import java.util.List;
30 import java.util.Random;
31 import java.util.regex.Matcher;
32 import java.util.regex.Pattern;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
35
36 public class Config {
37
38     private static final Logger LOG = LoggerFactory.getLogger(Config.class);
39     private static final String DEFAULT_CONFIGFILENAME = "etc/oauth-provider.config.json";
40     private static final String ENVVARIABLE = "${";
41     private static final String REGEXENVVARIABLE = "(\\$\\{[A-Z0-9_-]+\\})";
42     private static final Pattern pattern = Pattern.compile(REGEXENVVARIABLE);
43     private static final String DEFAULT_TOKENISSUER = "Opendaylight";
44     private static final String DEFAULT_TOKENSECRET = generateSecret();
45     private static final String DEFAULT_REDIRECTURI = "/odlux/index.html#/oauth?token=";
46     private static final String DEFAULT_SUPPORTODLUSERS = "true";
47     private static Config _instance;
48
49
50     private List<OAuthProviderConfig> providers;
51     private String host;
52     private String redirectUri;
53     private String supportOdlUsers;
54     private String tokenSecret;
55     private String tokenIssuer;
56
57
58     @Override
59     public String toString() {
60         return "Config [providers=" + providers + ", host=" + host + ", redirectUri=" + redirectUri
61                 + ", supportOdlUsers=" + supportOdlUsers + ", tokenSecret=" + tokenSecret + ", tokenIssuer="
62                 + tokenIssuer + "]";
63     }
64
65
66
67     public List<OAuthProviderConfig> getProviders() {
68         return providers;
69     }
70
71     public void setProviders(List<OAuthProviderConfig> providers) {
72         this.providers = providers;
73     }
74
75     public String getHost() {
76         return host;
77     }
78
79     public void setHost(String host) {
80         this.host = host;
81     }
82
83     public String getRedirectUri() {
84         return redirectUri;
85     }
86
87     public void setRedirectUri(String redirectUri) {
88         this.redirectUri = redirectUri;
89     }
90
91     public String getSupportOdlUsers() {
92         return supportOdlUsers;
93     }
94
95     public void setSupportOdlUsers(String supportOdlUsers) {
96         this.supportOdlUsers = supportOdlUsers;
97     }
98
99     public String getTokenSecret() {
100         return tokenSecret;
101     }
102
103     public void setTokenSecret(String tokenSecret) {
104         this.tokenSecret = tokenSecret;
105     }
106
107     public String getTokenIssuer() {
108         return tokenIssuer;
109     }
110
111     public void setTokenIssuer(String tokenIssuer) {
112         this.tokenIssuer = tokenIssuer;
113     }
114
115     @JsonIgnore
116     private void handleEnvironmentVars() {
117         if (isEnvExpression(tokenIssuer)) {
118             this.tokenIssuer = getProperty(tokenIssuer, null);
119         }
120         if (isEnvExpression(tokenSecret)) {
121             this.tokenSecret = getProperty(tokenSecret, null);
122         }
123         if (isEnvExpression(host)) {
124             this.host = getProperty(host, null);
125         }
126         if (isEnvExpression(redirectUri)) {
127             this.redirectUri = getProperty(redirectUri, null);
128         }
129         if (isEnvExpression(supportOdlUsers)) {
130             this.supportOdlUsers = getProperty(supportOdlUsers, null);
131         }
132     }
133
134     @JsonIgnore
135     private void handleDefaultValues() {
136         if (tokenIssuer == null || tokenIssuer.isEmpty()) {
137             this.tokenIssuer = DEFAULT_TOKENISSUER;
138         }
139         if (tokenSecret == null || tokenSecret.isEmpty()) {
140             this.tokenSecret = DEFAULT_TOKENSECRET;
141         }
142         if (redirectUri == null || redirectUri.isEmpty()) {
143             this.redirectUri = DEFAULT_REDIRECTURI;
144         }
145         if (supportOdlUsers == null || supportOdlUsers.isEmpty()) {
146             this.supportOdlUsers = DEFAULT_SUPPORTODLUSERS;
147         }
148     }
149
150     static boolean isEnvExpression(String key) {
151         return key != null && key.contains(ENVVARIABLE);
152     }
153
154     private static String generateSecret() {
155         int leftLimit = 48; // numeral '0'
156         int rightLimit = 122; // letter 'z'
157         int targetStringLength = 30;
158         Random random = new Random();
159
160         String generatedString = random.ints(leftLimit, rightLimit + 1)
161                 .filter(i -> (i <= 57 || i >= 65) && (i <= 90 || i >= 97)).limit(targetStringLength)
162                 .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString();
163         return generatedString;
164     }
165
166     /**
167      *
168      * @param key environment var
169      * @param defValue default value if no env var found
170      * @return
171      */
172     public static String getProperty(final String key, final String defValue) {
173         String value = defValue;
174         //try to read env var
175         boolean found = false;
176         if (isEnvExpression(key)) {
177
178             LOG.info("try to find env var(s) for {}", key);
179             final Matcher matcher = pattern.matcher(key);
180             String tmp = new String(key);
181             while (matcher.find() && matcher.groupCount() > 0) {
182                 final String mkey = matcher.group(1);
183                 if (mkey != null) {
184                     try {
185                         LOG.info("match found for v={} and env key={}", key, mkey);
186                         String envvar = mkey.substring(2, mkey.length() - 1);
187                         String env = System.getenv(envvar);
188                         tmp = tmp.replace(mkey, env == null ? "" : env);
189                         if (env != null && env != "") {
190                             found = true;
191                         }
192                     } catch (SecurityException e) {
193                         LOG.warn("unable to read env {}: {}", key, e);
194                     }
195                 }
196             }
197             if (found) {
198                 value = tmp;
199             }
200         }
201         return value;
202     }
203
204     public static boolean getPropertyBoolean(String key, boolean defaultValue) {
205         final String value = getProperty(key, String.valueOf(defaultValue));
206         return value.equals("true");
207     }
208
209     public static Config load(String filename) throws IOException {
210         CustomObjectMapper mapper = new CustomObjectMapper();
211         File file = new File(filename);
212         if (!file.exists()) {
213             throw new FileNotFoundException();
214         }
215         String content = String.join("", Files.readAllLines(file.toPath()));
216         Config cfg = mapper.readValue(content, Config.class);
217         cfg.handleEnvironmentVars();
218         cfg.handleDefaultValues();
219         return cfg;
220     }
221
222
223     @JsonIgnore
224     public boolean doSupportOdlUsers() {
225         return "true".equals(this.supportOdlUsers);
226     }
227
228
229
230     public static Config getInstance() throws IOException {
231         if(_instance==null) {
232             _instance = load(DEFAULT_CONFIGFILENAME);
233         }
234         return _instance;
235     }
236
237
238 }