private Object readResolve() { return getById(id, false); } }
/** * Gets the fallback "unknown" user instance. * <p> * This is used to avoid null {@link User} instance. */ public static @Nonnull User getUnknown() { return getById(UNKNOWN_USERNAME, true); }
public User getUser() { return userId == null ? User.getUnknown() : User.getById(userId, true) ; }
/** * Gets the {@link User} object representing the supplied {@link Authentication} or * {@code null} if the supplied {@link Authentication} is either anonymous or {@code null} * * @param a the supplied {@link Authentication} . * @return a {@link User} object for the supplied {@link Authentication} or {@code null} * @since 1.609 */ public static @CheckForNull User get(@CheckForNull Authentication a) { if (a == null || a instanceof AnonymousAuthenticationToken) return null; // Since we already know this is a name, we can just call getOrCreateById with the name directly. return getById(a.getName(), true); }
@Restricted(DoNotUse.class) // for Jelly @CheckForNull public String getUserUrl() { final User user = userId == null ? null : User.getById(userId, false); return user != null ? user.getUrl() : null; }
@Exported(visibility = 3) public String getUserName() { final User user = userId == null ? null : User.getById(userId, false); return user == null ? "anonymous" : user.getDisplayName(); }
/** * This is to map users under the security realm URL. * This in turn helps us set up the right navigation breadcrumb. */ @Restricted(NoExternalUse.class) public User getUser(String id) { return User.getById(id, User.ALLOW_USER_CREATION_VIA_URL && hasPermission(Jenkins.ADMINISTER)); }
/** * Gets user display name when possible. * @return User display name. * If the User does not exist, returns its ID. */ @Exported(visibility=3) public String getUserName() { final User user = User.getById(authenticationName, false); return user != null ? user.getDisplayName() : authenticationName; }
@Override public Details loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException { User u = User.getById(username, false); Details p = u!=null ? u.getProperty(Details.class) : null; if(p==null) throw new UsernameNotFoundException("Password is not set: "+username); if(p.getUser()==null) throw new AssertionError(); return p; }
@Override public void print(TaskListener listener) { User user = getUserId() == null ? null : User.getById(getUserId(), false); if (user != null) { listener.getLogger().println(Messages.Cause_UserIdCause_ShortDescription( ModelHyperlinkNote.encodeTo(user))); } else { listener.getLogger().println(Messages.Cause_UserIdCause_ShortDescription( "unknown or anonymous")); } }
@Override public String resolveCanonicalId(String idOrFullName, Map<String, ?> context) { User existing = getById(idOrFullName, false); if (existing != null) { return existing.getId(); } if (SECURITY_243_FULL_DEFENSE) { if (!resolving.get()) { resolving.set(true); try { UserDetails userDetails = UserDetailsCache.get().loadUserByUsername(idOrFullName); return userDetails.getUsername(); } catch (UsernameNotFoundException x) { LOGGER.log(Level.FINE, "not sure whether " + idOrFullName + " is a valid username or not", x); } catch (DataAccessException | ExecutionException x) { LOGGER.log(Level.FINE, "could not look up " + idOrFullName, x); } finally { resolving.set(false); } } } return null; }
protected UserDetails attemptToImpersonate(String username, RuntimeException e) { // this backend cannot tell if the user name exists or not. so substitute by what we know User u = User.getById(username, false); if (u!=null) { LastGrantedAuthoritiesProperty p = u.getProperty(LastGrantedAuthoritiesProperty.class); if (p!=null) return new org.acegisecurity.userdetails.User(username,"",true,true,true,true, p.getAuthorities()); } throw e; } }
@Override protected void loggedIn(@Nonnull String username) { try { // user should have been created but may not have been saved for some realms // but as this is a callback of a successful login we can safely create the user. User u = User.getById(username, true); LastGrantedAuthoritiesProperty o = u.getProperty(LastGrantedAuthoritiesProperty.class); if (o==null) u.addProperty(o=new LastGrantedAuthoritiesProperty()); Authentication a = Jenkins.getAuthentication(); if (a!=null && a.getName().equals(username)) o.update(a); // just for defensive sanity checking } catch (IOException e) { LOGGER.log(Level.WARNING, "Failed to record granted authorities",e); } }
@Override protected void onSuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, Authentication authResult) throws IOException { super.onSuccessfulAuthentication(request,response,authResult); // make sure we have a session to store this successful authentication, given that we no longer // let HttpSessionContextIntegrationFilter2 to create sessions. // HttpSessionContextIntegrationFilter stores the updated SecurityContext object into this session later // (either when a redirect is issued, via its HttpResponseWrapper, or when the execution returns to its // doFilter method. request.getSession().invalidate(); HttpSession newSession = request.getSession(); if (!UserSeedProperty.DISABLE_USER_SEED) { User user = User.getById(authResult.getName(), true); UserSeedProperty userSeed = user.getProperty(UserSeedProperty.class); String sessionSeed = userSeed.getSeed(); newSession.setAttribute(UserSeedProperty.USER_SESSION_SEED, sessionSeed); } // as the request comes from Acegi redirect, that's not a Stapler one // thus it's not possible to retrieve it in the SecurityListener in that case // for that reason we need to keep the above code that apply quite the same logic as UserSeedSecurityListener SecurityListener.fireLoggedIn(authResult.getName()); }
/** * Creates a new user account by registering a password to the user. */ public User createAccount(String userName, String password) throws IOException { User user = User.getById(userName, true); user.addProperty(Details.fromPlainPassword(password)); SecurityListener.fireUserCreated(user.getId()); return user; }
/** * Creates a new user account by registering a JBCrypt Hashed password with the user. * * @param userName The user's name * @param hashedPassword A hashed password, must begin with <code>#jbcrypt:</code> */ public User createAccountWithHashedPassword(String userName, String hashedPassword) throws IOException { if (!PASSWORD_ENCODER.isPasswordHashed(hashedPassword)) { throw new IllegalArgumentException("this method should only be called with a pre-hashed password"); } User user = User.getById(userName, true); user.addProperty(Details.fromHashedPassword(hashedPassword)); SecurityListener.fireUserCreated(user.getId()); return user; }
public static @CheckForNull User isConnectingUsingApiToken(String username, String tokenValue){ User user = User.getById(username, false); if(user == null){ ApiTokenPropertyConfiguration apiTokenConfiguration = GlobalConfiguration.all().getInstance(ApiTokenPropertyConfiguration.class); if(apiTokenConfiguration.isTokenGenerationOnCreationEnabled()){ String generatedTokenOnCreation = Util.getDigestOf(ApiTokenProperty.API_KEY_SEED.mac(username)); boolean areTokenEqual = MessageDigest.isEqual( generatedTokenOnCreation.getBytes(StandardCharsets.US_ASCII), tokenValue.getBytes(StandardCharsets.US_ASCII) ); if(areTokenEqual){ // directly return the user freshly created // and no need to check its token as the generated token // will be the same as the one we checked just above return User.getById(username, true); } } }else{ ApiTokenProperty t = user.getProperty(ApiTokenProperty.class); if (t!=null && t.matchesPassword(tokenValue)) { return user; } } return null; } }
private void putUserSeedInSession(String username) { StaplerRequest req = Stapler.getCurrentRequest(); if (req == null) { // expected case: CLI // But also HudsonPrivateSecurityRealm because of a redirect from Acegi, the request is not a Stapler one return; } HttpSession session = req.getSession(false); if (session == null) { // expected case: CLI through CLIRegisterer return; } if (!UserSeedProperty.DISABLE_USER_SEED) { User user = User.getById(username, true); UserSeedProperty userSeed = user.getProperty(UserSeedProperty.class); if (userSeed == null) { // if you want to filter out the user seed property, you should consider using the DISABLE_USER_SEED instead return; } String sessionSeed = userSeed.getSeed(); // normally invalidated before session.setAttribute(UserSeedProperty.USER_SESSION_SEED, sessionSeed); } } }
@Override protected String makeTokenSignature(long tokenExpiryTime, UserDetails userDetails) { String userSeed; if (UserSeedProperty.DISABLE_USER_SEED) { userSeed = "no-seed"; } else { User user = User.getById(userDetails.getUsername(), false); if (user == null) { return "no-user"; } UserSeedProperty userSeedProperty = user.getProperty(UserSeedProperty.class); if (userSeedProperty == null) { // if you want to filter out the user seed property, you should consider using the DISABLE_USER_SEED instead return "no-prop"; } userSeed = userSeedProperty.getSeed(); } String token = String.join(":", userDetails.getUsername(), Long.toString(tokenExpiryTime), userSeed, getKey()); return MAC.mac(token); }
@RequirePOST public HttpResponse doRevokeAllSelected(@JsonBody RevokeAllSelectedModel content) throws IOException { for (RevokeAllSelectedUserAndUuid value : content.values) { if (value.userId == null) { // special case not managed by JSONObject value.userId = "null"; } User user = User.getById(value.userId, false); if (user == null) { LOGGER.log(Level.INFO, "User not found id={0}", value.userId); } else { ApiTokenProperty apiTokenProperty = user.getProperty(ApiTokenProperty.class); if (apiTokenProperty == null) { LOGGER.log(Level.INFO, "User without apiTokenProperty found id={0}", value.userId); } else { ApiTokenStore.HashedToken revokedToken = apiTokenProperty.getTokenStore().revokeToken(value.uuid); if (revokedToken == null) { LOGGER.log(Level.INFO, "User without selected token id={0}, tokenUuid={1}", new Object[]{value.userId, value.uuid}); } else { apiTokenProperty.deleteApiToken(); user.save(); LOGGER.log(Level.INFO, "Revocation success for user id={0}, tokenUuid={1}", new Object[]{value.userId, value.uuid}); } } } } return HttpResponses.ok(); }