2020-04-29 22:44:16 +02:00
package org.hso.ecommerce.controller ;
2020-04-28 22:41:29 +02:00
2020-06-24 18:25:42 +02:00
import org.hso.ecommerce.entities.shop.ShoppingCart ;
2020-06-12 23:48:28 +02:00
import org.hso.ecommerce.entities.user.User ;
import org.hso.ecommerce.repos.user.UserRepository ;
import org.springframework.beans.factory.annotation.Autowired ;
2020-04-28 22:41:29 +02:00
import org.springframework.stereotype.Controller ;
2020-06-24 18:25:42 +02:00
import org.springframework.web.bind.annotation.* ;
2020-04-28 22:41:29 +02:00
2020-06-24 18:23:01 +02:00
import javax.servlet.http.HttpServletRequest ;
import javax.servlet.http.HttpServletResponse ;
import javax.servlet.http.HttpSession ;
import java.util.Optional ;
2020-04-28 22:41:29 +02:00
@Controller
2020-06-12 23:48:28 +02:00
@RequestMapping ( " / " )
2020-04-29 22:44:16 +02:00
public class LoginController {
2020-06-12 23:48:28 +02:00
@Autowired
private final UserRepository userRepository = null ;
@GetMapping ( " login " )
public String login ( ) {
return " login " ;
}
@PostMapping ( " login " )
public String loginPost ( HttpServletRequest request , HttpServletResponse response ,
@RequestParam ( " username " ) String username , @RequestParam ( " password " ) String password , HttpSession session ) {
String gto = ( String ) session . getAttribute ( " afterLogin " ) ;
Optional < User > user = userRepository . findByEmail ( username ) ;
if ( ! user . isPresent ( ) ) {
2020-06-13 10:41:59 +02:00
request . setAttribute ( " error " , " Die Email Adresse falsch. " ) ;
2020-06-12 23:48:28 +02:00
response . setStatus ( HttpServletResponse . SC_EXPECTATION_FAILED ) ;
return " login " ;
}
if ( ! user . get ( ) . validatePassword ( password ) ) {
2020-06-13 10:41:59 +02:00
request . setAttribute ( " error " , " Das Passwort ist falsch. " ) ;
2020-06-12 23:48:28 +02:00
response . setStatus ( HttpServletResponse . SC_EXPECTATION_FAILED ) ;
return " login " ;
}
if ( ! user . get ( ) . isActive ) {
2020-06-13 10:41:59 +02:00
request . setAttribute ( " error " , " Dieses Konto ist deaktiviert.. " ) ;
2020-06-12 23:48:28 +02:00
response . setStatus ( HttpServletResponse . SC_EXPECTATION_FAILED ) ;
return " login " ;
}
session . setAttribute ( " userId " , user . get ( ) . getId ( ) ) ;
if ( gto ! = null & & gto . startsWith ( " / " ) ) {
return " redirect: " + gto ;
} else {
return " redirect:/ " ;
}
}
@PostMapping ( " logout " )
2020-06-24 18:25:42 +02:00
public String logoutPost ( @RequestAttribute ( value = " shoppingCart " ) ShoppingCart shoppingCart , HttpSession session ) {
2020-06-12 23:48:28 +02:00
session . removeAttribute ( " userId " ) ;
2020-06-24 18:25:42 +02:00
shoppingCart . clear ( ) ;
2020-06-24 18:23:01 +02:00
2020-06-12 23:48:28 +02:00
return " redirect:/ " ;
}
2020-04-28 22:41:29 +02:00
}