2 * Copyright (C) 2016 Roland Haeder
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU Affero General Public License as
6 * published by the Free Software Foundation, either version 3 of the
7 * License, or (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU Affero General Public License for more details.
14 * You should have received a copy of the GNU Affero General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 package org.mxchange.addressbook.beans.user;
19 import java.text.MessageFormat;
20 import java.util.Collections;
21 import java.util.Iterator;
22 import java.util.List;
23 import java.util.Objects;
24 import javax.annotation.PostConstruct;
25 import javax.enterprise.context.RequestScoped;
26 import javax.enterprise.event.Event;
27 import javax.enterprise.event.Observes;
28 import javax.enterprise.inject.Any;
29 import javax.faces.view.facelets.FaceletException;
30 import javax.inject.Inject;
31 import javax.inject.Named;
32 import javax.naming.Context;
33 import javax.naming.InitialContext;
34 import javax.naming.NamingException;
35 import org.mxchange.addressbook.beans.contact.AddressbookContactWebSessionController;
36 import org.mxchange.addressbook.beans.helper.AddressbookAdminWebRequestController;
37 import org.mxchange.jcontacts.contact.Contact;
38 import org.mxchange.jusercore.container.login.UserLoginContainer;
39 import org.mxchange.jusercore.events.user.AdminAddedUserEvent;
40 import org.mxchange.jusercore.events.user.AdminUserAddedEvent;
41 import org.mxchange.jusercore.events.user.update.AdminUpdatedUserDataEvent;
42 import org.mxchange.jusercore.events.user.update.AdminUserDataUpdatedEvent;
43 import org.mxchange.jusercore.events.user.update.UpdatedUserPersonalDataEvent;
44 import org.mxchange.jusercore.exceptions.EmailAddressAlreadyRegisteredException;
45 import org.mxchange.jusercore.exceptions.UserNameAlreadyRegisteredException;
46 import org.mxchange.jusercore.exceptions.UserNotFoundException;
47 import org.mxchange.jusercore.exceptions.UserPasswordRepeatMismatchException;
48 import org.mxchange.jusercore.model.user.LoginUser;
49 import org.mxchange.jusercore.model.user.User;
50 import org.mxchange.jusercore.model.user.UserSessionBeanRemote;
51 import org.mxchange.jusercore.model.user.UserUtils;
52 import org.mxchange.jusercore.model.user.profilemodes.ProfileMode;
53 import org.mxchange.jusercore.model.user.status.UserAccountStatus;
56 * A user bean (controller)
58 * @author Roland Haeder<roland@mxchange.org>
60 @Named ("adminUserController")
62 public class AddressbookAdminUserWebRequestBean implements AddressbookAdminUserWebRequestController {
67 private static final long serialVersionUID = 542_145_347_916L;
70 * An event fired when the administrator has added a new user
74 private Event<AdminAddedUserEvent> addedUserEvent;
77 * Admin helper instance
80 private AddressbookAdminWebRequestController adminHelper;
83 * Regular contact controller
86 private AddressbookContactWebSessionController contactController;
89 * An event fired when the administrator has updated a new user
93 private Event<AdminUpdatedUserDataEvent> updatedUserDataEvent;
98 private final UserSessionBeanRemote userBean;
101 * Regular user controller
104 private AddressbookUserWebSessionController userController;
107 * A list of all user profiles
109 private List<User> userList;
114 private String userName;
117 * User password (unencrypted from web form)
119 private String userPassword;
122 * User password repeated (unencrypted from web form)
124 private String userPasswordRepeat;
127 * Default constructor
129 public AddressbookAdminUserWebRequestBean () {
132 // Get initial context
133 Context context = new InitialContext();
136 this.userBean = (UserSessionBeanRemote) context.lookup("java:global/addressbook-ejb/user!org.mxchange.jusercore.model.user.UserSessionBeanRemote"); //NOI18N
137 } catch (final NamingException e) {
139 throw new FaceletException(e);
144 public String addUser () {
145 // Create new user instance
146 User localUser = new LoginUser();
148 // Set user name, CONFIRMED and INVISIBLE
149 localUser.setUserName(this.getUserName());
150 localUser.setUserAccountStatus(UserAccountStatus.CONFIRMED);
151 localUser.setUserProfileMode(ProfileMode.INVISIBLE);
153 // Create contact instance
154 Contact contact = this.contactController.createContactInstance();
156 // Set contact in user
157 localUser.setUserContact(contact);
159 // Init variable for password
160 String password = null;
162 // Is the user name or email address used already?
163 // @TODO Add password length check
164 if (this.userController.isUserNameRegistered(localUser)) {
165 // User name is already used
166 throw new FaceletException(new UserNameAlreadyRegisteredException(localUser));
167 } else if (this.contactController.isEmailAddressRegistered(localUser.getUserContact())) {
168 // Email address is already used
169 throw new FaceletException(new EmailAddressAlreadyRegisteredException(localUser));
170 } else if ((this.getUserPassword() == null && (this.getUserPasswordRepeat() == null)) || ((this.getUserPassword().isEmpty()) && (this.getUserPasswordRepeat().isEmpty()))) {
171 // Empty password entered, then generate one
172 password = UserUtils.createRandomPassword(AddressbookUserWebSessionController.MINIMUM_PASSWORD_LENGTH);
173 } else if (!this.isSamePasswordEntered()) {
174 // Both passwords don't match
175 throw new FaceletException(new UserPasswordRepeatMismatchException(localUser));
177 // Both match, so get it from this bean
178 password = this.getUserPassword();
181 // The password should not be null and at least 5 characters long
182 assert (password != null) : "password is null"; //NOI18N
183 assert (password.length() >= AddressbookUserWebSessionController.MINIMUM_PASSWORD_LENGTH) : "Password is not long enough."; //NOI18N
185 // Encrypt password and set it
186 localUser.setUserEncryptedPassword(UserUtils.encryptPassword(password));
188 // Init updated user instance
189 User updatedUser = null;
192 // Now, that all is set, call EJB
193 updatedUser = this.userBean.addUser(localUser);
194 } catch (final UserNameAlreadyRegisteredException | EmailAddressAlreadyRegisteredException ex) {
196 throw new FaceletException(ex);
200 this.addedUserEvent.fire(new AdminUserAddedEvent(updatedUser));
202 // Add user to local list
203 this.userList.add(updatedUser);
205 // Clear contact instance
206 this.contactController.clear();
208 // Return to user list (for now)
209 return "admin_list_user"; //NOI18N
213 public void afterUserUpdatedPersonalData (@Observes final UpdatedUserPersonalDataEvent event) {
217 throw new NullPointerException("event is null"); //NOI18N
218 } else if (event.getUpdatedUser() == null) {
220 throw new NullPointerException("event.updatedUser is null"); //NOI18N
221 } else if (event.getUpdatedUser().getUserId() == null) {
223 throw new NullPointerException("event.updatedUser.userId is null"); //NOI18N
224 } else if (event.getUpdatedUser().getUserId() < 1) {
226 throw new IllegalArgumentException(MessageFormat.format("event.updatedUser.userId={0} is in valid", event.getUpdatedUser().getUserId())); //NOI18N
229 // All fine, so update list
230 this.updateList(event.getUpdatedUser());
234 public List<User> allUsers () {
236 return Collections.unmodifiableList(this.userList);
240 public String editUserData () {
242 User user = this.adminHelper.getUser();
244 // Null password means not setting it
245 String encryptedPassword = null;
247 // Check if user instance is in helper and valid
250 throw new NullPointerException("adminHelper.user is null"); //NOI18N
251 } else if (user.getUserId() == null) {
253 throw new NullPointerException("adminHelper.user.userId is null"); //NOI18N //NOI18N
254 } else if (user.getUserId() < 1) {
256 throw new IllegalStateException(MessageFormat.format("adminHelper.user.userId={0} is invalid", user.getUserId()));
257 } else if (this.getUserName() == null) {
258 // Not all required fields are set
259 throw new NullPointerException("this.userName is null"); //NOI18N
260 } else if (this.getUserName().isEmpty()) {
261 // Not all required fields are set
262 throw new IllegalArgumentException("this.userName is empty"); //NOI18N
263 } else if (((!this.getUserPassword().isEmpty()) || (!this.getUserPasswordRepeat().isEmpty())) && (!this.isSamePasswordEntered())) {
264 // Not same password entered
265 this.setUserPassword(null);
266 this.setUserPasswordRepeat(null);
269 throw new FaceletException("Not same password entered"); //NOI18N
270 } else if (this.isSamePasswordEntered()) {
271 // Same password entered, create container
272 if (UserUtils.ifPasswordMatches(new UserLoginContainer(user, this.getUserPassword()))) {
273 // Same password entered
274 throw new FaceletException("Same password as stored entered."); //NOI18N
278 encryptedPassword = UserUtils.encryptPassword(this.getUserPassword());
282 user.setUserName(this.getUserName());
284 // Is a password set?
285 if (encryptedPassword != null) {
287 user.setUserEncryptedPassword(encryptedPassword);
290 // Call EJB for updating user data
291 User updatedUser = this.userBean.updateUserData(user);
294 this.updateList(updatedUser);
297 this.updatedUserDataEvent.fire(new AdminUserDataUpdatedEvent(updatedUser));
299 // Return to user list (for now)
300 return "admin_list_user"; //NOI18N
304 public String getUserName () {
305 return this.userName;
309 public void setUserName (final String userName) {
310 this.userName = userName;
314 public String getUserPassword () {
315 return this.userPassword;
319 public void setUserPassword (final String userPassword) {
320 this.userPassword = userPassword;
324 public String getUserPasswordRepeat () {
325 return this.userPasswordRepeat;
329 public void setUserPasswordRepeat (final String userPasswordRepeat) {
330 this.userPasswordRepeat = userPasswordRepeat;
334 public boolean hasUsers () {
335 return (!this.allUsers().isEmpty());
339 * Post-initialization of this class
342 public void init () {
343 // Initialize user list
344 this.userList = this.userBean.allUsers();
348 public User lookupUserById (final Long userId) throws UserNotFoundException {
349 // Parameter must be valid
350 if (null == userId) {
352 throw new NullPointerException("userId is null"); //NOI18N
353 } else if (userId < 1) {
355 throw new IllegalArgumentException(MessageFormat.format("userId={0} is not valid.", userId)); //NOI18N
361 // Try to lookup it in visible user list
362 for (final Iterator<User> iterator = this.userList.iterator(); iterator.hasNext();) {
364 User next = iterator.next();
366 // Is the user id found?
367 if (Objects.equals(next.getUserId(), userId)) {
368 // Copy to other variable
376 // Not visible for the current user
377 throw new UserNotFoundException(userId);
385 * Checks if same password is entered and that they are not empty.
387 * @return Whether the same password was entered
389 private boolean isSamePasswordEntered () {
390 return ((!this.getUserPassword().isEmpty()) && (Objects.equals(this.getUserPassword(), this.getUserPasswordRepeat())));
394 * Updates list with given user instance
396 * @param user User instance
398 private void updateList (final User user) {
399 // The user should be valid
402 throw new NullPointerException("user is null"); //NOI18N
403 } else if (user.getUserId() == null) {
405 throw new NullPointerException("user.userId is null"); //NOI18N
406 } else if (user.getUserId() < 1) {
408 throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is invalid", user.getUserId())); //NOI18N
412 Iterator<User> iterator = this.userList.iterator();
415 while (iterator.hasNext()) {
417 User next = iterator.next();
419 // Is the same user id?
420 if (Objects.equals(user.getUserId(), next.getUserId())) {
421 // Found it, so remove it
422 this.userList.remove(next);
428 this.userList.add(user);