Skip to content

Commit

Permalink
Database connection works
Browse files Browse the repository at this point in the history
  • Loading branch information
BrendanAndrews committed Dec 2, 2024
1 parent 7ea4180 commit ac01608
Show file tree
Hide file tree
Showing 8 changed files with 172 additions and 30 deletions.
5 changes: 4 additions & 1 deletion software/plugins/alert-messenger/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,11 @@ dependencies {
implementation 'io.quarkus:quarkus-qute'
implementation 'io.quarkus:quarkus-mailer'
implementation 'io.quarkus:quarkus-hibernate-orm-panache'
implementation 'io.quarkus:quarkus-jdbc-postgresql'

implementation 'jakarta.persistence:jakarta.persistence-api:3.1.0'



// Add Quarkus REST Client dependency
implementation 'io.quarkus:quarkus-rest-client'

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import io.quarkus.qute.Location;
import io.quarkus.qute.Template;
import io.quarkus.security.identity.SecurityIdentity;
import jakarta.annotation.security.PermitAll;
import jakarta.annotation.security.RolesAllowed;
import jakarta.enterprise.context.RequestScoped;
Expand All @@ -11,8 +12,20 @@
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.transaction.Transactional;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import tech.ebp.oqm.plugin.alertMessenger.repositories.UserRepository;
import tech.ebp.oqm.plugin.alertMessenger.model.UserInfo;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import io.quarkus.hibernate.orm.panache.PanacheRepository;

import java.util.Set;
import java.util.UUID;

import org.eclipse.microprofile.jwt.JsonWebToken;
import org.eclipse.microprofile.openapi.annotations.tags.Tag;
import org.eclipse.microprofile.openapi.annotations.tags.Tags;

Expand All @@ -28,11 +41,61 @@ public class Home extends UiInterface {
@Location("webui/pages/index")
Template pageTemplate;

// EVERYTHING BELOW THIS HAS JUST BEEN ADDED BY CHATGPT
@Inject
JsonWebToken jwt; // Extracts claims from the JWT

@Inject
UserRepository userRepository; // Repository for database operations

@Inject
SecurityIdentity identity; // Provides user and role info

@GET
@RolesAllowed("inventoryView")
@Produces(MediaType.TEXT_HTML)
@Transactional // Ensures a transaction is active
public Response index() {
log.info("Got index page");

// Extract user details from the JWT
String idString = jwt.getClaim("sub"); // Extract the ID as a string
UUID id;
try {
id = UUID.fromString(idString); // Convert String to UUID
} catch (IllegalArgumentException e) {
log.error("Invalid UUID format in 'sub' claim: {}", idString);
return Response.status(Response.Status.BAD_REQUEST).entity("Invalid user ID format").build();
}

String name = jwt.getClaim("name");
String username = jwt.getClaim("preferred_username");
String email = jwt.getClaim("email");
Set<String> roles = identity.getRoles(); // Retrieves user roles

// Ensure the user is saved or updated in the database
UserInfo existingUser = userRepository.findById(id); // Find by unique ID
if (existingUser == null) {
log.info("New user detected, saving to database: {}", username);
UserInfo newUser = UserInfo.builder()
.id(id)
.name(name)
.username(username)
.email(email)
.roles(roles)
.build();
userRepository.persist(newUser); // Save new user
} else {
log.info("Existing user found: {}, updating details", username);
existingUser.setName(name);
existingUser.setUsername(username);
existingUser.setEmail(email);
existingUser.setRoles(roles);
userRepository.merge(existingUser); // Merge the detached entity
}

// Render the UI page

return Response.ok(
this.setupPageTemplate(this.pageTemplate)
).build();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,18 +1,51 @@
package tech.ebp.oqm.plugin.alertMessenger.model;

import lombok.AllArgsConstructor;
/*import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import lombok.NoArgsConstructor;*/
import java.util.Set;
import java.util.UUID;

import jakarta.persistence.*;
import lombok.*;

@Entity
@Table(name = "users")
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
public class UserInfo {
@Id
private UUID id;

private String name;

private String username;

@Data
private String email;

@ElementCollection
private Set<String> roles;

// Custom method to match the expected getUserId() in your other code
public String getUserId() {
return id.toString();
}
}

/*@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Entity // Makes this class a database entity
@Table(name = "users")
public class UserInfo {
@Id // This field acts as the primary key
private String id;
private String name;
private String username;
private String email;
Expand All @@ -22,4 +55,4 @@ public class UserInfo {
public String getUserId() {
return id;
}
}
}*/
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package tech.ebp.oqm.plugin.alertMessenger.repositories;

public @interface Query {

}
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,38 @@

import io.quarkus.hibernate.orm.panache.PanacheRepository;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.persistence.EntityManager;
import tech.ebp.oqm.plugin.alertMessenger.model.UserInfo;
import java.util.UUID;

@ApplicationScoped
public class UserRepository implements PanacheRepository<UserInfo> {

public UserInfo findByUserId(String userId) {
return find("userId", userId).firstResult();
/**
* Find a user by their unique ID.
*
* @param id the unique user ID
* @return the UserInfo object, or null if not found
*/
public UserInfo findById(UUID id) {
return find("id", id).firstResult();
}

/**
* Find a user by their email.
*
* @param email the user's email address
* @return the UserInfo object, or null if not found
*/
public UserInfo findByEmail(String email) {
return find("email", email).firstResult();
}

@Inject
EntityManager entityManager; // Inject EntityManager for persistence operations

public UserInfo merge(UserInfo userInfo) {
return entityManager.merge(userInfo); // Use EntityManager to merge detached entities
}
}
Original file line number Diff line number Diff line change
@@ -1,36 +1,41 @@
package tech.ebp.oqm.plugin.alertMessenger.utils;

import java.util.UUID;
import org.eclipse.microprofile.jwt.Claims;
import org.eclipse.microprofile.jwt.JsonWebToken;
import tech.ebp.oqm.plugin.alertMessenger.model.UserInfo;

import java.util.Set;

public class JwtUtils {
public static String getId(JsonWebToken jwt){
return jwt.getClaim(Claims.sub);

public static UUID getId(JsonWebToken jwt) {
return UUID.fromString(jwt.getClaim(Claims.sub));
}
public static String getName(JsonWebToken jwt){

public static String getName(JsonWebToken jwt) {
return jwt.getClaim("name");
}
public static String getEmail(JsonWebToken jwt){

public static String getEmail(JsonWebToken jwt) {
return jwt.getClaim(Claims.email);
}
public static String getUserName(JsonWebToken jwt){

public static String getUserName(JsonWebToken jwt) {
return jwt.getClaim(Claims.preferred_username);
}
public static Set<String> getRoles(JsonWebToken jwt){

public static Set<String> getRoles(JsonWebToken jwt) {
return jwt.getGroups();
}
public static UserInfo getUserInfo(JsonWebToken jwt){

public static UserInfo getUserInfo(JsonWebToken jwt) {
return UserInfo.builder()
.id(getId(jwt))
.name(getName(jwt))
.username(getUserName(jwt))
.email(getEmail(jwt))
.roles(getRoles(jwt))
.build();
.id(getId(jwt))
.name(getName(jwt))
.username(getUserName(jwt))
.email(getEmail(jwt))
.roles(getRoles(jwt))
.build();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

import java.util.Optional;
import java.util.Set;
import java.util.UUID;

@ApplicationScoped
@Slf4j
Expand All @@ -22,8 +23,8 @@ public class UserUtils {
* @param userId the unique user ID
* @return UserInfo object if found, Optional.empty otherwise
*/
public Optional<UserInfo> getUserInfo(String userId) {
return Optional.ofNullable(userRepository.findByUserId(userId));
public Optional<UserInfo> getUserInfo(UUID userId) {
return Optional.ofNullable(userRepository.findById(userId));
}

/**
Expand All @@ -32,7 +33,7 @@ public Optional<UserInfo> getUserInfo(String userId) {
* @param userId the unique user ID
* @return the user ID, or null if the user is not found
*/
public String getId(String userId) {
public String getId(UUID userId) {
return getUserInfo(userId)
.map(UserInfo::getUserId)
.orElse(null);
Expand All @@ -44,7 +45,7 @@ public String getId(String userId) {
* @param userId the unique user ID
* @return the user's name, or null if the user is not found
*/
public String getName(String userId) {
public String getName(UUID userId) {
return getUserInfo(userId)
.map(UserInfo::getName)
.orElse(null);
Expand All @@ -56,7 +57,7 @@ public String getName(String userId) {
* @param userId the unique user ID
* @return the user's email, or null if the user is not found
*/
public String getEmail(String userId) {
public String getEmail(UUID userId) {
return getUserInfo(userId)
.map(UserInfo::getEmail)
.orElse(null);
Expand All @@ -68,7 +69,7 @@ public String getEmail(String userId) {
* @param userId the unique user ID
* @return the user's username, or null if the user is not found
*/
public String getUserName(String userId) {
public String getUserName(UUID userId) {
return getUserInfo(userId)
.map(UserInfo::getUsername)
.orElse(null);
Expand All @@ -80,7 +81,7 @@ public String getUserName(String userId) {
* @param userId the unique user ID
* @return a set of roles, or null if the user is not found
*/
public Set<String> getRoles(String userId) {
public Set<String> getRoles(UUID userId) {
return getUserInfo(userId)
.map(UserInfo::getRoles)
.orElse(null);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,16 @@ quarkus:
username: "[email protected]"
password: "${SMTP_PASSWORD}"
mock: false
# Database configuration below (for user credentials).
datasource:
db-kind: postgresql
jdbc:
url: jdbc:postgresql://localhost:5432/oqm_db
username: Brendan
password: Password123
hibernate-orm:
database:
generation: update

mp:
messaging:
Expand Down

0 comments on commit ac01608

Please sign in to comment.