Skip to content

Commit

Permalink
feat(security): update UserController and improve security configurat…
Browse files Browse the repository at this point in the history
…ion for user roles (#79)
  • Loading branch information
Guhapriya01 committed Sep 12, 2024
1 parent 7614a5a commit e5d500d
Show file tree
Hide file tree
Showing 5 changed files with 78 additions and 79 deletions.
3 changes: 2 additions & 1 deletion JtProject/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -51,12 +51,13 @@
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>


<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import com.jtspringproject.JtSpringProject.models.User;
import com.jtspringproject.JtSpringProject.services.userService;
Expand All @@ -28,12 +29,14 @@ public static class AdminConfigurationAdapter{

@Bean
SecurityFilterChain adminFilterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(requests -> requests
.antMatchers("/admin/login").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN"))
http.antMatcher("/admin/**")
.authorizeHttpRequests(requests -> requests
.requestMatchers(new AntPathRequestMatcher("/admin/login")).permitAll()
.requestMatchers(new AntPathRequestMatcher("/admin/**")).hasRole("ADMIN")
)
.formLogin(login -> login
.loginPage("/admin/login")
.loginProcessingUrl("/adminloginvalidate")
.loginProcessingUrl("/admin/loginvalidate")
.successHandler((request, response, authentication) -> {
response.sendRedirect("/admin/"); // Redirect on success
})
Expand All @@ -49,6 +52,34 @@ SecurityFilterChain adminFilterChain(HttpSecurity http) throws Exception {
}
}

@Configuration
@Order(2)
public static class UserConfigurationAdapter{

@Bean
SecurityFilterChain userFilterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(requests -> requests
.antMatchers("/login", "/register", "/newuserregister" ,"/test", "/test2").permitAll()
.antMatchers("/**").hasRole("USER"))
.formLogin(login -> login
.loginPage("/login")
.loginProcessingUrl("/userloginvalidate")
.successHandler((request, response, authentication) -> {
response.sendRedirect("/"); // Redirect on success
})
.failureHandler((request, response, exception) -> {
response.sendRedirect("/login?error=true"); // Redirect on failure
}))

.logout(logout -> logout.logoutUrl("/logout")
.logoutSuccessUrl("/login")
.deleteCookies("JSESSIONID"));

http.csrf(csrf -> csrf.disable());
return http.build();
}
}

@Bean
UserDetailsService userDetailsService() {
return username -> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,11 @@
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jtspringproject.JtSpringProject.services.cartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
Expand All @@ -28,8 +27,6 @@
import com.jtspringproject.JtSpringProject.services.productService;
import com.jtspringproject.JtSpringProject.services.cartService;



@Controller
public class UserController{

Expand All @@ -53,43 +50,32 @@ public String buy()
{
return "buy";
}


@GetMapping("/")
public String userlogin(Model model) {

return "userLogin";
@GetMapping("/login")
public ModelAndView userlogin(@RequestParam(required = false) String error) {
ModelAndView mv = new ModelAndView("userLogin");
if ("true".equals(error)) {
mv.addObject("msg", "Please enter correct email and password");
}
return mv;
}
@RequestMapping(value = "userloginvalidate", method = RequestMethod.POST)
public ModelAndView userlogin( @RequestParam("username") String username, @RequestParam("password") String pass,Model model,HttpServletResponse res) {

System.out.println(pass);
User u = this.userService.checkLogin(username, pass);
System.out.println(u.getUsername());

if(username.equals(u.getUsername())) {

res.addCookie(new Cookie("username", u.getUsername()));
ModelAndView mView = new ModelAndView("index");
mView.addObject("user", u);
List<Product> products = this.productService.getProducts();

if (products.isEmpty()) {
mView.addObject("msg", "No products are available");
} else {
mView.addObject("products", products);
}
return mView;

@GetMapping("/")
public ModelAndView indexPage()
{
ModelAndView mView = new ModelAndView("index");
String username = SecurityContextHolder.getContext().getAuthentication().getName();
mView.addObject("user", username);
List<Product> products = this.productService.getProducts();

}else {
ModelAndView mView = new ModelAndView("userLogin");
mView.addObject("msg", "Please enter correct email and password");
return mView;
if (products.isEmpty()) {
mView.addObject("msg", "No products are available");
} else {
mView.addObject("products", products);
}

return mView;
}


@GetMapping("/user/products")
public ModelAndView getproduct() {

Expand Down Expand Up @@ -129,44 +115,25 @@ public ModelAndView newUseRegister(@ModelAttribute User user)
}

@GetMapping("/profileDisplay")
public String profileDisplay(Model model, HttpServletRequest request) {
try {
Cookie[] cookies = request.getCookies();
String username = null;

if (cookies != null) {
for (Cookie cookie : cookies) {
if ("username".equals(cookie.getName())) {
username = cookie.getValue();
break;
}
}
}

if (username != null) {
User user = userService.getUserByUsername(username);

if (user != null) {
model.addAttribute("userid", user.getId());
model.addAttribute("username", user.getUsername());
model.addAttribute("email", user.getEmail());
model.addAttribute("password", user.getPassword());
model.addAttribute("address", user.getAddress());
} else {
model.addAttribute("msg", "User not found");
}
} else {
model.addAttribute("msg", "Username not found in cookies");
}
} catch (Exception e) {
System.out.println("Exception: " + e);
model.addAttribute("msg", "An error occurred while retrieving user details");
}
return "updateProfile";
}

public String profileDisplay(Model model, HttpServletRequest request) {

String username = SecurityContextHolder.getContext().getAuthentication().getName();
User user = userService.getUserByUsername(username);

if (user != null) {
model.addAttribute("userid", user.getId());
model.addAttribute("username", user.getUsername());
model.addAttribute("email", user.getEmail());
model.addAttribute("password", user.getPassword());
model.addAttribute("address", user.getAddress());
} else {
model.addAttribute("msg", "User not found");
}

return "updateProfile";
}


//for Learning purpose of model
@GetMapping("/test")
public String Test(Model model)
Expand Down Expand Up @@ -212,4 +179,4 @@ public ModelAndView Test2()
// List<Cart>carts = cartService.getCarts();
// }

}
}
2 changes: 1 addition & 1 deletion JtProject/src/main/webapp/views/adminlogin.jsp
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@
<div class="login-container p-4">
<div class="jumbotron border p-4">
<h2 class="text-center">Admin Login</h2>
<form action="/adminloginvalidate" method="post">
<form action="/admin/loginvalidate" method="post">
<div class="form-group">
<label for="username">Username:</label>
<div class="input-group">
Expand Down
2 changes: 1 addition & 1 deletion JtProject/src/main/webapp/views/userLogin.jsp
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@
<div class="login-container p-4">
<div class="jumbotron border p-4">
<h2 class="text-center">User Login</h2>
<form action="userloginvalidate" method="post">
<form action="/userloginvalidate" method="post">
<div class="form-group">
<label for="username">Username</label>
<div class="input-group">
Expand Down

0 comments on commit e5d500d

Please sign in to comment.