Skip to content

Commit

Permalink
Adding login feature
Browse files Browse the repository at this point in the history
  • Loading branch information
iwokonl committed Feb 28, 2024
1 parent 0af7c08 commit 521bcba
Show file tree
Hide file tree
Showing 20 changed files with 360 additions and 28 deletions.
10 changes: 9 additions & 1 deletion Back/Spring/backend/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,15 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>5.1.3</version> <!-- Użyj odpowiedniej wersji Bootstrapa -->
</dependency>
<!-- PostgreSQL Driver -->
<dependency>
<groupId>org.postgresql</groupId>
Expand Down
Binary file not shown.
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package pl.zeto.backend.VMC.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
public class PasswordEncoderConfig {

@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
Original file line number Diff line number Diff line change
@@ -1,27 +1,47 @@
package pl.zeto.backend.VMC.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import pl.zeto.backend.VMC.service.CustomUserDetailsService;

@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Autowired
@Qualifier("userService")
private UserDetailsService userDetailsService;

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
}

@Autowired
private BCryptPasswordEncoder passwordEncoder;
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf().disable() // Wyłącza ochronę CSRF
.authorizeHttpRequests(auth -> auth
.anyRequest().permitAll() // Pozwala na dostęp do wszystkich zasobów bez autoryzacji
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeRequests(authorize -> authorize
.requestMatchers("/", "/home", "/register", "/process_register").permitAll() // Dostęp bez autoryzacji
.anyRequest().authenticated() // Wszystkie inne żądania wymagają autoryzacji
)
.formLogin(login -> login
.loginPage("/login") // Określa stronę logowania
.permitAll()
.defaultSuccessUrl("/", true)
)
.logout(logout -> logout
.permitAll() // Zezwala wszystkim na dostęp do wylogowania
);
return http.build();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package pl.zeto.backend.VMC.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class AccessDeniedController {

@GetMapping("/access-denied")
public String showAccessDeniedPage() {
return "access-denied";
}
}

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package pl.zeto.backend.VMC.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HomePageController {

@GetMapping("/")
public String home() {
return "index"; // Nazwa pliku bez rozszerzenia .html z katalogu resources/templates
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package pl.zeto.backend.VMC.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class LoginController {

@GetMapping("/login")
public String showLoginPage() {
return "login";
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package pl.zeto.backend.VMC.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import pl.zeto.backend.VMC.model.AppUser;
import pl.zeto.backend.VMC.model.Role;
import pl.zeto.backend.VMC.repository.UserRepo;

@Controller
public class RegisterController {

@Autowired
private UserRepo userRepo;
@Autowired
private pl.zeto.backend.VMC.service.UserService userService;

// Zwraca widok HTML
@GetMapping("/register")
public String showSignUpForm(Model model) {
model.addAttribute("user", new AppUser());
return "register";
}

// Przetwarza formularz rejestracji i zwraca stronę HTML
@PostMapping("/process_register")
public String processRegister(AppUser user) {

userService.addUser(user);
return "register_success";
}

// Endpoint API do obsługi rejestracji za pomocą JSON
@PostMapping("/api/register")
@ResponseBody
public ResponseEntity<Object> processRegisterApi(@RequestBody AppUser user) {
user.setRole(Role.USER);
userRepo.save(user);
return new ResponseEntity<>("User registered successfully", HttpStatus.CREATED);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package pl.zeto.backend.VMC.dto;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import pl.zeto.backend.VMC.model.AppAccount;
import pl.zeto.backend.VMC.model.AppUser;

import java.util.Collection;
import java.util.Collections;

public class CustomUserDetails implements UserDetails {

private AppUser appAccount;

public CustomUserDetails(AppUser account) {
this.appAccount = account;
}

@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return Collections.singleton(new SimpleGrantedAuthority(appAccount.getRole().name()));
}

@Override
public String getPassword() {
return appAccount.getPassword();
}

@Override
public String getUsername() {
return appAccount.getUsername();
}

@Override
public boolean isAccountNonExpired() {
return true;
}

@Override
public boolean isAccountNonLocked() {
return true;
}

@Override
public boolean isCredentialsNonExpired() {
return true;
}

@Override
public boolean isEnabled() {
return true;
}

// Implementacja pozostałych metod interfejsu UserDetails...
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,14 @@ public class AppUser {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private Role role;

private String username;
private String firstName;
private String lastName;
private String email;
private String password;
private Role role;


@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private Set<AppAccount> accounts;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,5 @@
import pl.zeto.backend.VMC.model.AppAccount;

public interface AccountRepo extends JpaRepository<AppAccount, Long> {

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package pl.zeto.backend.VMC.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import pl.zeto.backend.VMC.dto.CustomUserDetails;
import pl.zeto.backend.VMC.model.AppAccount;
import pl.zeto.backend.VMC.model.AppUser;
import pl.zeto.backend.VMC.repository.AccountRepo;
import pl.zeto.backend.VMC.repository.UserRepo;

@Service
public class CustomUserDetailsService implements UserDetailsService {

@Autowired
private UserRepo userRepo;

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
AppUser user = userRepo.findByUsername(username);
if (user == null) {
throw new UsernameNotFoundException("User not found");
}
return new CustomUserDetails(user);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,35 @@
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import pl.zeto.backend.VMC.model.AppUser;
import pl.zeto.backend.VMC.model.Role;
import pl.zeto.backend.VMC.repository.UserRepo;

import java.util.ArrayList;

@Service
public class UserService implements UserDetailsService {

private final UserRepo userRepository;
private final BCryptPasswordEncoder passwordEncoder;

@Autowired
private UserRepo userRepository;
public UserService(UserRepo userRepository, BCryptPasswordEncoder passwordEncoder) {
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
}


public void saveUser(AppUser user) {
user.setPassword(passwordEncoder.encode(user.getPassword()));
userRepository.save(user);
}
public AppUser addUser(AppUser user) {
// Tutaj można dodać logikę walidacji lub hashowania hasła
user.setRole(Role.USER);
user.setPassword(passwordEncoder.encode(user.getPassword()));
return userRepository.save(user);
}

Expand Down
7 changes: 4 additions & 3 deletions Back/Spring/backend/src/main/resources/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ spring.datasource.driver-class-name=org.postgresql.Driver

#Konfiguracja hibernate
#przy pierwszym uruchomieniu w innym wypadku wszystkie dane zostan? usuni?te z bazy
spring.jpa.hibernate.ddl-auto=create-drop
#spring.jpa.hibernate.ddl-auto=update
#spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
logging.level.org.hibernate.type=TRACE
logging.level.org.hibernate.SQL=DEBUG
Expand All @@ -29,4 +29,5 @@ spring.thymeleaf.cache=false


#konfigruacja springa
spring.main.allow-bean-definition-overriding=true
spring.main.allow-bean-definition-overriding=true
#logging.level.root=DEBUG
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Brak dostępu</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container mt-5">
<div class="alert alert-danger" role="alert">
Musisz być zalogowany, aby przejść dalej.
</div>
</div>
</body>
</html>
11 changes: 11 additions & 0 deletions Back/Spring/backend/src/main/resources/templates/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HomePage</title>
<link rel="stylesheet" href="/webjars/bootstrap/5.1.3/css/bootstrap.min.css"/>
</head>
<body>
<h1>HomePage</h1>
</body>
</html>
Loading

0 comments on commit 521bcba

Please sign in to comment.