Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

import com.itgura.authservice.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
Expand All @@ -13,6 +14,7 @@
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.client.RestTemplate;

@Configuration
@RequiredArgsConstructor
Expand Down Expand Up @@ -41,4 +43,9 @@ public AuthenticationManager authenticationManager(AuthenticationConfiguration c
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}

@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,13 @@ public AppResponse<AuthenticationResponse> register(@RequestBody RegisterRequest
try {
AuthenticationResponse res = authenticationService.register(registerRequest);
return AppResponse.ok(res);
}catch(IllegalArgumentException e ){
return AppResponse.error(null,"Illegal Arguments","500","500",e.getMessage());
}catch(ApplicationException e){
return AppResponse.error(null,"Application Exception","500","500",e.getMessage());

} catch (Exception e) {
return AppResponse.error(null, "Server Error", "500", "", e.getMessage());
return AppResponse.error(null, "Server Error", "500", "500", e.getMessage());
}

}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,6 @@ public interface UserRepository extends JpaRepository<User, UUID> {

Optional<User> findByEmail(String email);
Optional<User> findByRole(Role role);

boolean existsByEmail(String email);
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,36 +7,50 @@
import com.itgura.authservice.entity.Role;
import com.itgura.authservice.entity.User;
import com.itgura.authservice.repository.UserRepository;
import com.itgura.dto.AppResponse;
import com.itgura.exception.ApplicationException;
import com.itgura.exception.ValueNotExistException;
import com.itgura.util.UserUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import jakarta.validation.Valid;

import lombok.RequiredArgsConstructor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Optional;
import java.util.*;

@Service
@RequiredArgsConstructor
public class AuthenticationService {

@Value("${jwt.secretKey}")
private String SECRET_KEY;

@Autowired
private RestTemplate restTemplate;

private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
private final JwtService jwtService;
private final AuthenticationManager authenticationManager;
public AuthenticationResponse register(RegisterRequest registerRequest) {

@Transactional(rollbackFor = ApplicationException.class)
public AuthenticationResponse register(RegisterRequest registerRequest) throws IllegalArgumentException, ApplicationException {
if(isExistingUser(registerRequest.getEmail())){
throw new IllegalArgumentException("The email is already in use in another account, try logging instead");
}
var user = User.builder()
.firstName(registerRequest.getFirstName())
.lastName(registerRequest.getLastName())
Expand All @@ -45,14 +59,74 @@ public AuthenticationResponse register(RegisterRequest registerRequest) {
.role(Role.STUDENT)
.build();
userRepository.save(user);

var jwtToken = jwtService.generateToken(user);
var refreshToken = jwtService.generateRefresh(new HashMap<>(),user);
try {
createAccountInResourceService(user.getEmail(), user.getFirstName(), user.getLastName(), user.getId(),jwtToken);
} catch (Exception e) {

throw new ApplicationException("Failed to create account in resource service: " + e.getMessage());
}
return AuthenticationResponse.builder()
.authenticationToken(jwtToken)
.refreshToken(refreshToken)
.build();
}

private void createAccountInResourceService(String email, String firstName, String lastName, UUID id, String jwtToken) throws ApplicationException {
String url = "http://lms-gateway/resource-management/user-details";
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Bearer " + jwtToken);


// Prepare the request body with only the necessary fields
// Create a map for the request body
Map<String, Object> requestBody = new HashMap<>();
requestBody.put("registration_number", 0);
requestBody.put("first_name", firstName);
requestBody.put("last_name", lastName);
requestBody.put("user_id", id);
requestBody.put("email", email);
requestBody.put("mobile_number", null);
requestBody.put("examination_year", 0);
requestBody.put("gender", null);
requestBody.put("school", null);
requestBody.put("stream_id", null);
requestBody.put("address", null);

// Create the HttpEntity with headers and body
HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);

try {
ResponseEntity<AppResponse> responseEntity = restTemplate.exchange(url, HttpMethod.POST, entity, AppResponse.class);
AppResponse response = responseEntity.getBody();
System.out.println(response);

if (response == null || response.getData() == null) {
throw new ApplicationException("Error while creating account in resource account");
}

System.out.println("Account Created Successfully");



} catch (HttpClientErrorException.Forbidden e) {
throw new ApplicationException("Access is forbidden: " + e.getMessage());
} catch (HttpClientErrorException e) {
throw new ApplicationException("Client error: " + e.getStatusCode() + " " + e.getMessage());
} catch (Exception e) {
throw new ApplicationException("Server error: " + e.getMessage());
}


}

private boolean isExistingUser(String email) {
return userRepository.existsByEmail(email);

}

public AuthenticationResponse authenticate(AuthenticationRequest authenticationRequest) {
authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(authenticationRequest.getEmail(), authenticationRequest.getPassword())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ public String generateToken(
.setSubject(userDetails.getUsername())
.claim("roles", userDetails.getAuthorities())
.setIssuedAt(new Date(System.currentTimeMillis()))
.setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 24)) // 1 day
.setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 24)) // 1 day
.signWith(getSignInKey(), SignatureAlgorithm.HS256)
.compact();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,22 +15,39 @@ public class UserDaoImpl implements UserDao {
@PersistenceContext
private EntityManager entityManager;
public UserResponseDto getUserDetailByEmail(String email) throws CredentialNotFoundException {
try{
try {
StringBuilder sql = new StringBuilder();
sql.append("select u.id, u.role, concat(u.first_name,' ',u.last_name) as username from auth_service._user as u where u.email like :email");
java.util.List<Object[]> resultList ;
sql.append("select u.id, u.role, concat(u.first_name,' ',u.last_name) as username ")
.append("from auth_service._user as u where u.email like :email");

// Create and configure the query
Query nativeQuery = entityManager.createNativeQuery(sql.toString());
nativeQuery.setParameter("email",email).getResultList();
resultList = nativeQuery.getResultList();
nativeQuery.setParameter("email", email);
System.out.println("Executing query: " + sql.toString());

// Execute the query and fetch the result list
java.util.List<Object[]> resultList = nativeQuery.getResultList();

if (resultList.isEmpty()) {
throw new CredentialNotFoundException("No user found with the provided email");
}

// Map the result to the DTO
UserResponseDto response = new UserResponseDto();
response.setUserId((UUID) resultList.get(0)[0]);
response.setUserRoles((String) resultList.get(0)[1]);
response.setName((String) resultList.get(0)[2]);
return response;

} catch (Exception e) {
throw new CredentialNotFoundException("User not found");


} catch (Exception ex) {
System.out.println(ex);
throw new RuntimeException("Error occurred while fetching user details", ex);
}
}




}
Original file line number Diff line number Diff line change
@@ -1,12 +1,20 @@
package com.itgura.repository;


import com.itgura.entity.Student;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.stereotype.Repository;

import java.util.Optional;
import java.util.UUID;
@Repository
@EnableJpaRepositories
public interface StudentRepository extends JpaRepository<Student, UUID> {
Optional<Student> findByUserId(UUID userId);
}


@Query("SELECT MAX(s.registration_number) FROM Student s")
Integer findMaxRegistrationNumber();
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
package com.itgura.request;

import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Email;
Expand All @@ -8,42 +9,59 @@
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.UUID;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class UserDetailRequest {

@NotNull(message = "Registration number is required")
@JsonProperty("registration_number")
private Integer registrationNumber;

@NotNull(message = "User Id is required")
@JsonProperty("user_id")
private UUID userID;

@NotBlank(message = "First name is required")
@JsonProperty("first_name")
private String firstName;

@NotBlank(message = "Last name is required")
@JsonProperty("last_name")
private String lastName;

@Email(message = "Invalid email format")
@NotBlank(message = "Email is required")
@JsonProperty("email")
private String email;
@NotBlank(message = "Mobile number is required")

// @NotBlank(message = "Mobile number is required")
@JsonProperty("mobile_number")
private String mobileNumber;
@NotNull(message = "Examination year is required")

// @NotNull(message = "Examination year is required")
@JsonProperty("examination_year")
private Integer examinationYear;
@NotBlank(message = "Gender is required")

// @NotBlank(message = "Gender is required")
@JsonProperty("gender")
private String gender;
@NotBlank(message = "School is required")

// @NotBlank(message = "School is required")
@JsonProperty("school")
private String school;
@NotNull(message = "Stream ID is required")

// @NotNull(message = "Stream ID is required")
@JsonProperty("stream_id")
private UUID stream;

@Valid
@NotNull(message = "Address is required")
// @NotNull(message = "Address is required")
@JsonProperty("address")
private AddressRequest address;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
import lombok.NoArgsConstructor;

import java.util.UUID;

@Data
@AllArgsConstructor
@NoArgsConstructor
Expand All @@ -19,34 +18,49 @@ public class UserDetailsResponse {
private UUID userId;
@JsonProperty("registration_number")
private Integer registration_number;

@JsonProperty("first_name")
private String firstName;

@JsonProperty("last_name")
private String lastName;

@JsonProperty("email")
private String email;

@JsonProperty("mobile_number")
private String mobileNumber;

@JsonProperty("examination_year")
private Integer examinYear;

@JsonProperty("gender")
private String gender;

@JsonProperty("school")
private String school;
@JsonProperty("stream_id")
private UUID stream;

@JsonProperty("stream")
private String address;
private String stream;

@JsonProperty("stream_id")
private UUID streamId;


@JsonProperty("address_id")
private UUID addressId;

@JsonProperty("house_name_or_number")
private String houseNameOrNumber;

@JsonProperty("line1")
private String line1;

@JsonProperty("line2")
private String line2;

@JsonProperty("city")
private String city;
@JsonProperty("user_roles")
private String userRoles;
}
}
Loading