Mini Project Spring Boot Project
Mini Project Spring Boot Project
java
package com.example.project.controller;
import com.example.project.Model.ApplicationUser;
import com.example.project.security.JwtUtil;
import com.example.project.service.ApplicationUserService;
import com.example.project.service.UserAuthService;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import
org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;
@RestController
public class ApplicationUserController {
@Autowired
private ApplicationUserService applicationUserService;
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private JwtUtil jwtUtil;
@Autowired
private UserAuthService userAuthService;
@PostMapping("/register")
public String registerUser(@RequestBody ApplicationUser applicationUser) {
ApplicationUser user =
this.applicationUserService.createUser(applicationUser);
if (user != null) {
return "Registration successful";
}
return "Password or username policy failed";
}
@PostMapping("/signin")
public ResponseEntity<ApiResponse> signin(@RequestBody JwtAuthRequest request)
throws Exception {
System.out.println("USERNAME:"+request.getUsername());
this.authenticate(request.getUsername(), request.getPassword());
UserDetails
userDetails=this.userAuthService.loadUserByUsername(request.getUsername());
System.out.println("USERDetails:"+userDetails);
String token=this.jwtUtil.generateToken(userDetails);
if (token!=null){
ApplicationUser
user=applicationUserService.findUserByUsername(request.getUsername());
return new ResponseEntity<ApiResponse>(
new ApiResponse("Authentication
successful",token,user.getUser_name())
,HttpStatus.OK);
}
else{
return new ResponseEntity<ApiResponse>(new ApiResponse("Username or Password is
incorrect"),HttpStatus.CONFLICT);
}
}
@GetMapping("/viewprofile/{userId}")
public ApplicationUser getUserDetails(@PathVariable("userId") String user_name)
{
return this.applicationUserService.fetchApplicationUser(user_name);
}
@PutMapping("/editprofile/{userId}")
public ApplicationUser updateUser(@PathVariable("userId") String
user_name,@RequestBody ApplicationUser user){
return this.applicationUserService.editUser(user,user_name);
}
}
}
}
@Data
class ApiResponse{
private String message;
private String token;
private String userId;
02. AppointmentController.java
package com.example.project.controller;
import com.example.project.Model.Appointment;
import com.example.project.service.AppointmentService;
import com.example.project.service.PatientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/appointment")
public class AppointmentController {
@Autowired
private AppointmentService appointmentService;
@Autowired
private PatientService patientService;
@PostMapping("/register")
public String registerAppointment(@RequestBody Appointment appointment) {
if (this.appointmentService.checkPatient(appointment.getPatientId())) {
this.appointmentService.addAppointment(appointment);
return "Booking successful";
} else {
return "Booking failure";
}
}
@GetMapping("/list")
public List<Appointment> getAllAppointments(){
return this.appointmentService.getAllAppointments();
}
@GetMapping("/view/{appointmentId}")
public Appointment getAppointment(@PathVariable("appointmentId") String
appointmentId){
return this.appointmentService.findAppointmentById(appointmentId);
}
@GetMapping("/list/{patientId}")
public List<Appointment> getAppointmentsByPatientId(@PathVariable("patientId")
String patientId){
return this.appointmentService.findAppointmentsByPatientId(patientId);
}
@DeleteMapping("/{appointmentId}")
public void deleteAppointment(@PathVariable("appointmentId") String
appointmentId){
this.appointmentService.deleteAppointment(appointmentId);
}
}
03. PatientController.java
package com.example.project.controller;
import com.example.project.Model.Patient;
import com.example.project.service.PatientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/patients")
public class PatientController {
@Autowired
private PatientService patientService;
@PostMapping("/register")
public String registerPatient(@RequestBody Patient patient) {
@GetMapping("/list")
public List<Patient> getPatientsList() {
return this.patientService.fetchPatients();
}
@GetMapping("/view/{Id}")
public Patient getPatientDetails(@PathVariable("Id") String patientId) {
return this.patientService.fetchPatient(patientId);
}
@DeleteMapping("/delete/{Id}")
public void deletePatient(@PathVariable("Id") String patient_Id) {
this.patientService.deletePatient(patient_Id);
}
}
04. ApplicationUser.java
package com.example.project.Model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import javax.persistence.Entity;
import javax.persistence.Id;
import java.util.Collection;
@Data
@Entity
@AllArgsConstructor
@NoArgsConstructor
public class ApplicationUser implements UserDetails {
@Id
public String user_name;
public String user_email;
public String password;
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return null;
}
@Override
public String getUsername() {
return this.user_name;
}
@Override
public String getPassword() {
return this.password;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}
05. Appointment.java
package com.example.project.Model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import java.util.Date;
@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Appointment {
@Id
@GeneratedValue(generator = "system-uuid")
@GenericGenerator(name="system-uuid",strategy = "uuid")
private String booking_id;
06. Patient.java
package com.example.project.Model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import java.util.Date;
@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Patient {
@Id
@GeneratedValue(generator = "system-uuid")
@GenericGenerator(name="system-uuid",strategy = "uuid")
private String patient_Id;
}
07. ApplicationUserRepository.java
package com.example.project.repository;
import com.example.project.Model.ApplicationUser;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import java.util.Optional;
08. AppointmentRepository.java
package com.example.project.repository;
import com.example.project.Model.Appointment;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
09. PatientRepository.java
package com.example.project.repository;
import com.example.project.Model.Patient;
import org.springframework.data.jpa.repository.JpaRepository;
package com.example.project.security;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class ApiAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException,
ServletException {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED,"Access Denied");
}
}
11. ApiSecurityConfig.java
package com.example.project.security;
import com.example.project.service.UserAuthService;
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.Authenticati
onManagerBuilder;
import
org.springframework.security.config.annotation.method.configuration.EnableGlobalMet
hodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import
org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import
org.springframework.security.config.annotation.web.configuration.WebSecurityConfigu
rerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import
org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilte
r;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class ApiSecurityConfig extends WebSecurityConfigurerAdapter {
"/register",
"/h2-console/*",
"/signin"
};
@Autowired
private UserAuthService userAuthService;
@Autowired
private ApiAuthenticationEntryPoint apiAuthenticationEntryPoint;
@Autowired
private JwtAuthenticationFilter jwtAuthenticationFilter;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf()
.disable()
.authorizeRequests()
.antMatchers(PUBLIC_URLS).permitAll()
.anyRequest()
.authenticated()
.and()
.exceptionHandling().authenticationEntryPoint(this.apiAuthenticatio
nEntryPoint)
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.addFilterBefore(this.jwtAuthenticationFilter,
UsernamePasswordAuthenticationFilter.class);
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(this.userAuthService).passwordEncoder(passwordEncoder());
@Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
12. JwtAuthenticationFilter.java
package com.example.project.security;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import org.springframework.beans.factory.annotation.Autowired;
import
org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import
org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private JwtUtil jwtUtil;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
response, FilterChain filterChain)
throws ServletException, IOException {
// get token
String requestToken = request.getHeader("Authorization");
try {
username = this.jwtUtil.getUsernameFromToken(token);
} catch (IllegalArgumentException e) {
System.out.println("Unable to get JWT token");
} catch (ExpiredJwtException e) {
System.out.println("Jwt tokn has expired");
} catch (MalformedJwtException e) {
System.out.println("Invalid JWT token");
}
} else {
System.out.println("JWT Token doesn't begin with bearer");
}
UserDetails userDetails =
this.userDetailsService.loadUserByUsername(username);
if (this.jwtUtil.validateToken(token, userDetails)) {
UsernamePasswordAuthenticationToken
usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
userDetails, null, userDetails.getAuthorities());
usernamePasswordAuthenticationToken
.setDetails(new
WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthentication
Token);
} else {
System.out.println("Invalid token");
}
} else {
System.out.println("Username is null or contect is not null");
}
filterChain.doFilter(request, response);
}
}
13. JwtUtil.java
package com.example.project.security;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
@Component
public class JwtUtil {
@Value("${jwt.token.validity}")
public void setJwtExpirationInMs(int jwtExpirationInMs) {
this.jwtExpirationInMs = jwtExpirationInMs;
}
@Value("${jwt.secret}")
public void setSecret(String secret) {
this.secret = secret;
}
// for retrieving any information from token we will need the secret key
private Claims getAllClaimsFromToken(String token) {
return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
}
return Jwts.builder().setClaims(claims).setSubject(subject).setIssuedAt(new
Date(System.currentTimeMillis()))
.setExpiration(new Date(System.currentTimeMillis()
+jwtExpirationInMs ))
.signWith(SignatureAlgorithm.HS512, secret).compact();
}
// ValidateToken
public boolean validateToken(String token, UserDetails userDetails) {
final String username = getUsernameFromToken(token);
return (username.equals(userDetails.getUsername()) && !
isTokenExpired(token));
}
14. ApplicationUserService.java
package com.example.project.service;
import com.example.project.Model.ApplicationUser;
import com.example.project.repository.ApplicationUserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
@Service
public class ApplicationUserService {
@Autowired
private ApplicationUserRepository userRepository;
@Autowired
private PasswordEncoder passwordEncoder;
applicationUser.setPassword(this.passwordEncoder.encode(applicationUser.getPassword
()));
return userRepository.save(applicationUser);
}
15. AppointmentService.java
package com.example.project.service;
import com.example.project.Model.Appointment;
import com.example.project.Model.Patient;
import com.example.project.repository.AppointmentRepository;
import com.example.project.repository.PatientRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Optional;
@Service
public class AppointmentService {
@Autowired
private AppointmentRepository appointmentRepository;
@Autowired
private PatientService patientService;
@Autowired
private PatientRepository patientrepository;
return appointmentRepository.findAll();
}
16. PatientService.java
package com.example.project.service;
import com.example.project.Model.Patient;
import com.example.project.repository.PatientRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class PatientService {
@Autowired
private PatientRepository patientrepository;
public Patient registerPatient(Patient patient) {
return patientrepository.save(patient);
}
17. UserAuthService.java
package com.example.project.service;
import com.example.project.Model.ApplicationUser;
import com.example.project.repository.ApplicationUserRepository;
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;
@Service
public class UserAuthService implements UserDetailsService {
@Autowired
private ApplicationUserRepository userRepo;
@Override
public UserDetails loadUserByUsername(String username) throws
UsernameNotFoundException {
ApplicationUser user = this.userRepo.findByUser_name(username)
.orElseThrow(() -> new UsernameNotFoundException("Username not
found"));
return user;
}
}
12. ApplicationUserRepository.java
package com.example.project.repository;
import com.example.project.Model.ApplicationUser;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import java.util.Optional;