Skip to content

Commit

Permalink
Edit user and updating email works fine now
Browse files Browse the repository at this point in the history
  • Loading branch information
surajcm committed Feb 21, 2024
1 parent 243fdf5 commit 4872355
Show file tree
Hide file tree
Showing 9 changed files with 80 additions and 13 deletions.
1 change: 1 addition & 0 deletions config/checkstyle/suppressions.xml
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,5 @@ WHAT AND WHY CHECKS SUPPRESSED
<suppress files="SecurityConfig.java" checks="MethodLength"/>
<suppress files="SecurityConfig.java" checks="IllegalCatch"/>
<suppress files="RegistrationController.java" checks="MethodLength"/>
<suppress files="UserServiceImpl.java" checks="MethodLength"/>
</suppressions>
2 changes: 1 addition & 1 deletion gradle/dependencies.gradle
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
dependencies {
errorprone("com.google.errorprone:error_prone_core:2.24.1")
errorprone("com.google.errorprone:error_prone_core:2.25.0")
errorproneJavac("com.google.errorprone:javac:9+181-r4173-1")

implementation("org.springframework.boot:spring-boot-starter-web")
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
package com.quiz.darkhold.user.controller;

import com.quiz.darkhold.user.entity.User;
import com.quiz.darkhold.user.exception.UserNotFoundException;
import com.quiz.darkhold.user.service.UserService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

Expand Down Expand Up @@ -40,7 +42,8 @@ public String createUser(final Model model) {
user.setEnabled(true);
model.addAttribute("userForm", user);
model.addAttribute("listRoles", roles);
return "user/createuser";
model.addAttribute("pageTitle", "Create New User");
return "user/user_form";
}

@PostMapping("/users/save")
Expand All @@ -50,5 +53,21 @@ public String saveUser(final User user, final RedirectAttributes redirectAttribu
redirectAttributes.addFlashAttribute("message", "The user has been saved successfully");
return "redirect:/userManagement";
}

@GetMapping("/user/edit/{id}")
public String editUser(@PathVariable(name = "id") final Long id, final Model model,
final RedirectAttributes redirectAttributes) {
logger.info("Into the editUser method, id is {}", id);
try {
var user = userService.get(id);
model.addAttribute("userForm", user);
model.addAttribute("pageTitle", "Edit User (ID: " + id + ")");
model.addAttribute("listRoles", userService.listRoles());
return "user/user_form";
} catch (UserNotFoundException ex) {
redirectAttributes.addAttribute("message", ex.getMessage());
}
return "redirect:/userManagement";
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public UserRestController(final UserService userService) {
}

@PostMapping("/users/check_email")
public String checkDuplicateEmail(@Param("email") final String email) {
return userService.isEmailUnique(email) ? "OK" : "DUPLICATED";
public String checkDuplicateEmail(@Param("id") final Long id, @Param("email") final String email) {
return userService.isEmailUnique(id, email) ? "OK" : "DUPLICATED";
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package com.quiz.darkhold.user.exception;

public class UserNotFoundException extends Exception {

public UserNotFoundException(final String message) {
super(message);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import com.quiz.darkhold.user.entity.Role;
import com.quiz.darkhold.user.entity.User;
import com.quiz.darkhold.user.exception.UserNotFoundException;

import java.util.List;

Expand All @@ -14,6 +15,8 @@ public interface UserService {

List<Role> listRoles();

Boolean isEmailUnique(String email);
Boolean isEmailUnique(Long id, String email);

User get(Long id) throws UserNotFoundException;
}

39 changes: 35 additions & 4 deletions src/main/java/com/quiz/darkhold/user/service/UserServiceImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import com.quiz.darkhold.user.entity.Role;
import com.quiz.darkhold.user.entity.User;
import com.quiz.darkhold.user.exception.UserNotFoundException;
import com.quiz.darkhold.user.repository.RoleRepository;
import com.quiz.darkhold.user.repository.UserRepository;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
Expand All @@ -25,8 +26,19 @@ public UserServiceImpl(final UserRepository userRepository,

@Override
public void save(final User user) {
var pass = encoder.encode(user.getPassword());
user.setPassword(pass);
var isUpdating = (user.getId() != null);
if (isUpdating) {
var existingUser = userRepository.findById(user.getId()).get();
if (user.getPassword().isEmpty()) {
user.setPassword(existingUser.getPassword());
} else {
var pass = encoder.encode(user.getPassword());
user.setPassword(pass);
}
} else {
var pass = encoder.encode(user.getPassword());
user.setPassword(pass);
}
userRepository.save(user);
}

Expand All @@ -46,7 +58,26 @@ public List<Role> listRoles() {
}

@Override
public Boolean isEmailUnique(final String email) {
return userRepository.findByEmail(email) == null;
public Boolean isEmailUnique(final Long id, final String email) {
var userByEmail = userRepository.findByEmail(email);
if (userByEmail == null) {
return true;
}
var isCreatingNew = (id == null);
if (isCreatingNew) {
if (userByEmail != null) {
return false;
}
} else {
if (userByEmail.getId().equals(id)) {
return false;
}
}
return userByEmail == null;
}

@Override
public User get(final Long id) throws UserNotFoundException {
return userRepository.findById(id).orElseThrow(() -> new UserNotFoundException("Could not find any user with the id " + id));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,11 @@
<div class="container">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">Create User</h3>
<h3 class="panel-title">[[${pageTitle}]]</h3>
</div>
</div>
<form th:action="@{/users/save}" method="post" th:object="${userForm}" onsubmit="return checkEmailUnique(this);">
<input type="hidden" th:field="*{id}" />
<div class="border border-secondary rounded p-3">
<div class="input-group mb-3">
<label class="col-sm-4 col-form-label">First Name : </label>
Expand All @@ -46,7 +47,10 @@ <h3 class="panel-title">Create User</h3>
<div class="input-group mb-3">
<label class="col-sm-4 col-form-label">Password : </label>
<div class="col-sm-8">
<input type="password" class="form-control" th:field="*{password}" required minlength="8" maxlength="20" />
<input type="password" th:if="${userForm.id == null}" class="form-control"
th:field="*{password}" required minlength="8" maxlength="20" />
<input type="password" th:if="${userForm.id != null}" class="form-control"
th:field="*{password}" minlength="8" maxlength="20" />
</div>
</div>
<div class="input-group mb-3">
Expand Down Expand Up @@ -98,10 +102,11 @@ <h4 class="modal-title" id="modalTitle">Warning</h4>

function checkEmailUnique(form) {
const email = form.email.value;
const userId = form.id.value;
const xhr = new XMLHttpRequest();
xhr.open("POST", "/users/check_email", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("email=" + encodeURIComponent(email));
xhr.send("email=" + encodeURIComponent(email) + "&userId=" + userId);
xhr.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
// The request has been processed successfully
Expand Down
2 changes: 1 addition & 1 deletion src/main/resources/templates/user/usermanagement.html
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ <h2>Manage Users</h2>
<a th:if="${user.enabled == false}" class="fas fa-check-circle fa-2x icon-dark" href=""></a>
</td>
<td>
<a class="fas fa-edit fa-2x icon-green" th:href="@{'/users/edit/' + ${user.id}}" title="Edit this user"></a>
<a class="fas fa-edit fa-2x icon-green" th:href="@{'/user/edit/' + ${user.id}}" title="Edit this user"></a>
&nbsp;
<a class="fas fa-trash fa-2x icon-dark" href=""></a>
</td>
Expand Down

0 comments on commit 4872355

Please sign in to comment.