Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions .github/labeler.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
backend:
- 'JtProject/src/main/java/**'

frontend:
- 'JtProject/src/main/resources/static/**'

views:
- 'JtProject/src/main/resources/templates/**'

config:
- 'JtProject/src/main/resources/application.properties'
- 'JtProject/src/main/resources/META-INF/**'

security:
- 'JtProject/src/main/java/com/jtspringproject/JtSpringProject/configuration/**'
- 'JtProject/src/main/java/com/jtspringproject/JtSpringProject/models/User.java'
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,10 @@
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;


import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
@Configuration
@EnableTransactionManagement
public class HibernateConfiguration {
Expand Down Expand Up @@ -69,4 +72,23 @@ public HibernateTransactionManager transactionManager() {
transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionManager;
}

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource);
em.setPackagesToScan(PACKAGES_TO_SCAN);

JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);

Properties jpaProperties = new Properties();
jpaProperties.put("hibernate.dialect", DIALECT);
jpaProperties.put("hibernate.show_sql", SHOW_SQL);
jpaProperties.put("hibernate.hbm2ddl.auto", HBM2DDL_AUTO);
em.setJpaProperties(jpaProperties);

return em;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -62,18 +62,9 @@ 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
}))

.antMatchers("/login", "/register", "/newuserregister", "/userloginvalidate"
,"/test", "/test2").permitAll())
// .antMatchers("/**").hasRole("USER"))
.logout(logout -> logout.logoutUrl("/logout")
.logoutSuccessUrl("/login")
.deleteCookies("JSESSIONID"))
Expand Down Expand Up @@ -103,7 +94,6 @@ UserDetailsService userDetailsService() {
.build();
};
}

@Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@

import com.jtspringproject.JtSpringProject.services.cartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
Expand All @@ -26,17 +28,20 @@
import com.jtspringproject.JtSpringProject.services.userService;
import com.jtspringproject.JtSpringProject.services.productService;
import com.jtspringproject.JtSpringProject.services.cartService;
import org.springframework.security.core.Authentication;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;


@Controller
public class UserController{

private final userService userService;
private final productService productService;

@Autowired
public UserController(userService userService, productService productService) {
private final PasswordEncoder passwordencoder;
public UserController(userService userService, productService productService,PasswordEncoder passwordencoder) {
this.userService = userService;
this.productService = productService;
this.passwordencoder=passwordencoder;
}

@GetMapping("/register")
Expand All @@ -53,6 +58,7 @@ public String buy()

@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");
Expand All @@ -65,6 +71,8 @@ public ModelAndView indexPage()
{
ModelAndView mView = new ModelAndView("index");
String username = SecurityContextHolder.getContext().getAuthentication().getName();
System.out.println( "home page"+username);

mView.addObject("username", username);
List<Product> products = this.productService.getProducts();

Expand Down Expand Up @@ -92,6 +100,37 @@ public ModelAndView getproduct() {
return mView;
}


@PostMapping("/userloginvalidate")
public ModelAndView userLoginValidate(@RequestParam String username,
@RequestParam String password) {
System.out.println(username);
System.out.println(password);

User user = userService.getUserByUsername(username);
System.out.println(user.getUsername());

ModelAndView mv = new ModelAndView();
if (user != null && passwordencoder.matches(password, user.getPassword())) {
// Login successful
// Optionally, manually set authentication in Spring Security context
Authentication auth = new UsernamePasswordAuthenticationToken(
user.getUsername(),
null,
List.of(new SimpleGrantedAuthority(user.getRole().replace("ROLE_", "")))
);
SecurityContextHolder.getContext().setAuthentication(auth);

mv.setViewName("redirect:/"); // redirect to home page
} else {
// Login failed
mv.setViewName("userLogin");
mv.addObject("msg", "Invalid username or password");
}
return mv;
}


@RequestMapping(value = "newuserregister", method = RequestMethod.POST)
public ModelAndView newUseRegister(@ModelAttribute User user)
{
Expand All @@ -101,6 +140,7 @@ public ModelAndView newUseRegister(@ModelAttribute User user)
if(!exists) {
System.out.println(user.getEmail());
user.setRole("ROLE_NORMAL");
user.setPassword(passwordencoder.encode( user.getPassword()));
this.userService.addUser(user);

System.out.println("New user created: " + user.getUsername());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,8 @@ public User saveUser(User user) {
// }
@Transactional
public User getUser(String username,String password) {
Query query = sessionFactory.getCurrentSession().createQuery("from CUSTOMER where username = :username");
Query query = sessionFactory.getCurrentSession()
.createQuery("from User where username = :username");
query.setParameter("username",username);

try {
Expand All @@ -63,7 +64,7 @@ public User getUser(String username,String password) {

@Transactional
public boolean userExists(String username) {
Query query = sessionFactory.getCurrentSession().createQuery("from CUSTOMER where username = :username");
Query query = sessionFactory.getCurrentSession().createQuery("from User where username = :username");
query.setParameter("username",username);
return !query.getResultList().isEmpty();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity(name="CUSTOMER")
@Table
@Entity
@Table(name="CUSTOMER")
public class User {

@Id
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{"properties": [{
"name": "entitymanager.packagesToScan",
"type": "java.lang.String",
"description": "A description for 'entitymanager.packagesToScan'"
}]}
22 changes: 11 additions & 11 deletions JtProject/src/main/resources/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -17,19 +17,19 @@ spring.mvc.view.suffix=.jsp


# Hibernate
hibernate.dialect= org.hibernate.dialect.MySQL5Dialect
hibernate.show_sql= true
hibernate.hbm2ddl.auto= update
#entitymanager.packagesToScan:

spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true
# Database connection
db.driver=com.mysql.cj.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/ecommjava?createDatabaseIfNotExist=true&useSSL=false&allowPublicKeyRetrieval=true
db.username=root
db.password=ron#4343

# Hibernate settings
hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=update

db.driver= com.mysql.cj.jdbc.Driver
db.url= jdbc:mysql://localhost:3306/ecommjava?createDatabaseIfNotExist=true
db.username= root
db.password=
entitymanager.packagesToScan= com
# Where your entity classes are
entitymanager.packagesToScan=com.jtspringproject.JtSpringProject.models

#spring.datasource.url=jdbc:mysql://localhost:3306/ecommjava?createDatabaseIfNotExist=true
#spring.datasource.username=root
Expand Down
Loading