Commit b789f1d0 authored by Muhammad Suleman's avatar Muhammad Suleman

Upload Project

parent 24f072f8
No preview for this file type
......@@ -31,3 +31,167 @@ build/
### VS Code ###
.vscode/
# Created by .ignore support plugin (hsz.mobi)
### Gradle template
.gradle
build/
# Ignore Gradle GUI config
gradle-app.setting
# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored)
!gradle-wrapper.jar
### JetBrains template
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm
*.iml
## Directory-based project format:
.idea/
# if you remove the above rule, at least ignore the following:
# User-specific stuff:
# .idea/workspace.xml
# .idea/tasks.xml
# .idea/dictionaries
# Sensitive or high-churn files:
# .idea/dataSources.ids
# .idea/dataSources.xml
# .idea/sqlDataSources.xml
# .idea/dynamic.xml
# .idea/uiDesigner.xml
# Gradle:
# .idea/gradle.xml
# .idea/libraries
# Mongo Explorer plugin:
# .idea/mongoSettings.xml
## File-based project format:
*.ipr
*.iws
## Plugin-specific files:
# IntelliJ
/out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
### Eclipse template
*.pydevproject
.metadata
bin/
tmp/
*.tmp
*.bak
*.swp
*~.nib
local.properties
.settings/
.loadpath
# Eclipse Core
.project
# External tool builders
.externalToolBuilders/
# Locally stored "Eclipse launch configurations"
*.launch
# CDT-specific
.cproject
# JDT-specific (Eclipse Java Development Tools)
.classpath
# PDT-specific
.buildpath
# sbteclipse plugin
.target
# TeXlipse plugin
.texlipse
### Java template
*.class
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.ear
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
### Maven template
target/
pom.xml.tag
pom.xml.releaseBackup
pom.xml.versionsBackup
pom.xml.next
release.properties
dependency-reduced-pom.xml
buildNumber.properties
.mvn/timing.properties
### Grails template
# .gitignore for Grails 1.2 and 1.3
# Although this should work for most versions of grails, it is
# suggested that you use the "grails integrate-with --git" command
# to generate your .gitignore file.
# web application files
/web-app/WEB-INF/classes
# default HSQL database files for production mode
/prodDb.*
# general HSQL database files
*Db.properties
*Db.script
# logs
/stacktrace.log
/test/reports
/logs
# project release file
/*.war
# plugin release files
/*.zip
/plugin.xml
# older plugin install locations
/plugins
/web-app/plugins
# "temporary" build files
/target
......@@ -17,59 +17,104 @@
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>1.4.2.Final</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>1.4.2.Final</version>
<groupId>org.mindrot</groupId>
<artifactId>jbcrypt</artifactId>
<version>0.3m</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>5.7.1</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>5.7.1</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-jwt</artifactId>
<version>1.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>2.0.14.RELEASE</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<source>11</source>
<target>11</target>
<annotationProcessorPaths>
<path>
<groupId>org.mapstruct</groupId>
......
package com.school.project;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@SpringBootApplication
@EnableAutoConfiguration
@SpringBootApplication(exclude = { SecurityAutoConfiguration.class })
@EnableJpaRepositories("com.school.project.*")
@ComponentScan(basePackages = { "com.school.project.*" })
@EntityScan("com.school.project.*")
public class SchoolApplication {
public static void main(String[] args) {
......
package com.school.project.controller;
import com.school.project.model.Course;
import com.school.project.service.CourseService;
import com.school.project.service.interfaces.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
@RestController
@Controller
@RequestMapping()
public class CourseController {
@Autowired(required = true)
public CourseService courseService;
......
package com.school.project.controller;
import com.school.project.dto.DepartmentDTO;
import com.school.project.service.DepartmentService;
import com.school.project.service.implementation.DepartmentServiceImp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Optional;
@RestController
public class DepartmentController {
@Autowired(required=true)
public DepartmentService departmentService;
public DepartmentServiceImp departmentServiceImp;
@PostMapping("/department")
public void saveDepartment(@RequestBody DepartmentDTO departmentDTO){
departmentService.saveDepartment(departmentDTO);
}
@GetMapping("department")
public ResponseEntity<List<DepartmentDTO>> readAllDepartments() {
List<DepartmentDTO> departmentDTO = departmentServiceImp.readDepartment();
@GetMapping("/departments")
public List<DepartmentDTO> readAllDepartments() {
return departmentService.readDepartment();
if(departmentDTO.isEmpty()){
return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
}
else {
return ResponseEntity.of(Optional.of(departmentDTO));
}
}
@GetMapping("department/{id}")
@GetMapping("departmentId/{id}")
public ResponseEntity<DepartmentDTO> readDepartmentById(@PathVariable("id") Long id){
DepartmentDTO departmentDTO=departmentService.readDepartmentById(id);
try {
DepartmentDTO departmentDTO=departmentServiceImp.readDepartmentById(id);
return ResponseEntity.of(Optional.of(departmentDTO));
}catch (NoSuchElementException e){
return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
}
}
@GetMapping("departmentName/{name}")
public ResponseEntity<DepartmentDTO> findDepartmentByName(@PathVariable("name") String name){
DepartmentDTO departmentDTO=departmentServiceImp.findDepartmentByName(name);
if(departmentDTO == null){
return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
......@@ -36,18 +53,44 @@ public class DepartmentController {
}
}
@GetMapping("departmentName/{name}")
public DepartmentDTO findDepartmentByName(@PathVariable("name") String name){
return departmentService.findDepartmentByName(name);
@PostMapping("departmentSave")
public ResponseEntity<DepartmentDTO> saveDepartment(@RequestBody DepartmentDTO department){
DepartmentDTO departmentDTO = departmentServiceImp.saveDepartment(department);
if(departmentDTO == null){
return ResponseEntity.status(HttpStatus.NOT_ACCEPTABLE).build();
}
else {
return ResponseEntity.status(HttpStatus.OK).body(departmentDTO);
}
}
@PutMapping("department/{id}")
public DepartmentDTO updateDepartmentById(@RequestBody DepartmentDTO departmentDTO,@PathVariable("id") Long id){
return departmentService.updateDepartment(departmentDTO,id);
public ResponseEntity<DepartmentDTO> updateDepartmentById(@RequestBody DepartmentDTO department, @PathVariable("id") Long id){
DepartmentDTO checkDepartment = departmentServiceImp.readDepartmentById(id);
if(checkDepartment == null){
return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
}
else {
DepartmentDTO departmentDTO = departmentServiceImp.updateDepartment(department,id);
return ResponseEntity.of(Optional.of(departmentDTO));
}
}
@DeleteMapping("department/{id}")
public void deleteDepartmentById(@PathVariable("id") Long id){
departmentService.deleteDepartmentById(id);
public ResponseEntity<Object> deleteDepartmentById(@PathVariable("id") Long id){
departmentServiceImp.deleteDepartmentById(id);
DepartmentDTO departmentDTO = departmentServiceImp.readDepartmentById(id);
if(departmentDTO == null){
return ResponseEntity.status(HttpStatus.OK).build();
}else {
return ResponseEntity.of(Optional.of("Department Already Not Exist"));
}
}
}
package com.school.project.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class HomeController {
@GetMapping("/home")
public String getHomePage() {
return "hello";
}
@GetMapping("/welcome")
public String getWelcomePage() {
return "welcomPage";
}
@GetMapping("/accessDenied")
public String getAccessDeniedPage() {
return "accessDeniedPage";
}
}
package com.school.project.controller;
import com.school.project.model.Student;
import com.school.project.service.StudentService;
import com.school.project.service.interfaces.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
......
package com.school.project.controller;
import com.school.project.model.Teacher;
import com.school.project.service.TeacherService;
import com.school.project.service.implementation.TeacherServiceImp;
import com.school.project.service.interfaces.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
@RestController
@ComponentScan(basePackages = "com.school.project.service.interfaces.TeacherService")
public class TeacherController {
@Autowired
public TeacherService teacherService;
@Autowired(required = true)
public TeacherServiceImp teacherService;
@PostMapping("/teacher")
public Teacher saveTeacher(@RequestBody Teacher teacher){
......
package com.school.project.controller;
import com.school.project.dto.UserDTO;
import com.school.project.mapper.UserMapper;
import com.school.project.service.implementation.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
@Controller
public class UserController {
@Autowired(required = true)
UserServiceImpl userService;
@Autowired(required = true)
UserMapper userMapper;
@PostMapping("/saveuser")
public String saveUser(@ModelAttribute UserDTO userDTO){
Integer id = userService.saveUser(userMapper.userDtoToUser(userDTO));
String message = "User '"+id+"' saved successfully !";
return message;
}
}
......@@ -6,6 +6,5 @@ import lombok.Data;
public class DepartmentDTO {
private Long id;
private String name;
}
package com.school.project.dto;
import lombok.Data;
import java.util.List;
@Data
public class UserDTO {
private Long id;
private String name;
private String password;
private String email;
private List<String> roles;
}
......@@ -13,17 +13,16 @@ public interface DepartmentMapper {
DepartmentMapper INSTANCE = Mappers.getMapper(DepartmentMapper.class);
/*@Mappings({
@Mapping(target = "departId", source ="department.id"),
@Mapping(target ="departName",source = "department.name")
})*/
DepartmentDTO departmentModelToDTO(Department department);
Department departmentDTOToModel(DepartmentDTO saveDepartment);
List<DepartmentDTO> departmentListModelToDTO(List<Department> all);
/*@Mappings({
@Mapping(target = "id",source = "saveDepartment.departId"),
@Mapping(target ="name",source = "saveDepartment.departName")
})*/
Department departmentDTOToModel(DepartmentDTO saveDepartment);
List<DepartmentDTO> departmentListModelToDTO(List<Department> all);
/*@Mappings({
@Mapping(target = "departId", source ="department.id"),
@Mapping(target ="departName",source = "department.name")
})*/
}
package com.school.project.mapper;
import com.school.project.dto.UserDTO;
import com.school.project.model.User;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;
@Mapper(componentModel = "spring")
public interface UserMapper {
UserMapper INSTANCE = Mappers.getMapper(UserMapper.class);
User userDtoToUser(UserDTO userDTO);
UserDTO userToUserDto(User user);
}
......@@ -13,7 +13,7 @@ public class Department {
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
@Column(name = "name")
@Column(name = "name",unique = true)
private String name;
}
package com.school.project.model;
import lombok.Data;
import org.hibernate.annotations.Fetch;
import javax.persistence.*;
import java.util.List;
@Data
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "user_id")
private Long id;
@Column(name = "username")
private String name;
@Column(name = "user_password")
private String password;
@Column(name = "user_email")
private String email;
@ElementCollection(fetch= FetchType.EAGER)
@CollectionTable(
name = "roles",
joinColumns = @JoinColumn(name = "user_id")
)
@Column(name = "user_role")
private List<String> roles;
}
......@@ -2,6 +2,8 @@ package com.school.project.repository;
import com.school.project.model.Course;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface CourseRepository extends JpaRepository<Course,Long> {
}
......@@ -2,7 +2,9 @@ package com.school.project.repository;
import com.school.project.model.Department;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface DepartmentRepository extends JpaRepository<Department,Long>{
public Department findByName(String departmentName);
}
......@@ -2,8 +2,9 @@ package com.school.project.repository;
import com.school.project.model.Student;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface StudentRepository extends JpaRepository<Student,Long> {
}
......@@ -2,6 +2,8 @@ package com.school.project.repository;
import com.school.project.model.Teacher;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface TeacherRepository extends JpaRepository<Teacher,Long> {
}
package com.school.project.repository;
import com.school.project.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface UserRepository extends JpaRepository<User,Long> {
Optional<User> findUserByEmail(String email);
}
package com.school.project.security.basic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;
@Configuration
public class OAuth2ServerConfiguration {
private static final String SERVER_RESOURCE_ID = "oauth2-server";
private static InMemoryTokenStore tokenStore = new InMemoryTokenStore();
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
@Configuration
@EnableResourceServer
protected static class ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.tokenStore(tokenStore).resourceId(SERVER_RESOURCE_ID);
}
@Override
public void configure(HttpSecurity http) throws Exception {
http
.headers()
.frameOptions()
.disable()
.and()
.authorizeRequests()
.antMatchers("/department").fullyAuthenticated()
.antMatchers("/home").authenticated();
}
}
@Configuration
@EnableAuthorizationServer
protected static class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private PasswordEncoder passwordEncoder;
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints
.authenticationManager(authenticationManager)
.tokenStore(tokenStore);
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients
.inMemory()
.withClient("tacky")
.authorizedGrantTypes("client_credentials", "password", "refresh_token")
.authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT", "refresh_token")
.scopes("read", "write", "trust")
.resourceIds(SERVER_RESOURCE_ID)
.accessTokenValiditySeconds(24 * 60 * 60)
.secret(passwordEncoder.encode("ashdot")).refreshTokenValiditySeconds(0);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security
.checkTokenAccess("isAuthenticated()");
}
}
}
\ No newline at end of file
package com.school.project.security.basic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
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.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.util.matcher.RequestMatcher;
import javax.servlet.http.HttpServletRequest;
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userService;
@Autowired
BCryptPasswordEncoder encoder;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService).passwordEncoder(encoder);
}
public void configure(HttpSecurity http) throws Exception {
http
.requestMatcher(new BasicRequestMatcher())
.authorizeRequests()
.antMatchers("/oauth/token").authenticated()
.and()
.httpBasic()
.and()
.csrf().disable().cors().disable();
}
private static class BasicRequestMatcher implements RequestMatcher {
@Override
public boolean matches(HttpServletRequest request) {
String auth = request.getHeader("Authorization");
return (auth != null && auth.startsWith("Basic"));
}
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
package com.school.project.service;
package com.school.project.service.implementation;
import com.school.project.model.Course;
import com.school.project.repository.CourseRepository;
import com.school.project.service.interfaces.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.persistence.Table;
import javax.transaction.Transactional;
import java.util.List;
import java.util.Optional;
@Service
public class CourseServiceImp implements CourseService{
public class CourseServiceImp implements CourseService {
@Autowired(required = true)
public CourseRepository courseRepository;
......
package com.school.project.service;
package com.school.project.service.implementation;
import com.school.project.dto.DepartmentDTO;
import com.school.project.mapper.DepartmentMapper;
import com.school.project.repository.DepartmentRepository;
import com.school.project.service.interfaces.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class DepartmentServiceImp implements DepartmentService{
public class DepartmentServiceImp implements DepartmentService {
@Autowired(required=true)
private DepartmentRepository departmentRepository;
@Autowired(required = true)
private DepartmentMapper departmentMapper;
@Override
public void saveDepartment(DepartmentDTO departmentDTO) {
departmentRepository.save(departmentMapper.departmentDTOToModel(departmentDTO));
public DepartmentDTO saveDepartment(DepartmentDTO departmentDTO) {
return departmentMapper.departmentModelToDTO(
departmentRepository.save(
departmentMapper.departmentDTOToModel(departmentDTO)));
}
@Override
public List<DepartmentDTO> readDepartment() {
return departmentMapper.departmentListModelToDTO(departmentRepository.findAll());
......@@ -44,6 +49,9 @@ public class DepartmentServiceImp implements DepartmentService{
}
@Override
public DepartmentDTO findDepartmentByName(String departmentName) {
return departmentMapper.departmentModelToDTO(departmentRepository.findByName(departmentName));
}
}
package com.school.project.service;
package com.school.project.service.implementation;
import com.school.project.model.Student;
import com.school.project.repository.StudentRepository;
import com.school.project.service.interfaces.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
......@@ -9,8 +10,7 @@ import java.util.List;
import java.util.Optional;
@Service
public class StudentServiceImp implements StudentService{
public class StudentServiceImp implements StudentService {
@Autowired(required=true)
public StudentRepository studentRepository;
......
package com.school.project.service;
package com.school.project.service.implementation;
import com.school.project.model.Teacher;
import com.school.project.repository.TeacherRepository;
import com.school.project.service.interfaces.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
......@@ -9,7 +10,7 @@ import java.util.List;
import java.util.Optional;
@Service
public class TeacherServiceImp implements TeacherService{
public class TeacherServiceImp implements TeacherService {
@Autowired(required = true)
public TeacherRepository teacherRepository;
......
package com.school.project.service.implementation;
import com.school.project.model.User;
import com.school.project.repository.UserRepository;
import com.school.project.service.interfaces.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
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.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
@Service
public class UserServiceImpl implements UserService, UserDetailsService {
@Autowired
private UserRepository userRepository;
@Autowired
private PasswordEncoder passwordEncoder;
@Override
public Integer saveUser(User user) {
String password = user.getPassword();
String encodedPassword = passwordEncoder.encode(password);
user.setPassword(encodedPassword);
user = userRepository.save(user);
return Math.toIntExact(user.getId());
}
@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
Optional<User> userEmail = userRepository.findUserByEmail(email);
org.springframework.security.core.userdetails.User springUser=null;
if(userEmail.isEmpty()){
throw new UsernameNotFoundException("User With Email=" + email + "Not Founnd");
}else{
User user = userEmail.get();
List<String> userRoles = user.getRoles();
Set<GrantedAuthority> userAuthorities = new HashSet<>();
for (String userRole:userRoles){
userAuthorities.add(new SimpleGrantedAuthority(userRole));
}
springUser = new org.springframework.security.core.userdetails.User(
email,
user.getPassword(),
userAuthorities );
}
return springUser;
}
}
package com.school.project.service;
package com.school.project.service.interfaces;
import com.school.project.model.Course;
......
package com.school.project.service;
package com.school.project.service.interfaces;
import com.school.project.dto.DepartmentDTO;
import java.util.List;
public interface DepartmentService {
public void saveDepartment(DepartmentDTO departmentDTO);
public DepartmentDTO saveDepartment(DepartmentDTO departmentDTO);
public List<DepartmentDTO> readDepartment();
public DepartmentDTO readDepartmentById(Long id);
public DepartmentDTO updateDepartment(DepartmentDTO departmentDTO,Long id);
......
package com.school.project.service;
package com.school.project.service.interfaces;
import com.school.project.model.Student;
......
package com.school.project.service;
package com.school.project.service.interfaces;
import com.school.project.model.Teacher;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public interface TeacherService {
public Teacher saveTeacher(Teacher teacher);
......
package com.school.project.service.interfaces;
import com.school.project.model.User;
import javax.persistence.criteria.CriteriaBuilder;
public interface UserService {
public Integer saveUser(User user);
}
......@@ -2,4 +2,10 @@
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/schoolDataBase
spring.datasource.username=root
spring.datasource.password=charlie123
\ No newline at end of file
spring.datasource.password=charlie123
spring.security.user.name= sulemantalpur6@gmail.com
spring.security.user.password=charlie
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration
spring.mvc.view.prefix=/static
\ No newline at end of file
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h3>You are not allowed to access this page. Please go to Welcome Page</h3>
<a th:href="@{/welcome}" >Welcome</a>
<a th:href="@{/logout}" >LOGOUT</a>
</body>
</html>
\ No newline at end of file
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h3> welcome to the Home Page </h3>
This page is accessible to ALL.
</body>
</html>
\ No newline at end of file
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h3> Welcome Page after successful Login</h3>
<a th:href="@{/logout}" >LOGOUT</a>
</body>
</html>
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment