This repository has been archived on 2020-08-02. You can view files and clone it, but cannot push or open issues or pull requests.
e-commerce/web_backend/src/main/java/org/hso/ecommerce/controller/RegisterController.java

80 lines
2.5 KiB
Java

package org.hso.ecommerce.controller;
import org.hso.ecommerce.entities.shop.Address;
import org.hso.ecommerce.entities.user.User;
import org.hso.ecommerce.repos.user.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Optional;
@Controller
public class RegisterController {
@Autowired
private final UserRepository userRepository = null;
@PostMapping("/register")
public String registerPost(HttpServletRequest request, HttpServletResponse response,
@RequestParam("username") String username, @RequestParam("password") String password,
@RequestParam("password2") String password2, @RequestParam("salutation") String salutation,
@RequestParam("name") String name, @RequestParam("address") String address,
HttpSession session) {
Optional<User> user = userRepository.findByEmail(username);
if (user.isPresent()) {
request.setAttribute("error", "Die Email Adresse existiert bereits.");
response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
return "register";
}
if (!password.equals(password2)) {
request.setAttribute("error", "Die Passwörter stimmen nicht überein.");
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return "register";
}
// set values for new user
User newUser = new User();
newUser.email = username;
newUser.setPassword(password);
newUser.email = username;
newUser.isEmployee = false;
newUser.salutation = salutation;
newUser.defaultPayment = null;
newUser.isActive = true;
newUser.created = new java.sql.Timestamp(System.currentTimeMillis());
Address newAddress = new Address();
newAddress.name = name;
newAddress.addressString = address;
newUser.defaultDeliveryAddress = newAddress;
userRepository.save(newUser); // save newUser
user = userRepository.findByEmail(username);
session.setAttribute("userId", user.get().getId());
String gto = (String) session.getAttribute("afterLogin");
//login after register
if (gto != null && gto.startsWith("/")) {
return "redirect:" + gto;
} else {
return "redirect:/";
}
}
@GetMapping("/register")
public String register() {
return "register";
}
}