Publish swagger files for SDC APIs
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / servlets / UserAdminServlet.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
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.openecomp.sdc.be.servlets;
22
23 import com.jcabi.aspects.Loggable;
24 import io.swagger.v3.oas.annotations.Operation;
25 import io.swagger.v3.oas.annotations.Parameter;
26 import io.swagger.v3.oas.annotations.media.ArraySchema;
27 import io.swagger.v3.oas.annotations.media.Content;
28 import io.swagger.v3.oas.annotations.media.Schema;
29 import io.swagger.v3.oas.annotations.responses.ApiResponse;
30 import io.swagger.v3.oas.annotations.servers.Server;
31 import io.swagger.v3.oas.annotations.servers.Servers;
32 import io.swagger.v3.oas.annotations.tags.Tag;
33 import io.swagger.v3.oas.annotations.tags.Tags;
34 import org.eclipse.jetty.http.HttpStatus;
35 import org.openecomp.sdc.be.components.impl.aaf.AafPermission;
36 import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed;
37 import org.openecomp.sdc.be.impl.ComponentsUtils;
38 import org.openecomp.sdc.be.model.User;
39 import org.openecomp.sdc.be.user.Role;
40 import org.openecomp.sdc.be.user.UserBusinessLogic;
41 import org.openecomp.sdc.be.user.UserBusinessLogicExt;
42 import org.openecomp.sdc.common.api.Constants;
43 import org.openecomp.sdc.common.log.wrappers.Logger;
44 import org.springframework.stereotype.Controller;
45
46 import javax.servlet.http.HttpServletRequest;
47 import javax.ws.rs.Consumes;
48 import javax.ws.rs.DELETE;
49 import javax.ws.rs.GET;
50 import javax.ws.rs.HeaderParam;
51 import javax.ws.rs.POST;
52 import javax.ws.rs.Path;
53 import javax.ws.rs.PathParam;
54 import javax.ws.rs.Produces;
55 import javax.ws.rs.QueryParam;
56 import javax.ws.rs.core.Context;
57 import javax.ws.rs.core.MediaType;
58 import javax.ws.rs.core.Response;
59 import java.io.UnsupportedEncodingException;
60 import java.net.URLDecoder;
61 import java.util.ArrayList;
62 import java.util.List;
63 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
64 @Path("/v1/user")
65 @Tags({@Tag(name = "SDCE-2 APIs")})
66 @Servers({@Server(url = "/sdc2/rest")})
67 @Controller
68 public class UserAdminServlet extends BeGenericServlet {
69
70     private static final String UTF_8 = "UTF-8";
71         private static final String ROLE_DELIMITER = ",";
72     private static final Logger log = Logger.getLogger(UserAdminServlet.class);
73     private final UserBusinessLogic userBusinessLogic;
74     private final UserBusinessLogicExt userBusinessLogicExt;
75
76     static class UserRole {
77         Role role;
78
79         public Role getRole() {
80             return role;
81         }
82
83         public void setRole(Role role) {
84             this.role = role;
85         }
86
87     }
88
89     UserAdminServlet(UserBusinessLogic userBusinessLogic,
90                      ComponentsUtils componentsUtils, UserBusinessLogicExt userBusinessLogicExt) {
91         super(userBusinessLogic, componentsUtils);
92         this.userBusinessLogic = userBusinessLogic;
93         this.userBusinessLogicExt = userBusinessLogicExt;
94     }
95
96     /////////////////////////////////////////////////////////////////////////////////////////////////////
97     // retrieve all user details
98     @GET
99     @Path("/{userId}")
100     @Consumes(MediaType.APPLICATION_JSON)
101     @Produces(MediaType.APPLICATION_JSON)
102
103     @Operation(description = "retrieve user details", method = "GET",
104             summary = "Returns user details according to userId",responses = {
105             @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))),
106             @ApiResponse(responseCode = "200", description = "Returns user Ok"),
107             @ApiResponse(responseCode = "404", description = "User not found"),
108             @ApiResponse(responseCode = "405", description = "Method Not Allowed"),
109             @ApiResponse(responseCode = "500", description = "Internal Server Error")
110     })
111     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
112     public User get(
113         @Parameter(description = "userId of user to get", required = true) @PathParam("userId") final String userId,
114         @Context final HttpServletRequest request) {
115         return userBusinessLogic.getUser(userId, false);
116     }
117
118     @GET
119     @Path("/{userId}/role")
120     @Consumes(MediaType.APPLICATION_JSON)
121     @Produces(MediaType.APPLICATION_JSON)
122     @Operation(description = "retrieve user role", summary = "Returns user role according to userId", responses = {
123             @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),
124             @ApiResponse(responseCode = "200", description = "Returns user role Ok"),
125             @ApiResponse(responseCode = "404", description = "User not found"),
126             @ApiResponse(responseCode = "405", description = "Method Not Allowed"),
127             @ApiResponse(responseCode = "500", description = "Internal Server Error")})
128     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
129     public String getRole(
130         @Parameter(description = "userId of user to get", required = true) @PathParam("userId") final String userId,
131         @Context final HttpServletRequest request) {
132         User user = userBusinessLogic.getUser(userId, false);
133         return "{ \"role\" : \"" + user.getRole() + "\" }";
134     }
135
136     /////////////////////////////////////////////////////////////////////////////////////////////////////
137     // update user role
138     @POST
139     @Path("/{userId}/role")
140     @Consumes(MediaType.APPLICATION_JSON)
141     @Produces(MediaType.APPLICATION_JSON)
142     @Operation(description = "update user role", summary = "Update user role", responses = {
143             @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))),
144             @ApiResponse(responseCode = "200", description = "Update user OK"),
145             @ApiResponse(responseCode = "400", description = "Invalid Content."),
146             @ApiResponse(responseCode = "403", description = "Missing information/Restricted operation"),
147             @ApiResponse(responseCode = "404", description = "User not found"),
148             @ApiResponse(responseCode = "405", description = "Method Not Allowed"),
149             @ApiResponse(responseCode = "409", description = "User already exists"),
150             @ApiResponse(responseCode = "500", description = "Internal Server Error")})
151     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
152     public User updateUserRole(
153             @Parameter(description = "userId of user to get",
154             required = true) @PathParam("userId") final String userIdUpdateUser,
155             @Context final HttpServletRequest request,
156             @Parameter(description = "json describe the update role", required = true) UserRole newRole,
157             @HeaderParam(value = Constants.USER_ID_HEADER) String modifierUserId) {
158
159         return userBusinessLogic.updateUserRole(modifierUserId, userIdUpdateUser, newRole.getRole().name());
160     }
161
162     @POST
163     @Consumes(MediaType.APPLICATION_JSON)
164     @Produces(MediaType.APPLICATION_JSON)
165     @Operation(description = "add user", method = "POST", summary = "Provision new user", responses = {
166             @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))),
167             @ApiResponse(responseCode = "201", description = "New user created"),
168             @ApiResponse(responseCode = "400", description = "Invalid Content."),
169             @ApiResponse(responseCode = "403", description = "Missing information"),
170             @ApiResponse(responseCode = "405", description = "Method Not Allowed"),
171             @ApiResponse(responseCode = "409", description = "User already exists"),
172             @ApiResponse(responseCode = "500", description = "Internal Server Error")})
173     public Response createUser(@Context final HttpServletRequest request,
174             @Parameter(description = "json describe the user", required = true) User newUser,
175             @HeaderParam(value = Constants.USER_ID_HEADER) String modifierAttId) {
176
177         log.debug("modifier id is {}", modifierAttId);
178         User user = userBusinessLogic.createUser(modifierAttId, newUser);
179         return Response.status(HttpStatus.CREATED_201)
180                 .entity(user)
181                 .build();
182     }
183
184     @GET
185     @Path("/authorize")
186     @Consumes(MediaType.APPLICATION_JSON)
187     @Produces(MediaType.APPLICATION_JSON)
188
189     @Operation(description = "authorize", summary = "authorize user", responses = {
190             @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))),
191             @ApiResponse(responseCode = "200", description = "Returns user Ok"),
192             @ApiResponse(responseCode = "403", description = "Restricted Access"),
193             @ApiResponse(responseCode = "500", description = "Internal Server Error")})
194     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
195     public User authorize(@HeaderParam(value = Constants.USER_ID_HEADER) String userId,
196                           @HeaderParam("HTTP_CSP_FIRSTNAME") String firstName,
197                           @HeaderParam("HTTP_CSP_LASTNAME") String lastName,
198             @HeaderParam("HTTP_CSP_EMAIL") String email) throws UnsupportedEncodingException {
199
200         userId = userId != null ? URLDecoder.decode(userId, UTF_8) : null;
201         firstName = firstName != null ? URLDecoder.decode(firstName, UTF_8) : null;
202         lastName = lastName != null ? URLDecoder.decode(lastName, UTF_8) : null;
203         email = email != null ? URLDecoder.decode(email, UTF_8) : null;
204
205         User authUser = new User();
206         authUser.setUserId(userId);
207         authUser.setFirstName(firstName);
208         authUser.setLastName(lastName);
209         authUser.setEmail(email);
210         return userBusinessLogic.authorize(authUser);
211     }
212
213     @GET
214     @Path("/admins")
215     @Consumes(MediaType.APPLICATION_JSON)
216     @Produces(MediaType.APPLICATION_JSON)
217     @Operation(description = "retrieve all administrators", method = "GET", summary = "Returns all administrators",
218             responses = {@ApiResponse(
219                     content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))),
220                     @ApiResponse(responseCode = "200", description = "Returns user Ok"),
221                     @ApiResponse(responseCode = "405", description = "Method Not Allowed"),
222                     @ApiResponse(responseCode = "500", description = "Internal Server Error")})
223     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
224     public List<User> getAdminsUser(@Context final HttpServletRequest request) {
225         return userBusinessLogic.getAllAdminUsers();
226     }
227
228     @GET
229     @Path("/users")
230     @Consumes(MediaType.APPLICATION_JSON)
231     @Produces(MediaType.APPLICATION_JSON)
232     @Operation(description = "Retrieve the list of all active ASDC users or only group of users having specific roles.",
233             method = "GET",
234             summary = "Returns list of users with the specified roles, or all of users in the case of empty 'roles' header",
235             responses = {@ApiResponse(
236                     content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))),
237                     @ApiResponse(responseCode = "200", description = "Returns users Ok"),
238                     @ApiResponse(responseCode = "204", description = "No provisioned ASDC users of requested role"),
239                     @ApiResponse(responseCode = "403", description = "Restricted Access"),
240                     @ApiResponse(responseCode = "400", description = "Missing content"),
241                     @ApiResponse(responseCode = "500", description = "Internal Server Error")})
242     public List<User> getUsersList(@Context final HttpServletRequest request, @Parameter(
243             description = "Any active user's USER_ID ") @HeaderParam(Constants.USER_ID_HEADER) final String userId,
244             @Parameter(
245                     description = "TESTER,DESIGNER,PRODUCT_STRATEGIST,OPS,PRODUCT_MANAGER,GOVERNOR, ADMIN OR all users by not typing anything") @QueryParam("roles") final String roles) {
246
247         String url = request.getMethod() + " " + request.getRequestURI();
248         log.debug("Start handle request of {} modifier id is {}", url, userId);
249
250         List<String> rolesList = new ArrayList<>();
251         if (roles != null && !roles.trim().isEmpty()) {
252             String[] rolesArr = roles.split(ROLE_DELIMITER);
253             for (String role : rolesArr) {
254                 rolesList.add(role.trim());
255             }
256         }
257         return userBusinessLogic.getUsersList(userId, rolesList, roles);
258     }
259
260     @DELETE
261     @Path("/{userId}")
262     @Consumes(MediaType.APPLICATION_JSON)
263     @Produces(MediaType.APPLICATION_JSON)
264     @Operation(description = "delete user", summary = "Delete user", responses = {
265             @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))),
266             @ApiResponse(responseCode = "200", description = "Update deleted OK"),
267             @ApiResponse(responseCode = "400", description = "Invalid Content."),
268             @ApiResponse(responseCode = "403", description = "Missing information"),
269             @ApiResponse(responseCode = "404", description = "User not found"),
270             @ApiResponse(responseCode = "405", description = "Method Not Allowed"),
271             @ApiResponse(responseCode = "409", description = "Restricted operation"),
272             @ApiResponse(responseCode = "500", description = "Internal Server Error")})
273     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
274     public User deActivateUser(
275             @Parameter(description = "userId of user to get", required = true) @PathParam("userId") final String userId,
276             @Context final HttpServletRequest request,
277             @HeaderParam(value = Constants.USER_ID_HEADER) String modifierId) {
278         return userBusinessLogicExt.deActivateUser(modifierId, userId);
279     }
280 }