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