10f701ec258c5bb95d67bf570ea964a6fc6e2e6d
[ccsdk/features.git] /
1 /*
2  * ============LICENSE_START=======================================================
3  * ONAP : ccsdk features
4  * ================================================================================
5  * Copyright (C) 2021 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.providers;
23
24 import com.fasterxml.jackson.core.JsonProcessingException;
25 import com.fasterxml.jackson.databind.JsonMappingException;
26 import java.util.ArrayList;
27 import java.util.HashMap;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.Optional;
31 import org.onap.ccsdk.features.sdnr.wt.oauthprovider.data.Config;
32 import org.onap.ccsdk.features.sdnr.wt.oauthprovider.data.OAuthProviderConfig;
33 import org.onap.ccsdk.features.sdnr.wt.oauthprovider.data.UnableToConfigureOAuthService;
34 import org.onap.ccsdk.features.sdnr.wt.oauthprovider.data.UserTokenPayload;
35 import org.onap.ccsdk.features.sdnr.wt.oauthprovider.http.client.MappedBaseHttpResponse;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38
39 public class GitlabProviderService extends AuthService {
40
41     private static final Logger LOG = LoggerFactory.getLogger(GitlabProviderService.class);
42     private Map<String, String> additionalTokenVerifierParams;
43     protected final List<String> randomIds;
44     private static final String API_USER_URI = "/api/v4/user";
45     private static final String API_GROUP_URI = "/api/v4/groups?min_access_level=10";
46
47     public GitlabProviderService(OAuthProviderConfig config, String redirectUri, TokenCreator tokenCreator) throws UnableToConfigureOAuthService {
48         super(config, redirectUri, tokenCreator);
49         this.additionalTokenVerifierParams = new HashMap<>();
50         this.additionalTokenVerifierParams.put("grant_type", "authorization_code");
51         this.randomIds = new ArrayList<>();
52     }
53
54     @Override
55     protected String getTokenVerifierUri() {
56         return "/oauth/token";
57     }
58
59     @Override
60     protected String getLoginUrl(String callbackUrl) {
61         return String.format("%s/oauth/authorize?client_id=%s&response_type=code&state=%s&redirect_uri=%s",
62                 this.config.getUrl(), urlEncode(this.config.getClientId()), this.createRandomId(), callbackUrl);
63     }
64
65     private String createRandomId() {
66         String rnd = null;
67         while(true) {
68             rnd=Config.generateSecret(20);
69             if(!this.randomIds.contains(rnd)) {
70                 break;
71             }
72         }
73         this.randomIds.add(rnd);
74         return rnd;
75     }
76
77     @Override
78     protected ResponseType getResponseType() {
79         return ResponseType.CODE;
80     }
81
82     @Override
83     protected Map<String, String> getAdditionalTokenVerifierParams() {
84         return this.additionalTokenVerifierParams;
85
86     }
87
88     @Override
89     protected boolean doSeperateRolesRequest() {
90         return true;
91     }
92
93     @Override
94     protected UserTokenPayload mapAccessToken(String spayload) throws JsonMappingException, JsonProcessingException {
95         return null;
96     }
97
98     @Override
99     protected UserTokenPayload requestUserRoles(String access_token, long issued_at, long expires_at) {
100         LOG.info("reqesting user roles with token={}", access_token);
101         Map<String, String> authHeaders = new HashMap<>();
102         authHeaders.put("Authorization", String.format("Bearer %s", access_token));
103         Optional<MappedBaseHttpResponse<GitlabUserInfo>> userInfo =
104                 this.getHttpClient().sendMappedRequest(API_USER_URI, "GET", null, authHeaders, GitlabUserInfo.class);
105         if (userInfo.isEmpty()) {
106             LOG.warn("unable to read user data");
107             return null;
108         }
109         Optional<MappedBaseHttpResponse<GitlabGroupInfo[]>> groupInfos = this.getHttpClient()
110                 .sendMappedRequest(API_GROUP_URI, "GET", null, authHeaders, GitlabGroupInfo[].class);
111         if (groupInfos.isEmpty()) {
112             LOG.warn("unable to read group information for user");
113             return null;
114         }
115         UserTokenPayload data = new UserTokenPayload();
116         GitlabUserInfo uInfo = userInfo.get().body;
117         data.setPreferredUsername(uInfo.getUsername());
118         data.setGivenName(uInfo.getName());
119         data.setFamilyName(uInfo.getName());
120         data.setIat(issued_at);
121         data.setExp(expires_at);
122         List<String> roles = new ArrayList<>();
123         GitlabGroupInfo[] uRoles = groupInfos.get().body;
124         for (GitlabGroupInfo uRole : uRoles) {
125             roles.add(uRole.getName());
126         }
127         data.setRoles(this.mapRoles(roles));
128         return data;
129     }
130
131
132
133     @SuppressWarnings("unused")
134     private static class GitlabUserInfo {
135
136         private String username;
137         private String name;
138
139         public String getUsername() {
140             return username;
141         }
142
143         public void setUsername(String username) {
144             this.username = username;
145         }
146
147         public String getName() {
148             return name;
149         }
150
151         public void setName(String name) {
152             this.name = name;
153         }
154     }
155     @SuppressWarnings("unused")
156     private static class GitlabGroupInfo {
157         private String name;
158
159         public String getName() {
160             return name;
161         }
162
163         public void setName(String name) {
164             this.name = name;
165         }
166     }
167     @Override
168     protected boolean verifyState(String state) {
169         if(this.randomIds.contains(state)) {
170             this.randomIds.remove(state);
171             return true;
172         }
173         return false;
174     }
175 }