From 40949f59684075ebf1024f7d50a8960007e36791 Mon Sep 17 00:00:00 2001 From: Bogdan Kostov Date: Wed, 11 Sep 2024 14:23:55 +0200 Subject: [PATCH] Fix fetching user reference for change metadata - avoid exception when fetching user by username --- .../service/security/SecurityUtils.java | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/src/main/java/cz/cvut/kbss/analysis/service/security/SecurityUtils.java b/src/main/java/cz/cvut/kbss/analysis/service/security/SecurityUtils.java index f39db61..51b5b79 100755 --- a/src/main/java/cz/cvut/kbss/analysis/service/security/SecurityUtils.java +++ b/src/main/java/cz/cvut/kbss/analysis/service/security/SecurityUtils.java @@ -38,7 +38,7 @@ public SecurityUtils(UserDao userDao, SecurityConf config) { * If the user is impersonating another user, the impersonated user is returned. * Otherwise, the currently authenticated user is returned. * - * @return + * @return the instance of the User class representing the currently authenticated user */ public User getCurrentUser() { final SecurityContext context = SecurityContextHolder.getContext(); @@ -53,9 +53,21 @@ public User getCurrentUser() { } } + public String getCurrentUsername(){ + final SecurityContext context = SecurityContextHolder.getContext(); + assert context != null; + final Object principal = context.getAuthentication().getPrincipal(); + if (principal instanceof Jwt) { + final OidcUserInfo userInfo = new OidcUserInfo(((Jwt)principal).getClaims()); + return userInfo.getPreferredUsername(); + } else { + return context.getAuthentication().getName(); + } + } + public UserReference getCurrentUserReference() { - User user = getCurrentUser(); - return new UserReference(user); + String username = getCurrentUsername(); + return userDao.findUserReferenceByUsername(username); } // TODO map role, but I am not sure which changes in the model when be required if I add addRole method to User