Convert Sparky to Spring-Boot
[aai/sparky-be.git] / sparkybe-onap-service / src / main / java / org / onap / aai / sparky / security / portal / UserManager.java
1 /**
2  * ============LICENSE_START===================================================
3  * SPARKY (AAI UI service)
4  * ============================================================================
5  * Copyright © 2017 AT&T Intellectual Property.
6  * Copyright © 2017 Amdocs
7  * All rights reserved.
8  * ============================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=====================================================
21  *
22  * ECOMP and OpenECOMP are trademarks
23  * and service marks of AT&T Intellectual Property.
24  */
25 package org.onap.aai.sparky.security.portal;
26
27 import java.io.File;
28 import java.io.IOException;
29 import java.lang.reflect.Type;
30 import java.nio.file.Files;
31 import java.util.ArrayList;
32 import java.util.List;
33 import java.util.Optional;
34 import java.util.concurrent.locks.Lock;
35 import java.util.concurrent.locks.ReadWriteLock;
36 import java.util.concurrent.locks.ReentrantReadWriteLock;
37 import java.util.stream.Collectors;
38
39 import org.onap.aai.sparky.security.portal.config.RolesConfig;
40 import org.openecomp.portalsdk.core.restful.domain.EcompRole;
41 import org.openecomp.portalsdk.core.restful.domain.EcompUser;
42
43 import com.google.gson.Gson;
44 import com.google.gson.GsonBuilder;
45 import com.google.gson.reflect.TypeToken;
46
47 /**
48  * Basic file based user storage.
49  */
50 public class UserManager {
51
52   private File usersFile;
53
54   private static final ReadWriteLock LOCK = new ReentrantReadWriteLock(true);
55   private static final Lock READ_LOCK = LOCK.readLock();
56   private static final Lock WRITE_LOCK = LOCK.writeLock();
57
58   private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
59
60   /**
61    *
62    * @param usersFile a file to store the users
63    */
64   public UserManager(File usersFile) {
65     this.usersFile = usersFile;
66   }
67
68   /**
69    * Returns all users stored.
70    *
71    * @return a list of users.
72    */
73   public List<EcompUser> getUsers() {
74     Type collectionType = new TypeToken<List<EcompUser>>() {
75     }.getType();
76
77     Optional<String> users = read(usersFile);
78     if (users.isPresent()) {
79       return GSON.fromJson(users.get(), collectionType);
80     }
81
82     return new ArrayList<>();
83   }
84
85   /**
86    * Returns a stored user.
87    *
88    * @param loginId the identifier of the user
89    * @return an optional user.
90    */
91   public Optional<EcompUser> getUser(String loginId) {
92     if (!getUsers().isEmpty()) {
93       return getUsers().stream().filter(u -> loginId.equals(u.getLoginId())).findFirst();
94     }
95     return Optional.empty();
96   }
97
98   /**
99    * Stores a user if not already stored.
100    *
101    * @param user the user to be stored
102    * @throws IOException
103    */
104   public void pushUser(EcompUser user) throws IOException {
105     WRITE_LOCK.lock();
106     try {
107       if (!getUser(user.getLoginId()).isPresent()) {
108         addUser(getUsers(), user);
109       }
110     } finally {
111       WRITE_LOCK.unlock();
112     }
113   }
114
115   /**
116    * Replaces an existing user.
117    *
118    * @param loginId the id of the user
119    * @param user the new user details
120    * @throws IOException
121    */
122   public void editUser(String loginId, EcompUser user) throws IOException {
123     WRITE_LOCK.lock();
124     try {
125       if (getUser(loginId).isPresent()) {
126         List<EcompUser> users = getUsers().stream().filter(u -> !u.getLoginId().equals(loginId))
127             .collect(Collectors.toList());
128         addUser(users, user);
129       }
130     } finally {
131       WRITE_LOCK.unlock();
132     }
133   }
134
135   /**
136    * Gets the roles assigned to a user.
137    *
138    * @param loginId the id of the user
139    * @return the assigned roles
140    */
141   public List<EcompRole> getUserRoles(String loginId) {
142     List<EcompRole> roles = new ArrayList<>();
143     roles.addAll(getUser(loginId).orElseGet(EcompUser::new).getRoles());
144     return roles;
145   }
146
147   public static List<EcompRole> getRoles() {
148     return RolesConfig.getInstance().getRoles();
149   }
150
151   private void addUser(List<EcompUser> users, EcompUser user) throws IOException {
152     users.add(user);
153     write(users);
154   }
155
156   private void write(List<EcompUser> users) throws IOException {
157     Files.write(usersFile.toPath(), GSON.toJson(users).getBytes());
158   }
159
160   private Optional<String> read(File file) {
161     READ_LOCK.lock();
162     try {
163       return Optional.of(new String(Files.readAllBytes(file.toPath())));
164     } catch (IOException e) { // NOSONAR
165       return Optional.empty();
166     } finally {
167       READ_LOCK.unlock();
168     }
169   }
170 }