Checkpoint 4. Basic Auth, get login.
This commit is contained in:
		
							parent
							
								
									83bc1b8e85
								
							
						
					
					
						commit
						010e862edc
					
				
							
								
								
									
										8
									
								
								pom.xml
									
									
									
									
									
								
							
							
						
						
									
										8
									
								
								pom.xml
									
									
									
									
									
								
							| @ -55,10 +55,10 @@ | |||||||
|             <artifactId>postgresql</artifactId> |             <artifactId>postgresql</artifactId> | ||||||
|         </dependency> |         </dependency> | ||||||
| 
 | 
 | ||||||
| <!--        <dependency>--> |         <dependency> | ||||||
| <!--            <groupId>org.springframework.boot</groupId>--> |             <groupId>org.springframework.boot</groupId> | ||||||
| <!--            <artifactId>spring-boot-starter-security</artifactId>--> |             <artifactId>spring-boot-starter-security</artifactId> | ||||||
| <!--        </dependency>--> |         </dependency> | ||||||
| 
 | 
 | ||||||
|     </dependencies> |     </dependencies> | ||||||
| 
 | 
 | ||||||
|  | |||||||
| @ -1,40 +1,43 @@ | |||||||
| //package com.example.nto.config; | package com.example.nto.config; | ||||||
| // | 
 | ||||||
| //import lombok.RequiredArgsConstructor; | import lombok.RequiredArgsConstructor; | ||||||
| //import org.springframework.context.annotation.Configuration; | import org.springframework.context.annotation.Bean; | ||||||
| //import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; | import org.springframework.context.annotation.Configuration; | ||||||
| //import org.springframework.security.config.annotation.web.builders.HttpSecurity; | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; | ||||||
| //import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; | import org.springframework.security.config.annotation.web.builders.HttpSecurity; | ||||||
| //import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; | ||||||
| //import org.springframework.security.core.userdetails.UserDetailsService; | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; | ||||||
| //import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; | import org.springframework.security.core.userdetails.UserDetailsService; | ||||||
| //import org.springframework.security.crypto.password.PasswordEncoder; | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; | ||||||
| // | import org.springframework.security.crypto.password.PasswordEncoder; | ||||||
| //@Configuration | 
 | ||||||
| //@EnableWebSecurity | @Configuration | ||||||
| //@RequiredArgsConstructor | @EnableWebSecurity | ||||||
| //public class WebSecurityConfig extends WebSecurityConfigurerAdapter { | @RequiredArgsConstructor | ||||||
| // | public class WebSecurityConfig extends WebSecurityConfigurerAdapter { | ||||||
| //    private final UserDetailsService userDetailsService; | 
 | ||||||
| // |     private final UserDetailsService userDetailsService; | ||||||
| //    @Override | 
 | ||||||
| //    protected void configure(HttpSecurity http) throws Exception { |     @Override | ||||||
| //        http |     protected void configure(HttpSecurity http) throws Exception { | ||||||
| //                .csrf().disable() |         http | ||||||
| //                .authorizeRequests() |                 .csrf().disable() | ||||||
| //                .antMatchers("/api/employee/registration").hasAuthority("ROLE_ADMIN") |                 .authorizeRequests() | ||||||
| //                .anyRequest().authenticated() |                 .antMatchers("/api/employee/registration").hasAuthority("ROLE_ADMIN") | ||||||
| //                .and() |                 .anyRequest().authenticated() | ||||||
| //                .httpBasic() |                 .and() | ||||||
| //                .and() |                 .httpBasic() | ||||||
| //    } |                 .and() | ||||||
| // |                 .headers().frameOptions().disable(); | ||||||
| //    @Override |     } | ||||||
| //    protected void configure(AuthenticationManagerBuilder auth) throws Exception { | 
 | ||||||
| //        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); |     @Override | ||||||
| //    } |     protected void configure(AuthenticationManagerBuilder auth) throws Exception { | ||||||
| // |         auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); | ||||||
| //    public PasswordEncoder passwordEncoder(){ |     } | ||||||
| //        return new BCryptPasswordEncoder(); | 
 | ||||||
| //    } |     @Bean | ||||||
| //} |     public PasswordEncoder passwordEncoder(){ | ||||||
|  |         return new BCryptPasswordEncoder(); | ||||||
|  |     } | ||||||
|  | } | ||||||
|  | |||||||
| @ -9,6 +9,7 @@ import com.example.nto.service.impl.EmployeeServiceImpl; | |||||||
| import lombok.AllArgsConstructor; | import lombok.AllArgsConstructor; | ||||||
| import org.springframework.http.HttpStatus; | import org.springframework.http.HttpStatus; | ||||||
| import org.springframework.http.ResponseEntity; | import org.springframework.http.ResponseEntity; | ||||||
|  | import org.springframework.security.core.Authentication; | ||||||
| import org.springframework.web.bind.annotation.*; | import org.springframework.web.bind.annotation.*; | ||||||
| 
 | 
 | ||||||
| import java.time.LocalDateTime; | import java.time.LocalDateTime; | ||||||
| @ -92,4 +93,9 @@ public class EmployeeController { | |||||||
|         return ResponseEntity.status(HttpStatus.OK).body(service.createEmployee(dto)); |         return ResponseEntity.status(HttpStatus.OK).body(service.createEmployee(dto)); | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|  |     @GetMapping("/login") | ||||||
|  |     public ResponseEntity<EmployeeDTO> getLogin(Authentication authentication){ | ||||||
|  |         return ResponseEntity.status(HttpStatus.OK).body(service.findEmployeeDTOByUsername(authentication.getName())); | ||||||
|  |     } | ||||||
|  | 
 | ||||||
| } | } | ||||||
|  | |||||||
| @ -1,14 +1,16 @@ | |||||||
| package com.example.nto.entity; | package com.example.nto.entity; | ||||||
| 
 | 
 | ||||||
| import lombok.Data; | import lombok.Data; | ||||||
| //import org.springframework.security.core.GrantedAuthority; | import org.springframework.security.core.GrantedAuthority; | ||||||
| 
 | 
 | ||||||
| import javax.persistence.*; | import javax.persistence.*; | ||||||
|  | import java.util.List; | ||||||
|  | import java.util.Set; | ||||||
| 
 | 
 | ||||||
| @Data | @Data | ||||||
| @Entity | @Entity | ||||||
| @Table(name = "authorities") | @Table(name = "authorities") | ||||||
| public class Authority {//implements GrantedAuthority { | public class Authority implements GrantedAuthority { | ||||||
| 
 | 
 | ||||||
|     @Id |     @Id | ||||||
|     @GeneratedValue(strategy = GenerationType.IDENTITY) |     @GeneratedValue(strategy = GenerationType.IDENTITY) | ||||||
| @ -17,4 +19,7 @@ public class Authority {//implements GrantedAuthority { | |||||||
|     @Column(name = "authority") |     @Column(name = "authority") | ||||||
|     private String authority; |     private String authority; | ||||||
| 
 | 
 | ||||||
|  | //    @OneToMany(targetEntity = Employee.class, fetch = FetchType.EAGER, cascade = CascadeType.ALL) | ||||||
|  | //    private List<Employee> employees; | ||||||
|  | 
 | ||||||
| } | } | ||||||
|  | |||||||
| @ -4,7 +4,7 @@ import lombok.AllArgsConstructor; | |||||||
| import lombok.Builder; | import lombok.Builder; | ||||||
| import lombok.Data; | import lombok.Data; | ||||||
| import lombok.NoArgsConstructor; | import lombok.NoArgsConstructor; | ||||||
| //import org.springframework.security.core.userdetails.UserDetails; | import org.springframework.security.core.userdetails.UserDetails; | ||||||
| 
 | 
 | ||||||
| import javax.persistence.*; | import javax.persistence.*; | ||||||
| import java.util.Set; | import java.util.Set; | ||||||
| @ -15,7 +15,7 @@ import java.util.Set; | |||||||
| @AllArgsConstructor | @AllArgsConstructor | ||||||
| @Entity | @Entity | ||||||
| @Table(name="employee") | @Table(name="employee") | ||||||
| public class Employee {//implements UserDetails { | public class Employee implements UserDetails { | ||||||
|     @Id |     @Id | ||||||
|     @GeneratedValue(strategy = GenerationType.IDENTITY) |     @GeneratedValue(strategy = GenerationType.IDENTITY) | ||||||
|     private long id; |     private long id; | ||||||
| @ -38,26 +38,32 @@ public class Employee {//implements UserDetails { | |||||||
|     @Column(name="lastVisit") |     @Column(name="lastVisit") | ||||||
|     private String lastVisit; |     private String lastVisit; | ||||||
| 
 | 
 | ||||||
| //    @ManyToMany(fetch = FetchType.EAGER) |     @ManyToMany(fetch = FetchType.EAGER) | ||||||
| //    private Set<Authority> authorities; | //    @JoinTable(name = "employee_authorities", | ||||||
|  | //            joinColumns = @JoinColumn(name = "employee_id"), | ||||||
|  | //            inverseJoinColumns = @JoinColumn(name = "authorities_id") | ||||||
|  | //    ) | ||||||
|  |     private Set<Authority> authorities; | ||||||
|  | //    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER) | ||||||
|  | //    @JoinTable(name = "Employee_AUTHORITIES") | ||||||
| 
 | 
 | ||||||
| //    @Override |     @Override | ||||||
| //    public boolean isAccountNonExpired() { |     public boolean isAccountNonExpired() { | ||||||
| //        return true; |         return true; | ||||||
| //    } |     } | ||||||
| // | 
 | ||||||
| //    @Override |     @Override | ||||||
| //    public boolean isAccountNonLocked() { |     public boolean isAccountNonLocked() { | ||||||
| //        return true; |         return true; | ||||||
| //    } |     } | ||||||
| // | 
 | ||||||
| //    @Override |     @Override | ||||||
| //    public boolean isCredentialsNonExpired() { |     public boolean isCredentialsNonExpired() { | ||||||
| //        return true; |         return true; | ||||||
| //    } |     } | ||||||
| // | 
 | ||||||
| //    @Override |     @Override | ||||||
| //    public boolean isEnabled() { |     public boolean isEnabled() { | ||||||
| //        return true; |         return true; | ||||||
| //    } |     } | ||||||
| } | } | ||||||
|  | |||||||
| @ -9,6 +9,7 @@ import com.example.nto.repository.EmployeeRepository; | |||||||
| import com.example.nto.service.EmployeeService; | import com.example.nto.service.EmployeeService; | ||||||
| import com.example.nto.util.EmployeeMapper; | import com.example.nto.util.EmployeeMapper; | ||||||
| import lombok.AllArgsConstructor; | import lombok.AllArgsConstructor; | ||||||
|  | import org.springframework.security.crypto.password.PasswordEncoder; | ||||||
| import org.springframework.stereotype.Service; | import org.springframework.stereotype.Service; | ||||||
| 
 | 
 | ||||||
| import java.time.LocalDateTime; | import java.time.LocalDateTime; | ||||||
| @ -17,7 +18,10 @@ import java.util.Optional; | |||||||
| @Service | @Service | ||||||
| @AllArgsConstructor | @AllArgsConstructor | ||||||
| public class EmployeeServiceImpl implements EmployeeService { | public class EmployeeServiceImpl implements EmployeeService { | ||||||
|  | 
 | ||||||
|     private EmployeeRepository repository; |     private EmployeeRepository repository; | ||||||
|  |     private final PasswordEncoder passwordEncoder; | ||||||
|  | 
 | ||||||
|     @Override |     @Override | ||||||
|     public void updateLocalTime(Employee employee) { |     public void updateLocalTime(Employee employee) { | ||||||
|         employee.setLastVisit(LocalDateTime.now().toString()); |         employee.setLastVisit(LocalDateTime.now().toString()); | ||||||
| @ -30,6 +34,11 @@ public class EmployeeServiceImpl implements EmployeeService { | |||||||
|         return repository.findEmployeeByUsername(login).orElseThrow(() -> new EmployeeNotFoundException("Employee with username "+login+" not found")); |         return repository.findEmployeeByUsername(login).orElseThrow(() -> new EmployeeNotFoundException("Employee with username "+login+" not found")); | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|  |     public EmployeeDTO findEmployeeDTOByUsername(String login) { | ||||||
|  | 
 | ||||||
|  |         return EmployeeMapper.convertToDTO(repository.findEmployeeByUsername(login).orElseThrow(() -> new EmployeeNotFoundException("Employee with username "+login+" not found"))); | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|     @Override |     @Override | ||||||
|     public EmployeeDTO createEmployee(RegisterDTO dto) { |     public EmployeeDTO createEmployee(RegisterDTO dto) { | ||||||
| 
 | 
 | ||||||
| @ -41,7 +50,10 @@ public class EmployeeServiceImpl implements EmployeeService { | |||||||
|         Employee employee = new Employee(); |         Employee employee = new Employee(); | ||||||
|         employee.setName(dto.getName()); |         employee.setName(dto.getName()); | ||||||
|         employee.setUsername(dto.getUsername()); |         employee.setUsername(dto.getUsername()); | ||||||
|         employee.setPassword(dto.getPassword()); | 
 | ||||||
|  |         // Encoding password | ||||||
|  |         employee.setPassword(passwordEncoder.encode(dto.getPassword())); | ||||||
|  | 
 | ||||||
|         employee.setPhoto(dto.getPhoto()); |         employee.setPhoto(dto.getPhoto()); | ||||||
|         employee.setJobPos(dto.getJobPos()); |         employee.setJobPos(dto.getJobPos()); | ||||||
|         employee.setLastVisit(LocalDateTime.now().toString()); |         employee.setLastVisit(LocalDateTime.now().toString()); | ||||||
|  | |||||||
| @ -1,20 +1,20 @@ | |||||||
| //package com.example.nto.service.impl; | package com.example.nto.service.impl; | ||||||
| // | 
 | ||||||
| //import com.example.nto.repository.EmployeeRepository; | import com.example.nto.repository.EmployeeRepository; | ||||||
| //import lombok.RequiredArgsConstructor; | import lombok.RequiredArgsConstructor; | ||||||
| //import org.springframework.security.core.userdetails.UserDetails; | import org.springframework.security.core.userdetails.UserDetails; | ||||||
| //import org.springframework.security.core.userdetails.UserDetailsService; | import org.springframework.security.core.userdetails.UserDetailsService; | ||||||
| //import org.springframework.security.core.userdetails.UsernameNotFoundException; | import org.springframework.security.core.userdetails.UsernameNotFoundException; | ||||||
| //import org.springframework.stereotype.Service; | import org.springframework.stereotype.Service; | ||||||
| // | 
 | ||||||
| //@Service | @Service | ||||||
| //@RequiredArgsConstructor | @RequiredArgsConstructor | ||||||
| //public class UserDetailsServiceImpl implements UserDetailsService { | public class UserDetailsServiceImpl implements UserDetailsService { | ||||||
| // | 
 | ||||||
| //    private final EmployeeRepository employeeRepository; |     private final EmployeeRepository employeeRepository; | ||||||
| // | 
 | ||||||
| //    @Override |     @Override | ||||||
| //    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException{ |     public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException{ | ||||||
| //        return employeeRepository.findEmployeeByUsername(s).get(); |         return employeeRepository.findEmployeeByUsername(s).get(); | ||||||
| //    } |     } | ||||||
| //} | } | ||||||
|  | |||||||
| @ -9,7 +9,9 @@ spring: | |||||||
|   datasource: |   datasource: | ||||||
|     url: jdbc:postgresql://localhost:5432/testdb |     url: jdbc:postgresql://localhost:5432/testdb | ||||||
|     data: classpath:data.sql |     data: classpath:data.sql | ||||||
|     schema: classpath:schema.sql | 
 | ||||||
|  |     init: | ||||||
|  |       schema-locations: classpath:schema.sql | ||||||
| 
 | 
 | ||||||
|     username: "postgres" |     username: "postgres" | ||||||
|     password: "MobileDev" |     password: "MobileDev" | ||||||
| @ -28,7 +30,7 @@ spring: | |||||||
| 
 | 
 | ||||||
|     hibernate: |     hibernate: | ||||||
|       #ddl-auto: none |       #ddl-auto: none | ||||||
|       ddl-auto: create-drop |       ddl-auto: update | ||||||
| 
 | 
 | ||||||
|     # Показываем запросы |     # Показываем запросы | ||||||
|     show-sql: true |     show-sql: true | ||||||
|  | |||||||
| @ -5,10 +5,11 @@ VALUES | |||||||
| 
 | 
 | ||||||
| INSERT INTO employee (id, username, password, name, photo, job_pos, last_visit) | INSERT INTO employee (id, username, password, name, photo, job_pos, last_visit) | ||||||
| VALUES | VALUES | ||||||
| (1, 'pivanov', 'employee', 'Иванов Петр Федорович', 'https://funnyducks.ru/upload/iblock/0cd/0cdeb7ec3ed6fddda0f90fccee05557d.jpg', 'Разработчик', '2024-02-12T08:30'), | (1, 'pivanov', '$2a$12$oSvuYhIhHJtyw3Gp542S3.WI2aupaIQ5265ItMDvnTPopcLQudx9q', 'Иванов Петр Федорович', 'https://funnyducks.ru/upload/iblock/0cd/0cdeb7ec3ed6fddda0f90fccee05557d.jpg', 'Разработчик', '2024-02-12T08:30'), | ||||||
| (2, 'ipetrov', 'employee', 'Петров Иван Константинович', 'https://funnyducks.ru/upload/iblock/0cd/0cdeb7ec3ed6fddda0f90fccee05557d.jpg', 'Аналитик', '2024-02-13T08:35'), | (2, 'ipetrov', '$2a$12$oSvuYhIhHJtyw3Gp542S3.WI2aupaIQ5265ItMDvnTPopcLQudx9q', 'Петров Иван Константинович', 'https://funnyducks.ru/upload/iblock/0cd/0cdeb7ec3ed6fddda0f90fccee05557d.jpg', 'Аналитик', '2024-02-13T08:35'), | ||||||
| (3, 'asemenov', 'employee', 'Семенов Анатолий Анатольевич', 'https://funnyducks.ru/upload/iblock/0cd/0cdeb7ec3ed6fddda0f90fccee05557d.jpg', 'Разработчик', '2024-02-13T08:31'), | (3, 'asemenov', '$2a$12$oSvuYhIhHJtyw3Gp542S3.WI2aupaIQ5265ItMDvnTPopcLQudx9q', 'Семенов Анатолий Анатольевич', 'https://funnyducks.ru/upload/iblock/0cd/0cdeb7ec3ed6fddda0f90fccee05557d.jpg', 'Разработчик', '2024-02-13T08:31'), | ||||||
| (4, 'afedorov', 'employee', 'Федоров Александр Сергеевич', 'https://funnyducks.ru/upload/iblock/0cd/0cdeb7ec3ed6fddda0f90fccee05557d.jpg', 'Тестировщик', '2024-02-12T08:36'); | (4, 'afedorov', '$2a$12$oSvuYhIhHJtyw3Gp542S3.WI2aupaIQ5265ItMDvnTPopcLQudx9q', 'Федоров Александр Сергеевич', 'https://funnyducks.ru/upload/iblock/0cd/0cdeb7ec3ed6fddda0f90fccee05557d.jpg', 'Тестировщик', '2024-02-12T08:36'), | ||||||
|  | (5, 'gnazarov', '$2a$12$QH3S01HpdzDARg4qrZ4Qee9SkFmxmau2SiEvsSg5M17K2vBBm673O', 'Назаров Г. Н.', 'https://funnyducks.ru/upload/iblock/0cd/0cdeb7ec3ed6fddda0f90fccee05557d.jpg', 'Администратор', '2024-02-12T08:36'); | ||||||
| 
 | 
 | ||||||
| INSERT INTO code (value) | INSERT INTO code (value) | ||||||
| VALUES | VALUES | ||||||
| @ -17,3 +18,11 @@ VALUES | |||||||
| (1122334455667788990), | (1122334455667788990), | ||||||
| (998877665544332211), | (998877665544332211), | ||||||
| (5566778899001122334); | (5566778899001122334); | ||||||
|  | 
 | ||||||
|  | INSERT INTO employee_authorities(employee_id, authorities_id) | ||||||
|  | VALUES | ||||||
|  | (1, 1), | ||||||
|  | (2, 1), | ||||||
|  | (3, 1), | ||||||
|  | (4, 1), | ||||||
|  | (5, 2); | ||||||
|  | |||||||
| @ -2,4 +2,21 @@ CREATE TABLE IF NOT EXISTS authorities( | |||||||
| id auto_increment primary key, authority VARCHAR(255)); | id auto_increment primary key, authority VARCHAR(255)); | ||||||
| 
 | 
 | ||||||
| CREATE TABLE IF NOT EXISTS employee( | CREATE TABLE IF NOT EXISTS employee( | ||||||
| id auto_increment primary key, username VARCHAR(255), password VARCHAR(255), name VARCHAR(255), photo VARCHAR(255), job_pos VARCHAR(255), last_visit VARCHAR(255)); | id auto_increment primary key, | ||||||
|  | username VARCHAR(255), | ||||||
|  | password VARCHAR(255), | ||||||
|  | name VARCHAR(255), | ||||||
|  | photo VARCHAR(255), | ||||||
|  | job_pos VARCHAR(255), | ||||||
|  | last_visit VARCHAR(255) | ||||||
|  | --authorities_id BIGINT NOT NULL, | ||||||
|  | --CONSTRAINT fk_employee_authorities FOREIGN KEY(authorities_id) REFERENCES authorities(id) | ||||||
|  | ); | ||||||
|  | 
 | ||||||
|  | CREATE TABLE IF NOT EXISTS employee_authorities( | ||||||
|  | employee_id BIGINT NOT NULL, | ||||||
|  | authorities_id BIGINT NOT NULL, | ||||||
|  | PRIMARY KEY(employee_id, authorities_id), | ||||||
|  | CONSTRAINT fk_employee_empauth FOREIGN KEY(employee_id) REFERENCES employee(id), | ||||||
|  | CONSTRAINT fk_authorities_empauth FOREIGN KEY(authorities_id) REFERENCES authorities(id) | ||||||
|  | ); | ||||||
		Loading…
	
	
			
			x
			
			
		
	
		Reference in New Issue
	
	Block a user