use of hudson.model.User in project blueocean-plugin by jenkinsci.
the class JwtImplTest method getToken.
@Test
public void getToken() throws Exception {
j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
User user = j.jenkins.getUser("alice");
user.setFullName("Alice Cooper");
user.addProperty(new Mailer.UserProperty("alice@jenkins-ci.org"));
JenkinsRule.WebClient webClient = j.createWebClient();
webClient.login("alice");
Page page = webClient.goTo("jwt-auth/token/", null);
String token = page.getWebResponse().getResponseHeaderValue("X-BLUEOCEAN-JWT");
Assert.assertNotNull(token);
JsonWebStructure jsonWebStructure = JsonWebStructure.fromCompactSerialization(token);
Assert.assertTrue(jsonWebStructure instanceof JsonWebSignature);
JsonWebSignature jsw = (JsonWebSignature) jsonWebStructure;
System.out.println(token);
System.out.println(jsw.toString());
String kid = jsw.getHeader("kid");
Assert.assertNotNull(kid);
page = webClient.goTo("jwt-auth/jwks/" + kid + "/", "application/json");
// for(NameValuePair valuePair: page.getWebResponse().getResponseHeaders()){
// System.out.println(valuePair);
// }
JSONObject jsonObject = JSONObject.fromObject(page.getWebResponse().getContentAsString());
System.out.println(jsonObject.toString());
RsaJsonWebKey rsaJsonWebKey = new RsaJsonWebKey(jsonObject, null);
JwtConsumer jwtConsumer = new JwtConsumerBuilder().setRequireExpirationTime().setAllowedClockSkewInSeconds(// allow some leeway in validating time based claims to account for clock skew
30).setRequireSubject().setVerificationKey(// verify the sign with the public key
rsaJsonWebKey.getKey()).build();
JwtClaims claims = jwtConsumer.processToClaims(token);
Assert.assertEquals("alice", claims.getSubject());
Map<String, Object> claimMap = claims.getClaimsMap();
Map<String, Object> context = (Map<String, Object>) claimMap.get("context");
Map<String, String> userContext = (Map<String, String>) context.get("user");
Assert.assertEquals("alice", userContext.get("id"));
Assert.assertEquals("Alice Cooper", userContext.get("fullName"));
Assert.assertEquals("alice@jenkins-ci.org", userContext.get("email"));
}
use of hudson.model.User in project blueocean-plugin by jenkinsci.
the class GithubScm method getOrganizations.
@Override
public Container<ScmOrganization> getOrganizations() {
StaplerRequest request = Stapler.getCurrentRequest();
String credentialId = getCredentialIdFromRequest(request);
User authenticatedUser = getAuthenticatedUser();
final StandardUsernamePasswordCredentials credential = CredentialsUtils.findCredential(credentialId, StandardUsernamePasswordCredentials.class, new BlueOceanDomainRequirement());
if (credential == null) {
throw new ServiceException.BadRequestExpception(String.format("Credential id: %s not found for user %s", credentialId, authenticatedUser.getId()));
}
String accessToken = credential.getPassword().getPlainText();
try {
GitHub github = new GitHubBuilder().withOAuthToken(accessToken).withRateLimitHandler(new RateLimitHandlerImpl()).withEndpoint(getUri()).build();
final Link link = getLink().rel("organizations");
// preserve the same order that github org api returns
Map<String, ScmOrganization> orgMap = new LinkedHashMap<>();
for (Map.Entry<String, GHOrganization> entry : github.getMyOrganizations().entrySet()) {
orgMap.put(entry.getKey(), new GithubOrganization(GithubScm.this, entry.getValue(), credential, link));
}
GHMyself user = github.getMyself();
if (orgMap.get(user.getLogin()) == null) {
//this is to take care of case if/when github starts reporting user login as org later on
orgMap = new HashMap<>(orgMap);
orgMap.put(user.getLogin(), new GithubUserOrganization(user, credential, this));
}
final Map<String, ScmOrganization> orgs = orgMap;
return new Container<ScmOrganization>() {
@Override
public ScmOrganization get(String name) {
ScmOrganization org = orgs.get(name);
if (org == null) {
throw new ServiceException.NotFoundException(String.format("GitHub organization %s not found", name));
}
return org;
}
@Override
public Link getLink() {
return link;
}
@Override
public Iterator<ScmOrganization> iterator() {
return orgs.values().iterator();
}
};
} catch (IOException e) {
if (e instanceof HttpException) {
HttpException ex = (HttpException) e;
if (ex.getResponseCode() == 401) {
throw new ServiceException.PreconditionRequired("Invalid Github accessToken", ex);
} else if (ex.getResponseCode() == 403) {
throw new ServiceException.PreconditionRequired("Github accessToken does not have required scopes. Expected scopes 'user:email, repo'", ex);
}
}
throw new ServiceException.UnexpectedErrorException(e.getMessage(), e);
}
}
use of hudson.model.User in project blueocean-plugin by jenkinsci.
the class GitPipelineCreateRequest method create.
@Override
public BluePipeline create(Reachable parent) throws IOException {
User authenticatedUser = User.current();
if (authenticatedUser == null) {
throw new ServiceException.UnauthorizedException("Must login to create a pipeline");
}
String sourceUri = scmConfig.getUri();
if (sourceUri == null) {
throw new ServiceException.BadRequestExpception(new ErrorMessage(400, "Failed to create Git pipeline:" + getName()).add(new ErrorMessage.Error("scmConfig.uri", ErrorMessage.Error.ErrorCodes.MISSING.toString(), "uri is required")));
}
TopLevelItem item = create(Jenkins.getInstance(), getName(), MODE, MultiBranchProjectDescriptor.class);
if (item instanceof WorkflowMultiBranchProject) {
WorkflowMultiBranchProject project = (WorkflowMultiBranchProject) item;
if (StringUtils.isNotBlank(scmConfig.getCredentialId())) {
Domain domain = CredentialsUtils.findDomain(scmConfig.getCredentialId(), authenticatedUser);
if (domain == null) {
throw new ServiceException.BadRequestExpception(new ErrorMessage(400, "Failed to create pipeline").add(new ErrorMessage.Error("scm.credentialId", ErrorMessage.Error.ErrorCodes.INVALID.toString(), "No domain in user credentials found for credentialId: " + scmConfig.getCredentialId())));
}
if (domain.test(new BlueOceanDomainRequirement())) {
//this is blueocean specific domain
project.addProperty(new BlueOceanCredentialsProvider.FolderPropertyImpl(authenticatedUser.getId(), scmConfig.getCredentialId(), BlueOceanCredentialsProvider.createDomain(sourceUri)));
}
}
String credentialId = StringUtils.defaultString(scmConfig.getCredentialId());
project.getSourcesList().add(new BranchSource(new GitSCMSource(null, sourceUri, credentialId, "*", "", false)));
project.scheduleBuild(new Cause.UserIdCause());
return new MultiBranchPipelineImpl(project);
} else {
try {
// we don't know about this project type
item.delete();
} catch (InterruptedException e) {
throw new ServiceException.UnexpectedErrorException("Failed to delete pipeline: " + getName());
}
}
return null;
}
use of hudson.model.User in project blueocean-plugin by jenkinsci.
the class FavoritesStatePreloader method getFetchData.
@Override
protected FetchData getFetchData(@Nonnull BlueUrlTokenizer blueUrl) {
User jenkinsUser = User.current();
if (jenkinsUser != null) {
UserImpl blueUser = new UserImpl(jenkinsUser);
BlueFavoriteContainer favoritesContainer = blueUser.getFavorites();
if (favoritesContainer != null) {
JSONArray favorites = new JSONArray();
Iterator<BlueFavorite> favoritesIterator = favoritesContainer.iterator();
while (favoritesIterator.hasNext()) {
Reachable favorite = favoritesIterator.next();
try {
favorites.add(JSONObject.fromObject(ModelObjectSerializer.toJson(favorite)));
} catch (IOException e) {
LOGGER.log(Level.FINE, String.format("Unable to preload favorites for User '%s'. Serialization error.", jenkinsUser.getFullName()), e);
return null;
}
}
return new FetchData(favoritesContainer.getLink().getHref(), favorites.toString());
}
}
// Don't preload any data on the page.
return null;
}
use of hudson.model.User in project blueocean-plugin by jenkinsci.
the class CredentialApi method create.
@POST
@WebMethod(name = "")
public CreateResponse create(@JsonBody JSONObject body, StaplerRequest request) throws IOException {
User authenticatedUser = User.current();
if (authenticatedUser == null) {
throw new ServiceException.UnauthorizedException("No authenticated user found");
}
JSONObject jsonObject = body.getJSONObject("credentials");
final IdCredentials credentials = request.bindJSON(IdCredentials.class, jsonObject);
String domainName = DOMAIN_NAME;
if (jsonObject.get("domain") != null && jsonObject.get("domain") instanceof String) {
domainName = (String) jsonObject.get("domain");
}
CredentialsUtils.createCredentialsInUserStore(credentials, authenticatedUser, domainName, ImmutableList.<DomainSpecification>of(new BlueOceanDomainSpecification()));
CredentialsStoreAction.DomainWrapper domainWrapper = credentialStoreAction.getDomain(domainName);
if (domainWrapper != null) {
return new CreateResponse(new CredentialApi.Credential(domainWrapper.getCredential(credentials.getId()), getLink().rel("domains").rel(domainName).rel("credentials")));
}
//this should never happen
throw new ServiceException.UnexpectedErrorException("Unexpected error, failed to create credential");
}
Aggregations