• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

geosolutions-it / MapStore2 / 15422327504

03 Jun 2025 04:08PM UTC coverage: 76.952% (-0.04%) from 76.993%
15422327504

Pull #11024

github

web-flow
Merge 2ddc9a6d7 into 2dbe8dab2
Pull Request #11024: Update User Guide - Upload image on Text Widget

31021 of 48282 branches covered (64.25%)

38629 of 50199 relevant lines covered (76.95%)

36.23 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

97.44
/web/client/utils/SecurityUtils.js
1
/**
2
import { keys } from 'lodash';
3
 * Copyright 2016, GeoSolutions Sas.
4
 * All rights reserved.
5
 *
6
 * This source code is licensed under the BSD-style license found in the
7
 * LICENSE file in the root directory of this source tree.
8
 */
9

10
import ConfigUtils from "./ConfigUtils";
11
import URL from "url";
12
import assign from "object-assign";
13
import head from "lodash/head";
14
import isNil from "lodash/isNil";
15
import isArray from "lodash/isArray";
16
import isEmpty from "lodash/isEmpty";
17

18
import {setStore as stateSetStore, getState} from "./StateUtils";
19

20
export const USER_GROUP_ALL = 'everyone';
1✔
21

22
export function getCredentials(id) {
23
    const securityStorage = JSON.parse(sessionStorage.getItem('credentialStorage') ?? "{}");
209✔
24
    return securityStorage[id] || {};
209✔
25
}
26
export function setCredentials(id, credentials) {
27
    const securityStorage = JSON.parse(sessionStorage.getItem('credentialStorage') ?? "{}");
21✔
28
    sessionStorage.setItem('credentialStorage', JSON.stringify(assign({}, securityStorage, {[id]: credentials})));
21✔
29
}
30
/**
31
 * Stores the logged user security information.
32
 */
33
export function setStore(store) {
34
    stateSetStore(store);
10✔
35
}
36

37
/**
38
 * Gets security state form the store.
39
 */
40
export function getSecurityInfo() {
41
    return getState().security || {};
384✔
42
}
43

44
/**
45
 * Returns the current user or undefined if not available.
46
 */
47
export function getUser() {
48
    return getSecurityInfo()?.user;
12✔
49
}
50

51
/**
52
 * Returns the current user basic authentication header value.
53
 */
54
export function getBasicAuthHeader() {
55
    return getSecurityInfo()?.authHeader;
3✔
56
}
57

58
/**
59
 * Returns the current user access token value.
60
 */
61
export function getToken() {
62
    return getSecurityInfo()?.token;
351✔
63
}
64

65
/**
66
 * Returns the current user refresh token value.
67
 * The refresh token is used to get a new access token.
68
 */
69
export function getRefreshToken() {
70
    return getSecurityInfo()?.refresh_token;
18✔
71
}
72

73
/**
74
 * Return the user attributes as an array. If the user is undefined or
75
 * doesn't have any attributes an empty array is returned.
76
 */
77
export function getUserAttributes(providedUser) {
78
    const user = providedUser || getUser();
29✔
79
    if (!user || !user.attribute) {
29✔
80
        // not user defined or the user doesn't have any attributes
81
        return [];
17✔
82
    }
83
    const attributes = user.attribute;
12✔
84
    // if the user has only one attribute we need to put it in an array
85
    return isArray(attributes) ? attributes : [attributes];
12✔
86
}
87

88
/**
89
 * Search in the user attributes an attribute that matches the provided
90
 * attribute name. The search will not be case sensitive. Undefined is
91
 * returned if the attribute could not be found.
92
 */
93
export function findUserAttribute(attributeName) {
94
    // getting the user attributes
95
    const userAttributes = getUserAttributes();
8✔
96
    if (!userAttributes || !attributeName ) {
8!
97
        // the user as no attributes or the provided attribute name is undefined
98
        return null;
×
99
    }
100
    return head(userAttributes.filter(attribute => attribute.name
8✔
101
        && attribute.name.toLowerCase() === attributeName.toLowerCase()));
102
}
103

104
/**
105
 * Search in the user attributes an attribute that matches the provided
106
 * attribute name. The search will not be case sensitive. Undefined is
107
 * returned if the attribute could not be found otherwise the attribute
108
 * value is returned.
109
 */
110
export function findUserAttributeValue(attributeName) {
111
    const userAttribute = findUserAttribute(attributeName);
4✔
112
    return userAttribute?.value;
4✔
113
}
114

115
/**
116
 * Returns an array with the configured authentication rules. If no rules
117
 * were configured an empty array is returned.
118
 */
119
export function getAuthenticationRules() {
120
    return ConfigUtils.getConfigProp('authenticationRules') || [];
1,340✔
121
}
122

123
/**
124
 * Checks if authentication is activated or not.
125
 */
126
export function isAuthenticationActivated() {
127
    return ConfigUtils.getConfigProp('useAuthenticationRules') || false;
1,404✔
128
}
129

130
/**
131
 * Returns the authentication method that should be used for the provided URL.
132
 * We go through the authentication rules and find the first one that matches
133
 * the provided URL, if no rule matches the provided URL undefined is returned.
134
 */
135
export function getAuthenticationMethod(url) {
136
    const foundRule = head(getAuthenticationRules().filter(
318✔
137
        rule => rule && rule.urlPattern && url.match(new RegExp(rule.urlPattern, "i"))));
557✔
138
    return foundRule?.method;
318✔
139
}
140

141
/**
142
 * Returns the authentication rule that should be used for the provided URL.
143
 * We go through the authentication rules and find the first one that matches
144
 * the provided URL, if no rule matches the provided URL undefined is returned.
145
 */
146
export function getAuthenticationRule(url) {
147
    return head(getAuthenticationRules().filter(
1,020✔
148
        rule => rule && rule.urlPattern && url.match(new RegExp(rule.urlPattern, "i"))));
1,462✔
149
}
150

151
export function getAuthKeyParameter(url) {
152
    const foundRule = getAuthenticationRule(url);
496✔
153
    return foundRule?.authkeyParamName ?? 'authkey';
496✔
154
}
155

156
export function getAuthenticationHeaders(url, securityToken, security) {
157
    if (!url || !isAuthenticationActivated()) {
123✔
158
        return null;
35✔
159
    }
160
    const storedProtectedService = getCredentials(security?.sourceId);
88✔
161
    if (security && storedProtectedService) {
88✔
162
        return {
4✔
163
            "Authorization": `Basic ${btoa(storedProtectedService.username + ":" + storedProtectedService.password)}`
164
        };
165
    }
166
    switch (getAuthenticationMethod(url)) {
84✔
167
    case 'bearer': {
168
        const token = !isNil(securityToken) ? securityToken : getToken();
3!
169
        if (!token) {
3!
170
            return null;
×
171
        }
172
        return {
3✔
173
            "Authorization": `Bearer ${token}`
174
        };
175
    }
176
    case 'header': {
177
        const rule = getAuthenticationRule(url);
1✔
178
        return rule.headers;
1✔
179
    }
180
    default:
181
        // we cannot handle the required authentication method
182
        return null;
80✔
183
    }
184
}
185

186
/**
187
 * This method will add query parameter based authentications to an object
188
 * containing query parameters.
189
 */
190
export function addAuthenticationParameter(url, parameters, securityToken) {
191
    if (!url || !isAuthenticationActivated()) {
280✔
192
        return parameters;
86✔
193
    }
194
    switch (getAuthenticationMethod(url)) {
194✔
195
    case 'authkey': {
196
        const token = !isNil(securityToken) ? securityToken : getToken();
160✔
197
        if (!token) {
160✔
198
            return parameters;
12✔
199
        }
200
        const authParam = getAuthKeyParameter(url);
148✔
201
        return assign(parameters || {}, {[authParam]: token});
148✔
202
    }
203
    case 'test': {
204
        const rule = getAuthenticationRule(url);
1✔
205
        const token = rule ? rule.token : "";
1!
206
        const authParam = getAuthKeyParameter(url);
1✔
207
        return assign(parameters || {}, { [authParam]: token });
1!
208
    }
209
    default:
210
        // we cannot handle the required authentication method
211
        return parameters;
33✔
212
    }
213
}
214

215
/**
216
 * This method will add query parameter based authentications to an url.
217
 */
218
export function addAuthenticationToUrl(url) {
219
    if (!url || !isAuthenticationActivated()) {
5✔
220
        return url;
1✔
221
    }
222
    const parsedUrl = URL.parse(url, true);
4✔
223
    parsedUrl.query = addAuthenticationParameter(url, parsedUrl.query);
4✔
224
    // we need to remove this to force the use of query
225
    delete parsedUrl.search;
4✔
226
    return URL.format(parsedUrl);
4✔
227
}
228

229
export function clearNilValuesForParams(params = {}) {
68✔
230
    return Object.keys(params).reduce((pre, cur) => {
71✔
231
        return !isNil(params[cur]) ? {...pre, [cur]: params[cur]} : pre;
5✔
232
    }, {});
233
}
234

235
export function addAuthenticationToSLD(layerParams, options) {
236
    if (layerParams.SLD) {
233✔
237
        const parsed = URL.parse(layerParams.SLD, true);
2✔
238
        const params = addAuthenticationParameter(layerParams.SLD, parsed.query, options.securityToken);
2✔
239
        return assign({}, layerParams, {
2✔
240
            SLD: URL.format(assign({}, parsed, {
241
                query: params,
242
                search: undefined
243
            }))
244
        });
245
    }
246
    return layerParams;
231✔
247
}
248

249
export function cleanAuthParamsFromURL(url) {
250
    return ConfigUtils.filterUrlParams(url, [getAuthKeyParameter(url)].filter(p => p));
344✔
251
}
252

253
/**
254
 * it creates the headers function for axios config, if it finds a reference in sessionStorage
255
 * @param {string} protectedId the id of the protected service to look for in sessionStorage
256
 * @returns {object} the headers Basic
257
 */
258
export const getAuthorizationBasic = (protectedId) => {
1✔
259
    let headers = {};
76✔
260
    const storedProtectedService = getCredentials(protectedId);
76✔
261
    if (!isEmpty(storedProtectedService)) {
76✔
262
        headers = {
1✔
263
            Authorization: `Basic ${btoa(storedProtectedService.username + ":" + storedProtectedService.password)}`
264
        };
265
    }
266
    return headers;
76✔
267
};
268

269
/**
270
 * This utility class will get information about the current logged user directly from the store.
271
 */
272
const SecurityUtils = {
1✔
273
    getAuthorizationBasic,
274
    getCredentials,
275
    setCredentials,
276
    setStore,
277
    getSecurityInfo,
278
    getUser,
279
    getBasicAuthHeader,
280
    getToken,
281
    getRefreshToken,
282
    getUserAttributes,
283
    findUserAttribute,
284
    findUserAttributeValue,
285
    getAuthenticationRules,
286
    isAuthenticationActivated,
287
    getAuthenticationMethod,
288
    getAuthenticationRule,
289
    addAuthenticationToUrl,
290
    addAuthenticationParameter,
291
    clearNilValuesForParams,
292
    addAuthenticationToSLD,
293
    getAuthKeyParameter,
294
    cleanAuthParamsFromURL,
295
    getAuthenticationHeaders,
296
    USER_GROUP_ALL
297
};
298

299
export default SecurityUtils;
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc