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