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

The following examples show how to use hudson.model.User#getId() . 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: GitReadSaveService.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Override
public Object saveContent(@Nonnull StaplerRequest req, @Nonnull Item item) {
    item.checkPermission(Item.CONFIGURE);
    User user = User.current();
    if (user == null) {
        throw new ServiceException.UnauthorizedException("Not authenticated");
    }

    try {
        // parse json...
        JSONObject json = JSONObject.fromObject(IOUtils.toString(req.getReader()));
        GitReadSaveRequest r = makeSaveRequest(item, json);
        r.save();
        return new GitFile(
            new GitContent(r.filePath, user.getId(), r.gitSource.getRemote(), r.filePath, 0, "sha", null, "", r.branch, r.sourceBranch, true, "")
        );
    } catch (IOException e) {
        throw new ServiceException.UnexpectedErrorException("Unable to save file content", e);
    }
}
 
Example 2
Source File: UserImpl.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Override
public BlueFavoriteContainer getFavorites() {

    /*
     * Get the user id using authenticated user. User.current() returns authenticated user using security realm and
     * associated IdStrategy to get a consistent id.
     *
     * @see IdStrategy#keyFor(String)
     * @see IdStrategy.CaseInsensitive#keyFor(String)
     *
     */
    User u = User.current();
    String expectedUserId = u != null ? u.getId(): Jenkins.ANONYMOUS.getName();

    if(!user.getId().equals(expectedUserId)) {
        throw new ForbiddenException("This user '" + expectedUserId + "' cannot access resource owned by '" + user.getId() + "'");
    }
    return new FavoriteContainerImpl(this, this);
}
 
Example 3
Source File: UserSSHKeyManager.java    From blueocean-plugin with MIT License 5 votes vote down vote up
/**
 * Gets the existing generated SSH key for the user or creates one and
 * returns it in the user's credential store
 * @param user owner of the key
 * @return the user's personal private key
 */
public static @Nonnull BasicSSHUserPrivateKey getOrCreate(@Nonnull User user) {
    Preconditions.checkNotNull(user);

    CredentialsStore store = getUserStore(user);
    if(store == null){
        throw new ServiceException.ForbiddenException(String.format("Logged in user: %s doesn't have writable credentials store", user.getId()));
    }
    // try to find the right key
    for (Credentials cred : store.getCredentials(getDomain(store))) {
        if (cred instanceof BasicSSHUserPrivateKey) {
            BasicSSHUserPrivateKey sshKey = (BasicSSHUserPrivateKey)cred;
            if (BLUEOCEAN_GENERATED_SSH_KEY_ID.equals(sshKey.getId())) {
                return sshKey;
            }
        }
    }
    // if none found, create one
    try {
        // create one!
        String privateKey = SSHKeyUtils.generateKey(KEY_SIZE).trim();
        BasicSSHUserPrivateKey.DirectEntryPrivateKeySource keySource = new BasicSSHUserPrivateKey.DirectEntryPrivateKeySource(privateKey);
        BasicSSHUserPrivateKey key = new BasicSSHUserPrivateKey(CredentialsScope.USER, BLUEOCEAN_GENERATED_SSH_KEY_ID, user.getId(), keySource, null, BLUEOCEAN_GENERATED_SSH_KEY_ID);
        store.addCredentials(getDomain(store), key);
        store.save();
        return key;
    } catch (IOException ex) {
        throw new ServiceException.UnexpectedErrorException("Failed to create the private key", ex);
    }
}
 
Example 4
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 5
Source File: AbstractAnalytics.java    From blueocean-plugin with MIT License 4 votes vote down vote up
protected final String identity(String server) {
    User user = User.current();
    String username = user == null ? "ANONYMOUS" : user.getId();
    return Hashing.sha256().hashString( username + server, Charset.defaultCharset()).toString();
}
 
Example 6
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());
    }
}
 
Example 7
Source File: OicUserProperty.java    From oic-auth-plugin with MIT License 4 votes vote down vote up
@Override
public UserProperty newInstance(User user) {
	LOGGER.fine("OicUserPropertyDescriptor.newInstance called, user:" + user);
	return new OicUserProperty(user.getId(), new GrantedAuthority[0]);
}