Java Code Examples for hudson.model.User#getProperty()

The following examples show how to use hudson.model.User#getProperty() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HudsonPrivateSecurityRealmConfiguratorTest.java    From configuration-as-code-plugin with MIT License 6 votes vote down vote up
@Test
    @ConfiguredWithReadme("embedded-userdatabase/README.md#1")
    public void configure_all_attributes() {
        final User admin = User.getById("admin", false);
        assertNotNull(admin);

        assertThat(admin.getFullName(), is("Admin"));
        assertThat(admin.getDescription(), is("Superwoman"));

        SlackUserProperty slackUserProperty = admin
            .getProperty(SlackUserProperty.class);
        assertThat(slackUserProperty.getUserId(), is("ABCDEFGH"));

        UserProperty mailerProperty = admin.getProperty(UserProperty.class);
        assertThat(mailerProperty.getEmailAddress(), is("[email protected]"));

// Pending https://github.com/jenkinsci/ssh-cli-auth-module/pull/16
//        UserPropertyImpl authorizedKeysProperty = admin.getProperty(UserPropertyImpl.class);
//        assertThat(authorizedKeysProperty.authorizedKeys, is("ssh-rsa some-key\n"));
    }
 
Example 2
Source File: UserImpl.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Override
public String getEmail() {
    String name = Jenkins.getAuthentication().getName();
    if(isAnonymous(name)){
        return null;
    }else{
        User user = User.get(name, false, Collections.EMPTY_MAP);
        if(user == null){
            return null;
        }
        if (!user.hasPermission(Jenkins.ADMINISTER)) return null;
    }

    Mailer.UserProperty p = user.getProperty(Mailer.UserProperty.class);
    return p != null ? p.getAddress() : null;
}
 
Example 3
Source File: FavoriteListStatePreloader.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@CheckForNull
@Override
public String getStateJson() {
    User jenkinsUser = User.current();
    if (jenkinsUser == null) {
        return null;
    }
    FavoriteUserProperty fup = jenkinsUser.getProperty(FavoriteUserProperty.class);
    if (fup == null) {
        return null;
    }
    Set<String> favorites = fup.getAllFavorites();
    if (favorites == null) {
        return null;
    }
    return JSONArray.fromObject(favorites).toString();
}
 
Example 4
Source File: HudsonPrivateSecurityRealmConfiguratorTest.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Test
@ConfiguredWithReadme("embedded-userdatabase/README.md#0")
public void configure_local_security_and_admin_user() throws Exception {
    final Jenkins jenkins = Jenkins.get();
    final HudsonPrivateSecurityRealm securityRealm = (HudsonPrivateSecurityRealm) jenkins.getSecurityRealm();
    assertFalse(securityRealm.allowsSignup());
    final User admin = User.getById("admin", false);
    assertNotNull(admin);
    final HudsonPrivateSecurityRealm.Details details = admin.getProperty(HudsonPrivateSecurityRealm.Details.class);
    assertTrue(details.isPasswordCorrect("somethingsecret"));

    final FullControlOnceLoggedInAuthorizationStrategy authorizationStrategy = (FullControlOnceLoggedInAuthorizationStrategy) jenkins.getAuthorizationStrategy();
    assertTrue(authorizationStrategy.isAllowAnonymousRead());
}
 
Example 5
Source File: HudsonPrivateSecurityRealmConfiguratorTest.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Test
@ConfiguredWithReadme("embedded-userdatabase/README.md#1")
public void config_local_security_and_hashed_admin_user() {
    final User admin = User.getById("hashedadmin", false);
    assertNotNull(admin);
    final HudsonPrivateSecurityRealm.Details details = admin.getProperty(HudsonPrivateSecurityRealm.Details.class);
    assertTrue(details.isPasswordCorrect("password"));
}
 
Example 6
Source File: LockableResource.java    From lockable-resources-plugin with MIT License 5 votes vote down vote up
@Exported
public String getReservedByEmail() {
  if (reservedBy != null) {
    UserProperty email = null;
    User user = Jenkins.get().getUser(reservedBy);
    if (user != null) email = user.getProperty(UserProperty.class);
    if (email != null) return email.getAddress();
  }
  return null;
}
 
Example 7
Source File: JwtAuthenticationServiceImpl.java    From blueocean-plugin with MIT License 4 votes vote down vote up
@Override
public JwtToken getToken(@Nullable @QueryParameter("expiryTimeInMins") Integer expiryTimeInMins, @Nullable @QueryParameter("maxExpiryTimeInMins") Integer maxExpiryTimeInMins) {
    long expiryTime= Long.getLong("EXPIRY_TIME_IN_MINS",DEFAULT_EXPIRY_IN_SEC);

    int maxExpiryTime = Integer.getInteger("MAX_EXPIRY_TIME_IN_MINS",DEFAULT_MAX_EXPIRY_TIME_IN_MIN);

    if(maxExpiryTimeInMins != null){
        maxExpiryTime = maxExpiryTimeInMins;
    }
    if(expiryTimeInMins != null){
        if(expiryTimeInMins > maxExpiryTime) {
            throw new ServiceException.BadRequestException(
                String.format("expiryTimeInMins %s can't be greater than %s", expiryTimeInMins, maxExpiryTime));
        }
        expiryTime = expiryTimeInMins * 60;
    }

    Authentication authentication = Jenkins.getAuthentication();

    String userId = authentication.getName();

    User user = User.get(userId, false, Collections.emptyMap());
    String email = null;
    String fullName = null;
    if(user != null) {
        fullName = user.getFullName();
        userId = user.getId();
        Mailer.UserProperty p = user.getProperty(Mailer.UserProperty.class);
        if(p!=null)
            email = p.getAddress();
    }
    Plugin plugin = Jenkins.getInstance().getPlugin("blueocean-jwt");
    String issuer = "blueocean-jwt:"+ ((plugin!=null) ? plugin.getWrapper().getVersion() : "");

    JwtToken jwtToken = new JwtToken();
    jwtToken.claim.put("jti", UUID.randomUUID().toString().replace("-",""));
    jwtToken.claim.put("iss", issuer);
    jwtToken.claim.put("sub", userId);
    jwtToken.claim.put("name", fullName);
    long currentTime = System.currentTimeMillis()/1000;
    jwtToken.claim.put("iat", currentTime);
    jwtToken.claim.put("exp", currentTime+expiryTime);
    jwtToken.claim.put("nbf", currentTime - DEFAULT_NOT_BEFORE_IN_SEC);

    //set claim
    JSONObject context = new JSONObject();

    JSONObject userObject = new JSONObject();
    userObject.put("id", userId);
    userObject.put("fullName", fullName);
    userObject.put("email", email);

    JwtAuthenticationStore authenticationStore = getJwtStore(authentication);

    authenticationStore.store(authentication, context);

    context.put("user", userObject);
    jwtToken.claim.put("context", context);

    return jwtToken;
}
 
Example 8
Source File: GithubScm.java    From blueocean-plugin with MIT License 4 votes vote down vote up
@Override
public HttpResponse validateAndCreate(@JsonBody JSONObject request) {
    String accessToken = (String) request.get("accessToken");
    if(accessToken == null){
        throw new ServiceException.BadRequestException("accessToken is required");
    }

    accessToken = accessToken.trim();

    try {
        User authenticatedUser =  getAuthenticatedUser();

        HttpURLConnection connection = connect(String.format("%s/%s", getUri(), "user"),accessToken);
        validateAccessTokenScopes(connection);
        String data = IOUtils.toString(HttpRequest.getInputStream(connection));
        GHUser user = GithubScm.getMappingObjectReader().forType(GHUser.class).readValue(data);

        if(user.getEmail() != null){
            Mailer.UserProperty p = authenticatedUser.getProperty(Mailer.UserProperty.class);
            //XXX: If there is already email address of this user, should we update it with
            // the one from Github?
            if (p==null){
                authenticatedUser.addProperty(new Mailer.UserProperty(user.getEmail()));
            }
        }

        //Now we know the token is valid. Lets find credential
        String credentialId = createCredentialId(getUri());
        StandardUsernamePasswordCredentials githubCredential = CredentialsUtils.findCredential(credentialId, StandardUsernamePasswordCredentials.class, new BlueOceanDomainRequirement());
        final StandardUsernamePasswordCredentials credential = new UsernamePasswordCredentialsImpl(CredentialsScope.USER, credentialId, getCredentialDescription(), authenticatedUser.getId(), accessToken);

        if(githubCredential == null) {
            CredentialsUtils.createCredentialsInUserStore(
                    credential, authenticatedUser, getCredentialDomainName(),
                    ImmutableList.<DomainSpecification>of(new BlueOceanDomainSpecification()));
        }else{
            CredentialsUtils.updateCredentialsInUserStore(
                    githubCredential, credential, authenticatedUser, getCredentialDomainName(),
                    ImmutableList.<DomainSpecification>of(new BlueOceanDomainSpecification()));
        }

        return createResponse(credential.getId());

    } catch (IOException e) {
        if (e instanceof MalformedURLException || e instanceof UnknownHostException) {
            throw new ServiceException.BadRequestException(
                new ErrorMessage(400, "Invalid apiUrl").add(
                    new ErrorMessage.Error("apiUrl", ErrorMessage.Error.ErrorCodes.INVALID.toString(), e.getMessage())
                )
            );
        }
        throw new ServiceException.UnexpectedErrorException(e.getMessage());
    }
}