315f911a4cfdc789d70d73ef31c19000c1d061a3
[portal.git] / portal-BE / src / main / java / org / onap / portal / domain / db / fn / FnUser.java
1 /*
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
6  * ===================================================================
7  * Modifications Copyright (c) 2019 Samsung
8  * ===================================================================
9  *
10  * Unless otherwise specified, all software contained herein is licensed
11  * under the Apache License, Version 2.0 (the "License");
12  * you may not use this software except in compliance with the License.
13  * You may obtain a copy of the License at
14  *
15  *             http://www.apache.org/licenses/LICENSE-2.0
16  *
17  * Unless required by applicable law or agreed to in writing, software
18  * distributed under the License is distributed on an "AS IS" BASIS,
19  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20  * See the License for the specific language governing permissions and
21  * limitations under the License.
22  *
23  * Unless otherwise specified, all documentation contained herein is licensed
24  * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
25  * you may not use this documentation except in compliance with the License.
26  * You may obtain a copy of the License at
27  *
28  *             https://creativecommons.org/licenses/by/4.0/
29  *
30  * Unless required by applicable law or agreed to in writing, documentation
31  * distributed under the License is distributed on an "AS IS" BASIS,
32  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
33  * See the License for the specific language governing permissions and
34  * limitations under the License.
35  *
36  * ============LICENSE_END============================================
37  *
38  *
39  */
40
41 package org.onap.portal.domain.db.fn;
42
43 import java.io.Serializable;
44 import java.time.LocalDateTime;
45 import java.util.Collection;
46 import java.util.HashSet;
47 import java.util.Iterator;
48 import java.util.Set;
49 import java.util.SortedSet;
50 import java.util.TreeSet;
51 import java.util.stream.Collectors;
52 import javax.persistence.CascadeType;
53 import javax.persistence.Column;
54 import javax.persistence.Entity;
55 import javax.persistence.FetchType;
56 import javax.persistence.GeneratedValue;
57 import javax.persistence.GenerationType;
58 import javax.persistence.Id;
59 import javax.persistence.Index;
60 import javax.persistence.JoinColumn;
61 import javax.persistence.ManyToMany;
62 import javax.persistence.ManyToOne;
63 import javax.persistence.NamedQueries;
64 import javax.persistence.NamedQuery;
65 import javax.persistence.OneToMany;
66 import javax.persistence.SequenceGenerator;
67 import javax.persistence.Table;
68 import javax.persistence.UniqueConstraint;
69 import javax.validation.constraints.Digits;
70 import javax.validation.constraints.Email;
71 import javax.validation.constraints.NotNull;
72 import javax.validation.constraints.PastOrPresent;
73 import javax.validation.constraints.Size;
74 import lombok.AllArgsConstructor;
75 import lombok.Builder;
76 import lombok.Getter;
77 import lombok.NoArgsConstructor;
78 import lombok.Setter;
79 import org.hibernate.annotations.DynamicUpdate;
80 import org.hibernate.validator.constraints.SafeHtml;
81 import org.onap.portal.domain.db.cr.CrReportFileHistory;
82 import org.onap.portal.domain.db.ep.EpPersUserWidgetPlacement;
83 import org.onap.portal.domain.db.ep.EpPersUserWidgetSel;
84 import org.onap.portal.domain.db.ep.EpUserNotification;
85 import org.onap.portal.domain.db.ep.EpUserRolesRequest;
86 import org.onap.portal.domain.db.ep.EpWidgetCatalogParameter;
87 import org.onap.portal.domain.dto.DomainVo;
88 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
89 import org.springframework.security.core.GrantedAuthority;
90 import org.springframework.security.core.authority.SimpleGrantedAuthority;
91 import org.springframework.security.core.userdetails.UserDetails;
92
93 /*
94 CREATE TABLE `fn_user` (
95         `user_id` int(11) NOT NULL AUTO_INCREMENT,
96         `org_id` int(11) DEFAULT NULL,
97         `manager_id` int(11) DEFAULT NULL,
98         `first_name` varchar(50) DEFAULT NULL,
99         `middle_name` varchar(50) DEFAULT NULL,
100         `last_name` varchar(50) DEFAULT NULL,
101         `phone` varchar(25) DEFAULT NULL,
102         `fax` varchar(25) DEFAULT NULL,
103         `cellular` varchar(25) DEFAULT NULL,
104         `email` varchar(50) DEFAULT NULL,
105         `address_id` decimal(11,0) DEFAULT NULL,
106         `alert_method_cd` varchar(10) DEFAULT NULL,
107         `hrid` varchar(20) DEFAULT NULL,
108         `org_user_id` varchar(20) DEFAULT NULL,
109         `org_code` varchar(30) DEFAULT NULL,
110         `login_id` varchar(25) DEFAULT NULL,
111         `login_pwd` varchar(100) DEFAULT NULL,
112         `last_login_date` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
113         `active_yn` varchar(1) NOT NULL DEFAULT 'y',
114         `created_id` int(11) DEFAULT NULL,
115         `created_date` timestamp NOT NULL DEFAULT current_timestamp(),
116         `modified_id` int(11) DEFAULT NULL,
117         `modified_date` timestamp NOT NULL DEFAULT current_timestamp(),
118         `is_internal_yn` char(1) NOT NULL DEFAULT 'n',
119         `address_line_1` varchar(100) DEFAULT NULL,
120         `address_line_2` varchar(100) DEFAULT NULL,
121         `city` varchar(50) DEFAULT NULL,
122         `state_cd` varchar(3) DEFAULT NULL,
123         `zip_code` varchar(11) DEFAULT NULL,
124         `country_cd` varchar(3) DEFAULT NULL,
125         `location_clli` varchar(8) DEFAULT NULL,
126         `org_manager_userid` varchar(20) DEFAULT NULL,
127         `company` varchar(100) DEFAULT NULL,
128         `department_name` varchar(100) DEFAULT NULL,
129         `job_title` varchar(100) DEFAULT NULL,
130         `timezone` int(11) DEFAULT NULL,
131         `department` varchar(25) DEFAULT NULL,
132         `business_unit` varchar(25) DEFAULT NULL,
133         `business_unit_name` varchar(100) DEFAULT NULL,
134         `cost_center` varchar(25) DEFAULT NULL,
135         `fin_loc_code` varchar(10) DEFAULT NULL,
136         `silo_status` varchar(10) DEFAULT NULL,
137         `language_id` int(2) NOT NULL DEFAULT 1,
138         PRIMARY KEY (`user_id`),
139         UNIQUE KEY `fn_user_hrid` (`hrid`) USING BTREE,
140         UNIQUE KEY `fn_user_login_id` (`login_id`) USING BTREE,
141         KEY `fn_user_address_id` (`address_id`) USING BTREE,
142         KEY `fn_user_alert_method_cd` (`alert_method_cd`) USING BTREE,
143         KEY `fn_user_org_id` (`org_id`) USING BTREE,
144         KEY `fk_fn_user_ref_197_fn_user` (`manager_id`),
145         KEY `fk_fn_user_ref_198_fn_user` (`created_id`),
146         KEY `fk_fn_user_ref_199_fn_user` (`modified_id`),
147         KEY `fk_timezone` (`timezone`),
148         CONSTRAINT `fk_fn_user_ref_110_fn_org` FOREIGN KEY (`org_id`) REFERENCES `fn_org` (`org_id`),
149         CONSTRAINT `fk_fn_user_ref_123_fn_lu_al` FOREIGN KEY (`alert_method_cd`) REFERENCES `fn_lu_alert_method` (`alert_method_cd`),
150         CONSTRAINT `fk_fn_user_ref_197_fn_user` FOREIGN KEY (`manager_id`) REFERENCES `fn_user` (`user_id`),
151         CONSTRAINT `fk_fn_user_ref_198_fn_user` FOREIGN KEY (`created_id`) REFERENCES `fn_user` (`user_id`),
152         CONSTRAINT `fk_fn_user_ref_199_fn_user` FOREIGN KEY (`modified_id`) REFERENCES `fn_user` (`user_id`),
153         CONSTRAINT `fk_timezone` FOREIGN KEY (`timezone`) REFERENCES `fn_lu_timezone` (`timezone_id`)
154         )
155 */
156
157 @NamedQueries({
158         @NamedQuery(
159                 name = "FnUser.getUserWithOrgUserId",
160                 query = "FROM FnUser WHERE orgUserId = :orgId"),
161         @NamedQuery(
162                 name = "FnUser.getActiveUsers",
163                 query = "FROM FnUser WHERE activeYn = 'Y'"),
164         @NamedQuery(
165                 name = "FnUser.getUsersByOrgIds",
166                 query = "FROM FnUser WHERE orgUserId IN :orgIds"
167         )
168 })
169 @Table(name = "fn_user", indexes = {
170         @Index(name = "fn_user_address_id", columnList = "address_id"),
171         @Index(name = "fn_user_alert_method_cd", columnList = "alert_method_cd"),
172         @Index(name = "fn_user_org_id", columnList = "org_id"),
173         @Index(name = "fk_fn_user_ref_197_fn_user", columnList = "manager_id"),
174         @Index(name = "fk_fn_user_ref_198_fn_user", columnList = "created_id"),
175         @Index(name = "fk_fn_user_ref_199_fn_user", columnList = "modified_id"),
176         @Index(name = "fk_timezone", columnList = "timezone")
177 },
178         uniqueConstraints = {
179                 @UniqueConstraint(name = "fn_user_hrid", columnNames = "hrid"),
180                 @UniqueConstraint(name = "fn_user_login_id", columnNames = "login_id")
181
182         })
183
184 @Getter
185 @Setter
186 @Entity
187 @Builder
188 @NoArgsConstructor
189 @AllArgsConstructor
190 @DynamicUpdate
191 public class FnUser extends DomainVo implements UserDetails, Serializable {
192
193        private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FnUser.class);
194
195        @Id
196        @GeneratedValue(strategy = GenerationType.IDENTITY)
197        @Column(name = "user_id", nullable = false)
198        private Long userId;
199        @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
200        @JoinColumn(name = "org_id")
201        private FnOrg orgId;
202        @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
203        @JoinColumn(name = "manager_id")
204        private FnUser managerId;
205        @Column(name = "first_name", length = 50)
206        @Size(max = 50)
207        @SafeHtml
208        private String firstName;
209        @Column(name = "middle_name", length = 50)
210        @Size(max = 50)
211        @SafeHtml
212        private String middleName;
213        @Column(name = "last_name", length = 50)
214        @Size(max = 50)
215        @SafeHtml
216        private String lastName;
217        @Column(name = "phone", length = 25)
218        @Size(max = 25)
219        @SafeHtml
220        private String phone;
221        @Column(name = "fax", length = 25)
222        @Size(max = 25)
223        @SafeHtml
224        private String fax;
225        @Column(name = "cellular", length = 25)
226        @Size(max = 25)
227        @SafeHtml
228        private String cellular;
229        @Column(name = "email", length = 50)
230        @Size(max = 50)
231        @Email
232        @SafeHtml
233        private String email;
234        @Column(name = "address_id")
235        @Digits(integer = 11, fraction = 0)
236        private Long addressId;
237        @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
238        @JoinColumn(name = "alert_method_cd")
239        private FnLuAlertMethod alertMethodCd;
240        @Column(name = "hrid", length = 20)
241        @Size(max = 20)
242        @SafeHtml
243        private String hrid;
244        @Column(name = "org_user_id", length = 20)
245        @Size(max = 20)
246        @SafeHtml
247        private String orgUserId;
248        @Column(name = "org_code", length = 30)
249        @Size(max = 30)
250        @SafeHtml
251        private String org_code;
252        @Column(name = "login_id", length = 25)
253        @Size(max = 25)
254        @SafeHtml
255        private String loginId;
256        @Column(name = "login_pwd", length = 100)
257        @Size(max = 100)
258        @SafeHtml
259        private String loginPwd;
260        @Column(name = "last_login_date", nullable = false, columnDefinition = "datetime DEFAULT current_timestamp() ON UPDATE current_timestamp()")
261        @PastOrPresent
262        protected LocalDateTime lastLoginDate;
263        @Column(name = "active_yn", nullable = false)
264        private Boolean activeYn;
265        @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
266        @JoinColumn(name = "created_id")
267        private FnUser createdId;
268        @Column(name = "created_date", columnDefinition = "datetime DEFAULT current_timestamp()", nullable = false)
269        @PastOrPresent
270        protected LocalDateTime createdDate;
271        @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
272        @JoinColumn(name = "modified_id")
273        private FnUser modifiedId;
274        @Column(name = "modified_date", nullable = false, columnDefinition = "datetime default now()")
275        @PastOrPresent
276        protected LocalDateTime modifiedDate;
277        @Column(name = "is_internal_yn", nullable = false, columnDefinition = "bit DEFAULT 0")
278        private Boolean isInternalYn;
279        @Column(name = "address_line_1", length = 100)
280        @Size(max = 100)
281        @SafeHtml
282        private String addressLine1;
283        @Column(name = "address_line_2", length = 100)
284        @Size(max = 100)
285        @SafeHtml
286        private String addressLine2;
287        @Column(name = "city", length = 50)
288        @Size(max = 50)
289        @SafeHtml
290        private String city;
291        @Column(name = "state_cd", length = 3)
292        @Size(max = 3)
293        @SafeHtml
294        private String stateCd;
295        @Column(name = "zip_code", length = 11)
296        @Size(max = 11)
297        @SafeHtml
298        private String zipCode;
299        @Column(name = "country_cd", length = 3)
300        @Size(max = 3)
301        @SafeHtml
302        private String countryCd;
303        @Column(name = "location_clli", length = 8)
304        @Size(max = 8)
305        @SafeHtml
306        private String locationClli;
307        @Column(name = "org_manager_userid", length = 20)
308        @Size(max = 20)
309        @SafeHtml
310        private String orgManagerUserId;
311        @Column(name = "company", length = 100)
312        @Size(max = 100)
313        @SafeHtml
314        private String company;
315        @Column(name = "department_name", length = 200)
316        @Size(max = 200)
317        @SafeHtml
318        private String departmentName;
319        @Column(name = "job_title", length = 100)
320        @Size(max = 100)
321        @SafeHtml
322        private String jobTitle;
323        @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
324        @JoinColumn(name = "timezone")
325        private FnLuTimezone timezone;
326        @Column(name = "department", length = 25)
327        @Size(max = 25)
328        @SafeHtml
329        private String department;
330        @Column(name = "business_unit", length = 25)
331        @Size(max = 25)
332        @SafeHtml
333        private String businessUnit;
334        @Column(name = "business_unit_name", length = 100)
335        @Size(max = 100)
336        @SafeHtml
337        private String businessUnitName;
338        @Column(name = "cost_center", length = 25)
339        @Size(max = 25)
340        @SafeHtml
341        private String cost_center;
342        @Column(name = "fin_loc_code", length = 10)
343        @Size(max = 10)
344        @SafeHtml
345        private String finLocCode;
346        @Column(name = "silo_status", length = 10)
347        @Size(max = 10)
348        @SafeHtml
349        private String siloStatus;
350        @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
351        @JoinColumn(name = "language_id", nullable = false, columnDefinition = "bigint DEFAULT 1")
352        @NotNull(message = "languageId must not be null")
353        private FnLanguage languageId;
354        @Column(name = "is_guest", nullable = false, columnDefinition = "bit DEFAULT 0")
355        @NotNull(message = "guest must not be null")
356        private Boolean guest;
357        @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "fnUserList")
358        private Set<CrReportFileHistory> crReportFileHistorie;
359        @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
360        private Set<FnRole> fnRoles;
361        @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
362        private Set<FnMenuFunctional> fnRoleList;
363        @OneToMany(
364                targetEntity = FnAuditLog.class,
365                mappedBy = "userId",
366                cascade = CascadeType.ALL,
367                fetch = FetchType.LAZY
368        )
369        private Set<FnAuditLog> fnAuditLogs;
370        @OneToMany(
371                targetEntity = FnUser.class,
372                mappedBy = "createdId",
373                cascade = CascadeType.ALL,
374                fetch = FetchType.LAZY
375        )
376        private Set<FnUser> fnUsersCreatedId;
377        @OneToMany(
378                targetEntity = FnUser.class,
379                mappedBy = "managerId",
380                cascade = CascadeType.ALL,
381                fetch = FetchType.LAZY
382        )
383        private Set<FnUser> fnUsersManagerId;
384        @OneToMany(
385                targetEntity = FnUser.class,
386                mappedBy = "modifiedId",
387                cascade = CascadeType.ALL,
388                fetch = FetchType.LAZY
389        )
390        private Set<FnUser> fnUsersModifiedId;
391        @OneToMany(
392                targetEntity = EpUserRolesRequest.class,
393                mappedBy = "userId",
394                cascade = CascadeType.ALL,
395                fetch = FetchType.LAZY
396        )
397        private Set<EpUserRolesRequest> epUserRolesRequests;
398        @OneToMany(
399                targetEntity = FnPersUserAppSel.class,
400                mappedBy = "userId",
401                cascade = CascadeType.ALL,
402                fetch = FetchType.LAZY
403        )
404        private Set<FnPersUserAppSel> persUserAppSels;
405        @OneToMany(
406                targetEntity = EpWidgetCatalogParameter.class,
407                mappedBy = "userId",
408                cascade = CascadeType.ALL,
409                fetch = FetchType.LAZY
410        )
411        private Set<EpWidgetCatalogParameter> epWidgetCatalogParameters;
412        @OneToMany(
413                targetEntity = EpPersUserWidgetPlacement.class,
414                mappedBy = "userId",
415                cascade = CascadeType.ALL,
416                fetch = FetchType.LAZY
417        )
418        private Set<EpPersUserWidgetPlacement> epPersUserWidgetPlacements;
419        @OneToMany(
420                targetEntity = EpPersUserWidgetSel.class,
421                mappedBy = "userId",
422                cascade = CascadeType.ALL,
423                fetch = FetchType.LAZY
424        )
425        private Set<EpPersUserWidgetSel> epPersUserWidgetSels;
426        @OneToMany(
427                targetEntity = FnUserRole.class,
428                mappedBy = "userId",
429                cascade = CascadeType.ALL,
430                fetch = FetchType.LAZY
431        )
432        private Set<FnUserRole> fnUserRoles;
433        @OneToMany(
434                targetEntity = EpUserNotification.class,
435                mappedBy = "userId",
436                cascade = CascadeType.ALL,
437                fetch = FetchType.LAZY
438        )
439        private Set<EpUserNotification> epUserNotifications;
440
441        @Override
442        public Collection<? extends GrantedAuthority> getAuthorities() {
443               return fnRoles
444                       .stream()
445                       .map(fnRole -> new SimpleGrantedAuthority("ROLE_" + fnRole.getRoleName()))
446                       .collect(Collectors.toList());
447        }
448
449        @Override
450        public String getPassword() {
451               return this.getLoginPwd();
452        }
453
454        @Override
455        public String getUsername() {
456               return this.getLoginId();
457        }
458
459        @Override
460        public boolean isAccountNonExpired() {
461               return true;
462        }
463
464        @Override
465        public boolean isAccountNonLocked() {
466               return true;
467        }
468
469        @Override
470        public boolean isCredentialsNonExpired() {
471               return true;
472        }
473
474        @Override
475        public boolean isEnabled() {
476               return true;
477        }
478
479        public String getFullName() {
480               return this.firstName + " " + this.lastName;
481        }
482
483        public SortedSet<FnRole> getAppEPRoles(FnApp app) {
484
485                      logger.debug(EELFLoggerDelegate.debugLogger, "In EPUser.getAppEPRoles() - app = {}", app.getAppName());
486
487                      SortedSet<FnRole> roles = new TreeSet<>();
488                      Set<FnUserRole> userAppRoles = getFnUserRoles();
489
490                      logger.debug(EELFLoggerDelegate.debugLogger, "In EPUser.getAppEPRoles() - userApps = {} ", userAppRoles.size());
491
492                      Iterator<FnUserRole> userAppRolesIterator = userAppRoles.iterator();
493
494               FnUserRole userAppRole;
495                      // getting default app
496                      while (userAppRolesIterator.hasNext()) {
497                             FnUserRole tempUserApp = userAppRolesIterator.next();
498                             if (tempUserApp.getAppId().getId().equals(app.getId())) {
499
500                                    logger.debug(EELFLoggerDelegate.debugLogger,
501                                            "In EPUser.getAppEPRoles() - for user {}, found application {}", this.getFullName(),
502                                            app.getAppName());
503
504                                    userAppRole = tempUserApp;
505
506                                    FnRole role = userAppRole.getRoleId();
507                                    if (role.getActiveYn()) {
508                                           logger.debug(EELFLoggerDelegate.debugLogger,
509                                                   "In EPUser.getAppEPRoles() - Role {} is active - adding for user {} and app {}",
510                                                   role.getRoleName(), this.getFullName(), app.getAppName());
511                                           roles.add(role);
512                                    } else {
513                                           logger.debug(EELFLoggerDelegate.debugLogger,
514                                                   "In EPUser.getAppEPRoles() - Role {} is NOT active - NOT adding for user {} and app {}",
515                                                   role.getRoleName(), this.getFullName(), app.getAppName());
516                                    }
517                             }
518                      }
519                      logger.debug(EELFLoggerDelegate.debugLogger, "In EPUser.getAppEPRoles() - roles = {}", roles.size());
520
521                      return roles;
522               }
523 }