First version of NonRT RIC Controlpanel
[portal/nonrtric-controlpanel.git] / webapp-backend / src / main / java / org / oransc / portal / nonrtric / controlpanel / ControlpanelUserManager.java
1 /*-
2  * ========================LICENSE_START=================================
3  * O-RAN-SC
4  * %%
5  * Copyright (C) 2019 AT&T Intellectual Property
6  * Modifications Copyright (C) 2020 Nordix Foundation
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 package org.oransc.portal.nonrtric.controlpanel;
22
23 import com.fasterxml.jackson.core.type.TypeReference;
24 import com.fasterxml.jackson.databind.ObjectMapper;
25
26 import java.io.File;
27 import java.io.IOException;
28 import java.lang.invoke.MethodHandles;
29 import java.nio.file.Files;
30 import java.util.ArrayList;
31 import java.util.HashSet;
32 import java.util.List;
33 import java.util.Set;
34
35 import org.onap.portalsdk.core.onboarding.exception.PortalAPIException;
36 import org.onap.portalsdk.core.restful.domain.EcompRole;
37 import org.onap.portalsdk.core.restful.domain.EcompUser;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40
41 /**
42  * Provides simple user-management services.
43  *
44  * This first implementation serializes user details to a file.
45  */
46 public class ControlpanelUserManager {
47
48     private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
49
50     // This default value is only useful for development and testing.
51     public static final String USER_FILE_PATH = "controlpanel-users.json";
52
53     private final File userFile;
54     private final List<EcompUser> users;
55
56     /**
57      * Development/test-only constructor that uses default file path.
58      *
59      * @param clear
60      *        If true, start empty and remove any existing file.
61      *
62      * @throws IOException
63      *         On file error
64      */
65     public ControlpanelUserManager(boolean clear) throws IOException {
66         this(USER_FILE_PATH);
67         if (clear) {
68             logger.debug("ctor: removing file {}", userFile.getAbsolutePath());
69             File f = new File(ControlpanelUserManager.USER_FILE_PATH);
70             if (f.exists())
71                 Files.delete(f.toPath());
72             users.clear();
73         }
74     }
75
76     /**
77      * Constructur that accepts a file path
78      *
79      * @param userFilePath
80      *        File path
81      * @throws IOException
82      *         If file cannot be read
83      */
84     public ControlpanelUserManager(final String userFilePath) throws IOException {
85         logger.debug("ctor: userfile {}", userFilePath);
86         if (userFilePath == null)
87             throw new IllegalArgumentException("Missing or empty user file property");
88         userFile = new File(userFilePath);
89         logger.debug("ctor: managing users in file {}", userFile.getAbsolutePath());
90         if (userFile.exists()) {
91             final ObjectMapper mapper = new ObjectMapper();
92             users = mapper.readValue(userFile, new TypeReference<List<EcompUser>>() {});
93         } else {
94             users = new ArrayList<>();
95         }
96     }
97
98     /**
99      * Gets the current users.
100      *
101      * @return List of EcompUser objects, possibly empty
102      */
103     public List<EcompUser> getUsers() {
104         return this.users;
105     }
106
107     /**
108      * Gets the user with the specified login Id
109      *
110      * @param loginId
111      *        Desired login Id
112      * @return User object; null if Id is not known
113      */
114     public EcompUser getUser(String loginId) {
115         for (EcompUser u : this.users) {
116             if (u.getLoginId().equals(loginId)) {
117                 logger.debug("getUser: match on {}", loginId);
118                 return u;
119             }
120         }
121         logger.debug("getUser: no match on {}", loginId);
122         return null;
123     }
124
125     private void saveUsers() throws IOException {
126         final ObjectMapper mapper = new ObjectMapper();
127         mapper.writeValue(userFile, users);
128     }
129
130     /*
131      * Allow at most one thread to create a user at one time.
132      */
133     public synchronized void createUser(EcompUser user) throws PortalAPIException {
134         if (logger.isDebugEnabled()) {
135             logger.debug("createUser: loginId is {}", user.getLoginId());
136         }
137         if (users.contains(user))
138             throw new PortalAPIException("User exists: " + user.getLoginId());
139         users.add(user);
140         try {
141             saveUsers();
142         } catch (Exception ex) {
143             throw new PortalAPIException("Save failed", ex);
144         }
145     }
146
147     /*
148      * Allow at most one thread to modify a user at one time. We still have
149      * last-edit-wins of course.
150      */
151     public synchronized void updateUser(String loginId, EcompUser user) throws PortalAPIException {
152         logger.debug("editUser: loginId is {}", loginId);
153         int index = users.indexOf(user);
154         if (index < 0)
155             throw new PortalAPIException("User does not exist: " + user.getLoginId());
156         users.remove(index);
157         users.add(user);
158         try {
159             saveUsers();
160         } catch (Exception ex) {
161             throw new PortalAPIException("Save failed", ex);
162         }
163     }
164
165     // Test infrastructure
166     public static void main(String[] args) throws Exception {
167         ControlpanelUserManager dum = new ControlpanelUserManager(false);
168         EcompUser user = new EcompUser();
169         user.setActive(true);
170         user.setLoginId("demo");
171         user.setFirstName("First");
172         user.setLastName("Last");
173         EcompRole role = new EcompRole();
174         role.setId(1L);
175         role.setName(ControlpanelConstants.ROLE_NAME_ADMIN);
176         Set<EcompRole> roles = new HashSet<>();
177         roles.add(role);
178         user.setRoles(roles);
179         dum.createUser(user);
180         logger.debug("Created user {}", user);
181     }
182
183 }