Commit 314744c1 authored by Muhammad Suleman's avatar Muhammad Suleman

Added Teacher Registration

parent 1577d277
package com.school.project.controller.other;
import com.school.project.dto.modelDTO.TeacherDTO;
import com.school.project.service.teacher.TeacherServiceImp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.NoSuchElementException;
@RestController
@ComponentScan(basePackages = "com.school.project.service.teacher.TeacherService")
@RequestMapping("/teacher")
public class TeacherController {
@Autowired(required = true)
public TeacherServiceImp teacherServiceImp;
@PostMapping("/save")
public ResponseEntity<TeacherDTO> saveTeacher(@RequestBody TeacherDTO teacherDTO) {
TeacherDTO dto = teacherServiceImp.saveTeacher(teacherDTO);
if (dto == null) {
return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).build();
} else {
return ResponseEntity.status(HttpStatus.OK).body(dto);
}
}
@GetMapping("/findAll")
public ResponseEntity<List<TeacherDTO>> readAllTeachers() {
List<TeacherDTO> teacherDTOS = teacherServiceImp.readAllTeachers();
if (teacherDTOS.size() <= 0) {
return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).build();
} else {
return ResponseEntity.status(HttpStatus.OK).body(teacherDTOS);
}
}
@GetMapping("/find/{id}")
public ResponseEntity<TeacherDTO> readTeacherById(@PathVariable("id") Long id) {
try {
TeacherDTO teacherDTO = teacherServiceImp.readTeacherById(id);
return ResponseEntity.status(HttpStatus.OK).body(teacherDTO);
} catch (NoSuchElementException e) {
return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).build();
}
}
@PutMapping("/update/{id}")
public ResponseEntity<TeacherDTO> updateTeacherById(@RequestBody TeacherDTO teacherDTO, @PathVariable("id") Long id) {
try {
TeacherDTO updateTeacher = teacherServiceImp.updateTeacher(teacherDTO, id);
return ResponseEntity.status(HttpStatus.OK).body(updateTeacher);
} catch (NoSuchElementException e) {
return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).build();
}
}
@DeleteMapping("/delete/{id}")
public ResponseEntity deleteTeacherById(@PathVariable("id") Long id) {
try {
teacherServiceImp.deleteTeacherById(id);
return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
} catch (EmptyResultDataAccessException e) {
return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).build();
}
}
}
......@@ -2,8 +2,11 @@ package com.school.project.controller.registration;
import com.school.project.dto.registrationDTO.StudentRegistrationDTO;
import com.school.project.dto.registrationDTO.TeacherRegistrationDTO;
import com.school.project.dto.registrationDTO.UserDTO;
import com.school.project.service.userRegistration.StudentRegistrationService;
import com.school.project.model.registration.Teacher;
import com.school.project.service.userRegistration.student.StudentRegistrationService;
import com.school.project.service.userRegistration.teacher.TeacherRegistrationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
......@@ -13,8 +16,6 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;
import javax.management.relation.RelationServiceNotRegisteredException;
@RestController
@RequestMapping("/register")
public class RegistrationController {
......@@ -22,16 +23,26 @@ public class RegistrationController {
@Autowired
private StudentRegistrationService studentRegistrationService;
@Autowired
private TeacherRegistrationService teacherRegistrationService;
@PostMapping("/student")
public ResponseEntity<UserDTO> registerStudent(@RequestBody StudentRegistrationDTO student) {
try {
UserDTO userDTO = studentRegistrationService.registerStudent(student);
return ResponseEntity.ok(userDTO);
} catch (Exception e) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Data is not correct", e);
}
}
UserDTO userDTO = studentRegistrationService.registerStudent(student);
return ResponseEntity.ok(userDTO);
@PostMapping("/teacher")
public ResponseEntity<UserDTO> registerTeacher(@RequestBody TeacherRegistrationDTO teacher) {
try {
UserDTO userDTO = teacherRegistrationService.registerTeacher(teacher);
return ResponseEntity.ok(userDTO);
} catch (Exception e) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Data is not correct", e);
}
}
}
package com.school.project.dto.modelDTO;
import com.school.project.model.school.Course;
import com.school.project.model.school.Department;
import lombok.Data;
import java.util.List;
@Data
public class TeacherDTO {
private Long id;
private String name;
private String degree;
private List<Course> courseList;
private Department department;
}
package com.school.project.dto.registrationDTO;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
......
package com.school.project.dto.registrationDTO;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.RequiredArgsConstructor;
@Data
@AllArgsConstructor
@RequiredArgsConstructor
@Builder
public class TeacherRegistrationDTO {
private String email;
private String password;
private String name;
private String teacherNumber;
private String degree;
}
package com.school.project.mapper;
import com.school.project.dto.modelDTO.TeacherDTO;
import com.school.project.model.registration.Teacher;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;
import java.util.List;
@Mapper(componentModel = "spring")
public interface TeacherMapper {
TeacherMapper INSTANCE = Mappers.getMapper(TeacherMapper.class);
TeacherDTO teacherModelToDTo(Teacher teacher);
Teacher teacherDTOToModel(TeacherDTO teacherDTO);
List<TeacherDTO> teacherModelToDTo(List<Teacher> all);
}
......@@ -4,6 +4,7 @@ import com.school.project.model.school.Course;
import com.school.project.model.school.Department;
import com.sun.istack.NotNull;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.codehaus.jackson.annotate.JsonIgnore;
import javax.persistence.*;
......@@ -11,6 +12,7 @@ import java.util.List;
@Data
@Entity
@NoArgsConstructor
@Table(name = "Teacher")
public class Teacher {
......@@ -23,6 +25,10 @@ public class Teacher {
@Column(name = "name")
private String name;
@NotNull
@Column(name = "teacher_num")
private String teacherNumber;
@NotNull
@Column(name = "degree")
private String degree;
......@@ -42,5 +48,10 @@ public class Teacher {
)
private List<Course> courseList;
@OneToOne
@MapsId
@JoinColumn(name = "teacher_id")
private User teacherAppUser;
}
......@@ -35,12 +35,9 @@ public class User {
@PrimaryKeyJoinColumn
private Student studentUser;
// @ElementCollection(fetch = FetchType.EAGER)
// @CollectionTable(
// name = "roles",
// joinColumns = @JoinColumn(name = "user_id")
// )
// @Column(name = "user_role")
// private List<String> roles; StudentReg
@OneToOne(mappedBy = "teacherAppUser", cascade = {CascadeType.MERGE})
@PrimaryKeyJoinColumn
private Teacher teacherUser;
}
package com.school.project.repository.modelRepositery;
package com.school.project.repository.registrationRepositery;
import com.school.project.model.registration.Teacher;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface TeacherRepository extends JpaRepository<Teacher, Long> {
public interface TeacherRegRepository extends JpaRepository<Teacher,Long> {
}
......@@ -8,6 +8,5 @@ import java.util.Optional;
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findUserByEmail(String email);
}
......@@ -18,6 +18,8 @@ import org.springframework.security.oauth2.config.annotation.web.configurers.Aut
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;
import static com.school.project.model.registration.Role.ROLES.STUDENT;
@Configuration
public class OAuth2ServerConfiguration {
......@@ -49,8 +51,8 @@ public class OAuth2ServerConfiguration {
.and()
.authorizeRequests()
.antMatchers("/user/**").permitAll()
.antMatchers("/registerCourse").hasRole("teacher")
.antMatchers("/course/**","/department/**","/student/**","/teacher/**").authenticated();
.antMatchers("/department/**").hasAuthority("STUDENT")
.antMatchers("/course/**", "/student/**", "/teacher/**").hasAuthority("TEACHER");
}
}
......
package com.school.project.security;
import com.school.project.service.userRegistration.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
......@@ -17,7 +18,7 @@ import javax.servlet.http.HttpServletRequest;
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userService;
private UserServiceImpl userService;
@Autowired
BCryptPasswordEncoder encoder;
......
package com.school.project.service.teacher;
import com.school.project.dto.modelDTO.TeacherDTO;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public interface TeacherService {
public TeacherDTO saveTeacher(TeacherDTO teacherDTO);
public List<TeacherDTO> readAllTeachers();
public TeacherDTO readTeacherById(Long id);
public TeacherDTO updateTeacher(TeacherDTO teacherDTO, Long id);
public void deleteTeacherById(Long id);
}
package com.school.project.service.teacher;
import com.school.project.dto.modelDTO.TeacherDTO;
import com.school.project.mapper.TeacherMapper;
import com.school.project.repository.modelRepositery.TeacherRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class TeacherServiceImp implements TeacherService {
@Autowired(required = true)
private TeacherRepository teacherRepository;
@Autowired
private TeacherMapper teacherMapper;
@Override
public TeacherDTO saveTeacher(TeacherDTO teacherDTO) {
return teacherMapper.teacherModelToDTo(
teacherRepository.save(
teacherMapper.teacherDTOToModel(teacherDTO)));
}
@Override
public List<TeacherDTO> readAllTeachers() {
return teacherMapper.teacherModelToDTo(teacherRepository.findAll());
}
@Override
public TeacherDTO readTeacherById(Long id) {
return teacherMapper.teacherModelToDTo(teacherRepository.findById(id).get());
}
@Override
public TeacherDTO updateTeacher(TeacherDTO teacherDTO, Long id) {
TeacherDTO dto = readTeacherById(id);
if (teacherDTO.getName() != null) {
dto.setName(teacherDTO.getName());
}
if (teacherDTO.getDegree() != null) {
dto.setDegree(teacherDTO.getDegree());
}
if (teacherDTO.getCourseList() != null) {
dto.setCourseList(teacherDTO.getCourseList());
}
if (teacherDTO.getDepartment() != null) {
dto.setDepartment(teacherDTO.getDepartment());
}
return saveTeacher(dto);
}
@Override
public void deleteTeacherById(Long id) {
teacherRepository.deleteById(id);
}
}
package com.school.project.service.userRegistration;
import com.school.project.model.registration.User;
public interface UserService {
public Integer saveUser(User user);
}
package com.school.project.service.userRegistration;
import com.school.project.model.registration.Role;
import com.school.project.model.registration.User;
import com.school.project.repository.registrationRepositery.UserRepository;
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.stereotype.Service;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
@Service
public class UserServiceImpl implements UserService, UserDetailsService {
@Override
public Integer saveUser(User user) {
return null;
}
public class UserServiceImpl implements UserDetailsService {
@Autowired
private UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
return null;
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 Not Found");
} else {
User userByEmail = userEmail.get();
Role userByRoles = userByEmail.getRole();
String userSpecifiedRoles = userByRoles.getRole();
Set<GrantedAuthority> userAuthorities = new HashSet<>();
userAuthorities.add(new SimpleGrantedAuthority(userSpecifiedRoles));
springUser = new org.springframework.security.core.userdetails.User(
email,
userByEmail.getPassword(),
userAuthorities);
}
return springUser;
}
//
// @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.userRegistration;
package com.school.project.service.userRegistration.student;
import com.school.project.dto.registrationDTO.StudentRegistrationDTO;
import com.school.project.dto.registrationDTO.UserDTO;
......
package com.school.project.service.userRegistration;
package com.school.project.service.userRegistration.student;
import com.school.project.dto.registrationDTO.StudentRegistrationDTO;
import com.school.project.dto.registrationDTO.UserDTO;
......
package com.school.project.service.userRegistration.teacher;
import com.school.project.dto.registrationDTO.TeacherRegistrationDTO;
import com.school.project.dto.registrationDTO.UserDTO;
public interface TeacherRegistrationService {
public UserDTO registerTeacher(TeacherRegistrationDTO teacherRegistrationDTO);
}
package com.school.project.service.userRegistration.teacher;
import com.school.project.dto.registrationDTO.TeacherRegistrationDTO;
import com.school.project.dto.registrationDTO.UserDTO;
import com.school.project.model.registration.Role;
import com.school.project.model.registration.Teacher;
import com.school.project.model.registration.User;
import com.school.project.repository.registrationRepositery.RoleRepository;
import com.school.project.repository.registrationRepositery.TeacherRegRepository;
import com.school.project.repository.registrationRepositery.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
@Service
public class TeacherRegistrationServiceImpl implements TeacherRegistrationService {
@Autowired
private TeacherRegRepository teacherRegRepository;
@Autowired
private UserRepository userRepository;
@Autowired
private RoleRepository roleRepository;
@Autowired
private PasswordEncoder passwordEncoder;
@Override
@Transactional
public UserDTO registerTeacher(TeacherRegistrationDTO teacherRegistrationDTO) {
User newUser = new User();
newUser.setEmail(teacherRegistrationDTO.getEmail());
newUser.setRole(roleRepository.findByRole(Role.ROLES.TEACHER.name()));
newUser.setPassword(passwordEncoder.encode(teacherRegistrationDTO.getPassword()));
newUser = userRepository.save(newUser);
Teacher newTeacher = new Teacher();
newTeacher.setName(teacherRegistrationDTO.getName());
newTeacher.setDegree(teacherRegistrationDTO.getDegree());
newTeacher.setTeacherNumber(teacherRegistrationDTO.getTeacherNumber());
newTeacher.setTeacherAppUser(newUser);
teacherRegRepository.save(newTeacher);
return new UserDTO(newTeacher.getTeacherId(), newUser.getEmail());
}
}
......@@ -2,12 +2,7 @@
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/school-portal
spring.datasource.username=root
spring.datasource.password=root
#spring.jpa.hibernate.ddl-auto=update
#spring.datasource.url=jdbc:mysql://localhost:3306/schooldataBase
#spring.datasource.username=root
#spring.datasource.password=root
spring.datasource.password=charlie123
spring.security.user.name= sulemantalpur6@gmail.com
spring.security.user.password=charlie
......@@ -15,4 +10,6 @@ spring.security.user.password=charlie
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration
spring.mvc.view.prefix=/static
server.error.include-message=always
\ No newline at end of file
server.error.include-message=always
spring.datasource.data=data.sql
\ 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