Skip to content

Commit

Permalink
Merge pull request #92 from Arquisoft/proyectoJava
Browse files Browse the repository at this point in the history
Add better error handling, email validation, and auto login post signup
  • Loading branch information
Pelayori authored Feb 27, 2024
2 parents 0b99223 + 6b89221 commit 5cbe943
Show file tree
Hide file tree
Showing 5 changed files with 83 additions and 16 deletions.
7 changes: 7 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,13 @@
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-validator/commons-validator -->
<dependency>
<groupId>commons-validator</groupId>
<artifactId>commons-validator</artifactId>
<version>1.7</version>
</dependency>

</dependencies>

<build>
Expand Down
35 changes: 22 additions & 13 deletions src/main/java/com/uniovi/controllers/PlayersController.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,21 @@
import com.uniovi.configuration.SecurityConfig;
import com.uniovi.entities.Player;
import com.uniovi.services.PlayerService;
import com.uniovi.validators.SignUpValidator;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import com.uniovi.dto.PlayerDto;
import org.springframework.web.bind.annotation.ModelAttribute;
Expand All @@ -21,10 +30,12 @@
@Controller
public class PlayersController {
private final PlayerService playerService;
private final SignUpValidator signUpValidator;

@Autowired
public PlayersController(PlayerService playerService) {
public PlayersController(PlayerService playerService, SignUpValidator signUpValidator) {
this.playerService = playerService;
this.signUpValidator = signUpValidator;
}

@GetMapping("/signup")
Expand All @@ -42,27 +53,25 @@ public String showRegistrationForm(Model model){
}

@PostMapping("/signup")
public String registerUserAccount(@Valid @ModelAttribute("user") PlayerDto user, BindingResult result, Model model){
public String registerUserAccount(HttpServletRequest request, @Validated @ModelAttribute("user") PlayerDto user, BindingResult result, Model model){
if (SecurityConfig.isAuthenticated())
return "redirect:/home";

if(playerService.getUserByEmail(user.getEmail()).isPresent()){
result.rejectValue("email", null,
"There is already an account registered with the same email");
}

if (playerService.getUserByUsername(user.getUsername()).isPresent()) {
result.rejectValue("username", null,
"There is already an account registered with the same username");
}
signUpValidator.validate(user, result);

if(result.hasErrors()){
if(result.hasErrors()) {
model.addAttribute("user", user);
return "player/signup";
}

playerService.addNewPlayer(user);
return "redirect:/";

try {
request.login(user.getUsername(), user.getPassword());
} catch (ServletException e) {
return "redirect:/signup";
}
return "redirect:/home";
}

@GetMapping("/login")
Expand Down
3 changes: 3 additions & 0 deletions src/main/java/com/uniovi/services/impl/PlayerServiceImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,9 @@ public Player addNewPlayer(PlayerDto dto) {
passwordEncoder.encode(dto.getPassword())
);

if (dto.getRoles() == null)
dto.setRoles(new String[] {"ROLE_USER"} );

for (String roleStr : dto.getRoles()) {
Role r = roleService.getRole(roleStr);
if (r != null)
Expand Down
48 changes: 48 additions & 0 deletions src/main/java/com/uniovi/validators/SignUpValidator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package com.uniovi.validators;

import com.uniovi.dto.PlayerDto;
import com.uniovi.services.PlayerService;
import org.apache.commons.validator.routines.EmailValidator;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

@Component
public class SignUpValidator implements Validator {
private PlayerService playerService;

public SignUpValidator(PlayerService playerService) {
this.playerService = playerService;
}

@Override
public boolean supports(Class<?> clazz) {
return clazz.equals(PlayerDto.class);
}

@Override
public void validate(Object target, Errors errors) {
PlayerDto user = (PlayerDto) target;

if (!EmailValidator.getInstance().isValid(user.getEmail())) {
errors.rejectValue("email", null,
"El email no es válido");
}

if(playerService.getUserByEmail(user.getEmail()).isPresent()){
errors.rejectValue("email", null,
"Ya hay una cuenta registrada con este email");
}

if (playerService.getUserByUsername(user.getUsername()).isPresent()) {
errors.rejectValue("username", null,
"Ya existe una cuenta con este nombre de usuario");
}

if (user.getPassword() == null
|| !user.getPassword().equals(user.getPasswordConfirm())) {
errors.rejectValue("passwordConfirm", null,
"Las contraseñas no coinciden");
}
}
}
6 changes: 3 additions & 3 deletions src/main/resources/templates/player/signup.html
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,16 @@ <h2>Registrate</h2>
<label class="control-label col-sm-2" for="username">Nombre de usuario:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="username" name="username"
placeholder="wikiuser" required="true"/>
placeholder="wikiuser" required="true" th:value="${user.username}"/>
<span class="text-danger" th:if="${#fields.hasErrors('username')}" th:errors="*{username}"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="email">Correo electrónico:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="email" name="email"
placeholder="[email protected]" required="true" />

placeholder="[email protected]" required="true" th:value="${user.email}"/>
<span class="text-danger" th:if="${#fields.hasErrors('email')}" th:errors="*{email}"></span>
</div>
</div>
<div class="form-group">
Expand Down

0 comments on commit 5cbe943

Please sign in to comment.