How to map the Groovy script to Nexus script API and pass the Argument in JSON - grails

I have a script which will add the nexus role to the LDAP user.
import org.sonatype.nexus.security.role.RoleIdentifier;
import org.sonatype.nexus.security.user.User;
import org.sonatype.nexus.security.user.UserManager;
String userId = 'NA12345';
String newRoleId = 'dot-maven'
String realm = 'LDAP'
String role_realm = 'default'
User user = security.securitySystem.getUser(userId, realm)
authManager = security.getSecuritySystem().getAuthorizationManager(UserManager.DEFAULT_SOURCE)
def existingRole = authManager.getRole(newRoleId)
if(user != null) {
RoleIdentifier newRole = new RoleIdentifier(role_realm, existingRole.roleId);
user.addRole(newRole)
security.securitySystem.setUsersRoles(user.getUserId(), realm, user.getRoles());
} else {
log.warn("No user with ID of $userId found.")
}
Now I need to add this script in the NExus Script API and pass the username and role id as argrument in JSON format.
How can i achieve this?

Related

Can't pass password from credentialsJSON to commitStatusPublisher (bitbucket server) Teamcity

It seems that i have an old version of commitStatusPublisher plugin and it can't convert credentialsJSON string to its value. In any other situation I can access password with
params.findRawParam("env.mypass")!!.value
or in buildstep, script content
$mypass
But commitStatusPublisher not working with it.
Code example
import jetbrains.buildServer.configs.kotlin.v2019_2.*
import jetbrains.buildServer.configs.kotlin.v2019_2.buildFeatures.commitStatusPublisher
params {
password("env.mypass", "credentialsJSON:8420d5dc-1d32-4f9e-a74d-c9444be05c23", display = ParameterDisplay.HIDDEN)
}
features {
commitStatusPublisher {
publisher = bitbucketServer {
url = "https://bitbucket.domain.com/"
userName = "user"
password = params.findRawParam("env.mypass")!!.value
}
}
}
Maybe I can somehow extract 'raw' var to use it for that plugin?
for example
var pass = something("env.mypass")
features {
commitStatusPublisher {
publisher = bitbucketServer {
url = "https://bitbucket.domain.com/"
userName = "user"
password = pass
}
}
}
In the result i want to keep password in TC tokens and use it with my version of commitStatusPublisher
Seems like a bug.
Recreating the token resolves problem

How to update credentials of specific folder in Jenkins using Groovy script?

I want to update a credentials object of an existing folder. How can I do that using groovy?
Here is what I have so far:
import com.cloudbees.plugins.credentials.CredentialsProvider;
import com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials;
import com.cloudbees.hudson.plugins.folder.Folder
import com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl
// Init
String user_name = "my_user_name"
String user_pass = "my_new_pass"
String folderName = "Projects"
Folder targetFolder = null
// Get folder:
def allJenkinsItems = Jenkins.getInstance().getItems();
for (currentJenkinsItem in allJenkinsItems)
{
if(!(currentJenkinsItem instanceof Folder)) {continue}
if(((Folder)currentJenkinsItem).getFullName().equals(folderName))
{
targetFolder = (Folder)currentJenkinsItem;
}
}
if (targetFolder == null) {println "Failed to find folder: folderName"; return}
// Get target credentials of that folder:
def credsList = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(
com.cloudbees.plugins.credentials.common.StandardUsernameCredentials.class,
targetFolder,
null,
null
);
// Get target creds out of the list - will get the first one it encounters:
def targetCreds = credsList.findResult { it.username == user_name ? it : null }
if (targetCreds == null) {println "Failed to find username: $user_name under credentials of folder: $folderName"; return}
// Gets store - how to get the folder's store??
def credentials_store = Jenkins.instance.getExtensionList(
'com.cloudbees.plugins.credentials.SystemCredentialsProvider'
)[0].getStore()
// Try to update the creds of the folder.
// **updateResult is always 'false' here**
def updateResult = credentials_store.updateCredentials(
com.cloudbees.plugins.credentials.domains.Domain.global(),
targetCreds,
new UsernamePasswordCredentialsImpl(targetCreds.scope, targetCreds.id, targetCreds.description, targetCreds.username, user_pass)
)
if (updateResult) {
println "Success changing password for ${user_name}"
} else {
println "Failed changing password for ${user_name}"
}
But when I am trying to update - I get a updateResult == false.
How can I update the credentials after they are found?
Found it myself:
/*
* Configures single (username & password) credentials for a folder in global domain
* if already exists a credentials with defined username - it will update it
* if more than one exists - the first one it encounters will be updated
*/
import java.util.logging.Logger
import jenkins.model.*
import com.cloudbees.hudson.plugins.folder.*;
import com.cloudbees.hudson.plugins.folder.properties.*;
import com.cloudbees.hudson.plugins.folder.properties.FolderCredentialsProvider.FolderCredentialsProperty;
import com.cloudbees.plugins.credentials.impl.*;
import com.cloudbees.plugins.credentials.*;
import com.cloudbees.plugins.credentials.domains.*;
// Init
def logger = Logger.getLogger("")
jenkins = Jenkins.instance
String user_name = "my_user_name"
String user_pass = "my_new_pass"
String description = "my desc"
String folderName = "Projects"
String id = java.util.UUID.randomUUID().toString()
Credentials c = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, id, "description: "+id, user_name, user_pass)
logger.info("Configuring domain credentials for folder: $folderName")
for (folder in jenkins.getAllItems(Folder.class)) {
if(folder.name.equals(folderName)) {
AbstractFolder<?> folderAbs = AbstractFolder.class.cast(folder)
FolderCredentialsProperty property = folderAbs.getProperties().get(FolderCredentialsProperty.class)
// If not defined FolderCredentialsProperty yet - define and finish
if(property == null) {
logger.info("Initializing folder credentials store and add credentials in global store")
property = new FolderCredentialsProperty([c])
folderAbs.addProperty(property)
jenkins.save()
return
}
// Check for existing credentials - and update their password & description
// will update the first credentials it encounters
def credentials_store = property.getStore()
List<com.cloudbees.plugins.credentials.Credentials> folderCredentialsList = property.getCredentials()
for (creds in folderCredentialsList) {
logger.info("Checking existing credentials of folder: $folderName for user: $user_name")
if (creds.username.equals(user_name)) {
// Found username - updating it
// Try to update the creds of the folder:
def updateResult = credentials_store.updateCredentials(
com.cloudbees.plugins.credentials.domains.Domain.global(),
creds,
new UsernamePasswordCredentialsImpl(creds.scope, creds.id, description, creds.username, user_pass)
)
if (updateResult) {
println "Update successful"
} else {
println "Update failed"
}
jenkins.save()
return
}
}
logger.info("Didn't find credntials with username: $user_name - adding new one")
// If got here - then:
// 1. There is already a FolderCredentials property defined for folder: folderName
// 2. didn't find any credentials(of username & password type) with username == user_name
// so just add the new credentials
property.getStore().addCredentials(Domain.global(), c)
jenkins.save()
return
}
}

How to make the input paramter option in Swagger while calling Rest Endpoint

I already went through: How to define an optional parameter in path using swagger.
I've this endpoint:
#ApiOperation(value = "Retrieve Student Data By firstName Or lastName Or middleName",nickname = "Find Student Data")
#ApiResponses(value = { #ApiResponse(code = 200, message = "Successfully Retrieved Student Data"),
#ApiResponse(code = 404, message = "No data found !!!") })
#GetMapping(path = "/firstName/{firstName}/lastName/{lastName}/middleName/{middleName}")
public GetStudentDataResponse getStudentData(#PathVariable(required = false) String firstName, #PathVariable(required = false) String lastName,#PathVariable(required = false) String middleName) {
return service.getStudentData(firstName,lastName,middleName);
}
When I hit the rest endpoint and pass firstName only, Swagger is complaining about required parameter. How can we disabled it ?
Note: I really don't want to create another endpoint just to create / for the sake of to make it working via swagger.
You need to use #RequestParam instead of #PathVariable. Then it allows you to make the Parameters optional.

oauth facebook with grails accessing token

Its a grails project,
Facebook authentication is successful via oauth,
Now when it comes back to my controller, I want to get emailID of the logged in user,
Searched a lot, but did not find proper documentation,
I am using scribe and have following code in Config.groory
import org.scribe.builder.api.FacebookApi
oauth {
providers {
facebook {
api = FacebookApi
key = 'xxxx'
secret = 'yyyy'
callback = "http://my-domain-name-here:8080/TestOAuth2/dashBoard/facebooklogin"
successUri = "http://my-domain-name-here:8080/TestOAuth2/dashBoard/success"
}
}
}
Any help much appreciated.
Thanks.
Try this..,.
Config:
import org.scribe.builder.api.FacebookApi
...
oauth {
providers {
facebook {
api = FacebookApi
key = 'XXX'
secret = 'YYY'
scope = 'email,read_stream,publish_actions,user_birthday,publish_stream'
callback = "http://localhost:8080/appName/oauth/facebook/callback" //callback to oauth controller of oauth plugin
successUri = "http://localhost:8080/appName/myController/facebookSuccess"
failureUri = "http://localhost:8080/appName/myController/facebookFailure"
}
}
}
MyController:
def facebookSuccess() {
Token facebookAccessToken = (Token) session[oauthService.findSessionKeyForAccessToken('facebook')]
def facebookResource = oauthService.getFacebookResource(facebookAccessToken, "https://graph.facebook.com/me")
def facebookResponse = JSON.parse(facebookResource?.getBody())
log.info "Email = ${facebookResponse.email}"
...
}
You can get working example from my git repo. Grails Oauth Plugin Demo.
Email is not part of a Facebook public_profile. The only way to get the users e-mail address is to request extended permissions on the email field. You can do this by adding a scope to the oauth provider.
config.groovy
oauth {
providers {
facebook {
api = org.scribe.builder.api.FacebookApi
scope = 'email'
...
...
}
}
}
As an example of how to return email and various public_profile fields please see below.
Take Note of: getFacebookResource params e.g. https://graph.facebook.com/me?fields=id,name,verified,age_range,email"
import grails.converters.JSON
import org.scribe.model.Token
import grails.plugin.springsecurity.oauth.OAuthToken
class SpringSecurityOAuthController {
def oauthService
def onSuccess = {
// Validate the 'provider' URL. Any errors here are either misconfiguration
// or web crawlers (or malicious users).
if (!params.provider) {
renderError 400, "The Spring Security OAuth callback URL must include the 'provider' URL parameter."
return
}
def sessionKey = oauthService.findSessionKeyForAccessToken(params.provider)
if (!session[sessionKey]) {
renderError 500, "No OAuth token in the session for provider '${params.provider}'!"
return
}
// Create the relevant authentication token and attempt to log in.
OAuthToken oAuthToken = createAuthToken(params.provider, session[sessionKey])
Token facebookAccessToken = (Token) session[oauthService.findSessionKeyForAccessToken('facebook')]
def facebookResource = oauthService.getFacebookResource(facebookAccessToken , "https://graph.facebook.com/me?fields=id,name,verified,age_range,email")
def facebookResponse = JSON.parse(facebookResource?.getBody())
println facebookResponse
...
...
}
}
public_profile (Default)
A person's public profile refers to the following properties on the user object by default:
id cover
name
first_name
last_name
age_range
link
gender
locale
picture
timezone
updated_time
verified

WSDL 1.1 Basic question on endpoint salesforce Apex code

From my WSDL I have the following service part:
<service name="BAPI_CUSTOMER_DISPLAYService">
<documentation>SAP Service BAPI_CUSTOMER_DISPLAY via SOAP</documentation>
<port name="BAPI_CUSTOMER_DISPLAYPortType" binding="s0:BAPI_CUSTOMER_DISPLAYBinding">
<soap:address location="http://2.3.4.100:8000/sap/bc/soap/rfc"/>
</port>
</service>
then what will be endpoint reference for this?
I am giving it as "http://2.3.4.100:8000/sap/bc/soap/rfc" in my salesforce client and it gives the following error.
"This service requires client certificate for authentication procedure."
I am sure that i need to give user name and password not knowing how i can set them in my client which is a Apex code.
Help is appreciated.
I imported the Enterprise WSDL and used the uri from the loginResult. Here's some code from my project:
LoginResult loginResult = null; // Login Result (save and make static)
SessionHeader sessionHeader = null; // Session Header (save and make static)
SoapClient soapClient = null; // This is the Enterprise WSDL
SecureStatusClient SecureStatusClient = null; // This is my custom #WebService
// Create Login Request
LoginScopeHeader loginScopeHeader = new LoginScopeHeader
{
organizationId = configuration["OrganizationId"],
portalId = configuration["PortalId"]
};
// Call Login Service
string userName = configuration["UserName"];
string password = configuration["Password"];
string securityToken = configuration["SecurityToken"];
using (SoapClient loginClient = new SoapClient())
{
loginResult = loginClient.login(loginScopeHeader, userName, password + securityToken);
if (result.passwordExpired)
{
string message = string.Format("Salesforce.com password expired for user {0}", userName);
throw new Exception(message);
}
}
// Create the SessionHeader
sessionHeader = new SessionHeader { sessionId = loginResult.sessionId };
// Create the SoapClient to use for queries/updates
soapClient = new SoapClient();
soapClient.Endpoint.Address = new EndpointAddress(loginResult.serverUrl);
// Create the SecureStatusServiceClient
secureStatusClient = new SecureStatusServiceClient();
Uri apexUri = new Uri(SoapClient.Endpoint.Address.Uri, "/services/Soap/class/SecureStatusService");
secureStatusClient.Endpoint.Address = new EndpointAddress(apexUri);

Resources