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.jjobs.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.jcontacts.contact.Contact;
36 import org.mxchange.jjobs.beans.contact.JobsContactWebSessionController;
37 import org.mxchange.jusercore.container.login.UserLoginContainer;
38 import org.mxchange.jusercore.events.user.AdminAddedUserEvent;
39 import org.mxchange.jusercore.events.user.AdminUserAddedEvent;
40 import org.mxchange.jusercore.events.user.update.AdminUpdatedUserDataEvent;
41 import org.mxchange.jusercore.events.user.update.AdminUserDataUpdatedEvent;
42 import org.mxchange.jusercore.events.user.update.UpdatedUserPersonalDataEvent;
43 import org.mxchange.jusercore.exceptions.EmailAddressAlreadyRegisteredException;
44 import org.mxchange.jusercore.exceptions.UserNameAlreadyRegisteredException;
45 import org.mxchange.jusercore.exceptions.UserNotFoundException;
46 import org.mxchange.jusercore.exceptions.UserPasswordRepeatMismatchException;
47 import org.mxchange.jusercore.model.user.LoginUser;
48 import org.mxchange.jusercore.model.user.User;
49 import org.mxchange.jusercore.model.user.UserSessionBeanRemote;
50 import org.mxchange.jusercore.model.user.UserUtils;
51 import org.mxchange.jusercore.model.user.profilemodes.ProfileMode;
52 import org.mxchange.jusercore.model.user.status.UserAccountStatus;
53 import org.mxchange.pizzaapplication.beans.contact.PizzaContactWebSessionController;
54 import org.mxchange.pizzaapplication.beans.helper.PizzaAdminWebRequestController;
57 * A user bean (controller)
59 * @author Roland Haeder<roland@mxchange.org>
61 @Named ("adminUserController")
63 public class JobsAdminUserWebRequestBean implements JobsAdminUserWebRequestController {
68 private static final long serialVersionUID = 542_145_347_916L;
71 * An event fired when the administrator has added a new user
75 private Event<AdminAddedUserEvent> addedUserEvent;
78 * Admin helper instance
81 private PizzaAdminWebRequestController adminHelper;
84 * Regular contact controller
87 private JobsContactWebSessionController contactController;
90 * An event fired when the administrator has updated a new user
94 private Event<AdminUpdatedUserDataEvent> updatedUserDataEvent;
99 private final UserSessionBeanRemote userBean;
102 * Regular user controller
105 private JobsUserWebSessionController userController;
108 * A list of all user profiles
110 private List<User> userList;
115 private String userName;
118 * User password (unencrypted from web form)
120 private String userPassword;
123 * User password repeated (unencrypted from web form)
125 private String userPasswordRepeat;
128 * Default constructor
130 public JobsAdminUserWebRequestBean () {
133 // Get initial context
134 Context context = new InitialContext();
137 this.userBean = (UserSessionBeanRemote) context.lookup("java:global/jjobs-ejb/user!org.mxchange.jusercore.model.user.UserSessionBeanRemote"); //NOI18N
138 } catch (final NamingException e) {
140 throw new FaceletException(e);
145 public String addUser () {
146 // Create new user instance
147 User localUser = new LoginUser();
149 // Set user name, CONFIRMED and INVISIBLE
150 localUser.setUserName(this.getUserName());
151 localUser.setUserAccountStatus(UserAccountStatus.CONFIRMED);
152 localUser.setUserProfileMode(ProfileMode.INVISIBLE);
154 // Create contact instance
155 Contact contact = this.contactController.createContactInstance();
157 // Set contact in user
158 localUser.setUserContact(contact);
160 // Init variable for password
161 String password = null;
163 // Is the user name or email address used already?
164 // @TODO Add password length check
165 if (this.userController.isUserNameRegistered(localUser)) {
166 // User name is already used
167 throw new FaceletException(new UserNameAlreadyRegisteredException(localUser));
168 } else if (this.contactController.isEmailAddressRegistered(localUser.getUserContact())) {
169 // Email address is already used
170 throw new FaceletException(new EmailAddressAlreadyRegisteredException(localUser));
171 } else if ((this.getUserPassword() == null && (this.getUserPasswordRepeat() == null)) || ((this.getUserPassword().isEmpty()) && (this.getUserPasswordRepeat().isEmpty()))) {
172 // Empty password entered, then generate one
173 password = UserUtils.createRandomPassword(JobsUserWebSessionController.MINIMUM_PASSWORD_LENGTH);
174 } else if (!this.isSamePasswordEntered()) {
175 // Both passwords don't match
176 throw new FaceletException(new UserPasswordRepeatMismatchException(localUser));
178 // Both match, so get it from this bean
179 password = this.getUserPassword();
182 // The password should not be null and at least 5 characters long
183 assert (password != null) : "password is null"; //NOI18N
184 assert (password.length() >= JobsUserWebSessionController.MINIMUM_PASSWORD_LENGTH) : "Password is not long enough."; //NOI18N
186 // Encrypt password and set it
187 localUser.setUserEncryptedPassword(UserUtils.encryptPassword(password));
189 // Init updated user instance
190 User updatedUser = null;
193 // Now, that all is set, call EJB
194 updatedUser = this.userBean.addUser(localUser);
195 } catch (final UserNameAlreadyRegisteredException | EmailAddressAlreadyRegisteredException ex) {
197 throw new FaceletException(ex);
201 this.addedUserEvent.fire(new AdminUserAddedEvent(updatedUser));
203 // Add user to local list
204 this.userList.add(updatedUser);
206 // Clear contact instance
207 this.contactController.clear();
209 // Return to user list (for now)
210 return "admin_list_user"; //NOI18N
214 public void afterUserUpdatedPersonalData (@Observes final UpdatedUserPersonalDataEvent event) {
218 throw new NullPointerException("event is null"); //NOI18N
219 } else if (event.getUpdatedUser() == null) {
221 throw new NullPointerException("event.updatedUser is null"); //NOI18N
222 } else if (event.getUpdatedUser().getUserId() == null) {
224 throw new NullPointerException("event.updatedUser.userId is null"); //NOI18N
225 } else if (event.getUpdatedUser().getUserId() < 1) {
227 throw new IllegalArgumentException(MessageFormat.format("event.updatedUser.userId={0} is in valid", event.getUpdatedUser().getUserId())); //NOI18N
230 // All fine, so update list
231 this.updateList(event.getUpdatedUser());
235 public List<User> allUsers () {
237 return Collections.unmodifiableList(this.userList);
241 public String editUserData () {
243 User user = this.adminHelper.getUser();
245 // Null password means not setting it
246 String encryptedPassword = null;
248 // Check if user instance is in helper and valid
251 throw new NullPointerException("adminHelper.user is null"); //NOI18N
252 } else if (user.getUserId() == null) {
254 throw new NullPointerException("adminHelper.user.userId is null"); //NOI18N //NOI18N
255 } else if (user.getUserId() < 1) {
257 throw new IllegalStateException(MessageFormat.format("adminHelper.user.userId={0} is invalid", user.getUserId()));
258 } else if (this.getUserName() == null) {
259 // Not all required fields are set
260 throw new NullPointerException("this.userName is null"); //NOI18N
261 } else if (this.getUserName().isEmpty()) {
262 // Not all required fields are set
263 throw new IllegalArgumentException("this.userName is empty"); //NOI18N
264 } else if (((!this.getUserPassword().isEmpty()) || (!this.getUserPasswordRepeat().isEmpty())) && (!this.isSamePasswordEntered())) {
265 // Not same password entered
266 this.setUserPassword(null);
267 this.setUserPasswordRepeat(null);
270 throw new FaceletException("Not same password entered"); //NOI18N
271 } else if (this.isSamePasswordEntered()) {
272 // Same password entered, create container
273 if (UserUtils.ifPasswordMatches(new UserLoginContainer(user, this.getUserPassword()))) {
274 // Same password entered
275 throw new FaceletException("Same password as stored entered."); //NOI18N
279 encryptedPassword = UserUtils.encryptPassword(this.getUserPassword());
283 user.setUserName(this.getUserName());
285 // Is a password set?
286 if (encryptedPassword != null) {
288 user.setUserEncryptedPassword(encryptedPassword);
291 // Call EJB for updating user data
292 User updatedUser = this.userBean.updateUserData(user);
295 this.updateList(updatedUser);
298 this.updatedUserDataEvent.fire(new AdminUserDataUpdatedEvent(updatedUser));
300 // Return to user list (for now)
301 return "admin_list_user"; //NOI18N
305 public String getUserName () {
306 return this.userName;
310 public void setUserName (final String userName) {
311 this.userName = userName;
315 public String getUserPassword () {
316 return this.userPassword;
320 public void setUserPassword (final String userPassword) {
321 this.userPassword = userPassword;
325 public String getUserPasswordRepeat () {
326 return this.userPasswordRepeat;
330 public void setUserPasswordRepeat (final String userPasswordRepeat) {
331 this.userPasswordRepeat = userPasswordRepeat;
335 public boolean hasUsers () {
336 return (!this.allUsers().isEmpty());
340 * Post-initialization of this class
343 public void init () {
344 // Initialize user list
345 this.userList = this.userBean.allUsers();
349 public User lookupUserById (final Long userId) throws UserNotFoundException {
350 // Parameter must be valid
351 if (null == userId) {
353 throw new NullPointerException("userId is null"); //NOI18N
354 } else if (userId < 1) {
356 throw new IllegalArgumentException(MessageFormat.format("userId={0} is not valid.", userId)); //NOI18N
362 // Try to lookup it in visible user list
363 for (final Iterator<User> iterator = this.userList.iterator(); iterator.hasNext();) {
365 User next = iterator.next();
367 // Is the user id found?
368 if (Objects.equals(next.getUserId(), userId)) {
369 // Copy to other variable
377 // Not visible for the current user
378 throw new UserNotFoundException(userId);
386 * Checks if same password is entered and that they are not empty.
388 * @return Whether the same password was entered
390 private boolean isSamePasswordEntered () {
391 return ((!this.getUserPassword().isEmpty()) && (Objects.equals(this.getUserPassword(), this.getUserPasswordRepeat())));
395 * Updates list with given user instance
397 * @param user User instance
399 private void updateList (final User user) {
400 // The user should be valid
403 throw new NullPointerException("user is null"); //NOI18N
404 } else if (user.getUserId() == null) {
406 throw new NullPointerException("user.userId is null"); //NOI18N
407 } else if (user.getUserId() < 1) {
409 throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is invalid", user.getUserId())); //NOI18N
413 Iterator<User> iterator = this.userList.iterator();
416 while (iterator.hasNext()) {
418 User next = iterator.next();
420 // Is the same user id?
421 if (Objects.equals(user.getUserId(), next.getUserId())) {
422 // Found it, so remove it
423 this.userList.remove(next);
429 this.userList.add(user);