How to provide credentials to Fetch() and Pul() methods? - libgit2sharp

I'm looking for a nice clean example of how to do a pull using lidgit2sharp. I took the example here which does a fetch, but the reference to Credentials is throwing an exception.
using (var repo = new Repository(workingDir, null))
{
Remote remote = repo.Network.Remotes.Add("master", repoUrl);
repo.Network.Fetch(remote,
{
Credentials credentials = new Credentials
{
Username = "username",
Password = "password"
}
});
}
The exception is Cannot create an instance of the abstract class or
interface 'LibGit2Sharp.Credentials'

It's telling you in the error: Credentials is an abstract class, interface, whatever.
Try this:
Credentials credentials = new UsernamePasswordCredentials()
{
Username = "username",
Password = "password"
}

Related

Using facebook social plugin how to get email address in grails

I want to get email address using social plugin of grails . I am using facebook plugin compile ':spring-security-oauth-facebook:0.1' and configured properly in Config.groovy like below.
oauth {
debug = true
providers {
facebook {
api = org.scribe.builder.api.FacebookApi
key = 'here is my-key'
secret = 'my-secret-key'
successUri = '/oauth/facebook/success'
failureUri = '/oauth/facebook/failure'
callback = "${baseURL}/oauth/facebook/callback"
scopes = "email"
}
}
}
After get successfully response, below method is called.
def onSuccess(String provider) {
if (!provider) {
log.warn "The Spring Security OAuth callback URL must include the 'provider' URL
parameter"
throw new OAuthLoginException("The Spring Security OAuth callback URL must include the
'provider' URL parameter")
}
def sessionKey = oauthService.findSessionKeyForAccessToken(provider)
if (!session[sessionKey]) {
log.warn "No OAuth token in the session for provider '${provider}'"
throw new OAuthLoginException("Authentication error for provider '${provider}'")
}
}
OAuthToken oAuthToken = springSecurityOAuthService.createAuthToken(provider,
session[sessionKey])
println "oAuthToken.principal = "+oAuthToken.principal.toString();
println "oAuthToken.socialId = "+oAuthToken.socialId;
println "oAuthToken.properties= "+oAuthToken.properties
println "oAuthToken.properties= "+oAuthToken.name
println "oAuthToken.properties= "+oAuthToken.toString();
How to get email address by using this. I successfully get response from facebook but it is same number for Username,socialId,profileId but i need email Address like myemailid#gmail.com
please help me.

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

Grails2.1 Dynamic mail configuration

I am trying to send an email from a grails app. I tried with recommended settings using gmail and it worked fine. I sent mail successfully. But I want to override the username and password dynamically. I don't know how can I do it. Can anybody help?
grails {
mail {
host = "smtp.gmail.com"
port = 465
username = "faruq#gmail.com" // Want to change dynamically like variable ${branch.mail}
password = "12345" // Want to change dynamically like variable ${branch.pass}
props = [
"mail.smtp.auth":"true",
"mail.smtp.socketFactory.port":"465",
"mail.smtp.socketFactory.class":"javax.net.ssl.SSLSocketFactory",
"mail.smtp.socketFactory.fallback":"false"
]
}
}
I use this process for overriding the username from the controller
grailsApplication.config.grails.mail.username = Branch.get(2).mail
by this process username successfully changes
here Branch is my domain class and mail is property
but an authentication problem comes up:
javax.mail.AuthenticationFailedException: 535-5.7.8 Username and Password not accepted
Now what can I do?
You can use an external configuration file - put placeholder values in the main Config.groovy
grails {
mail {
host = "smtp.gmail.com"
port = 465
username = "<changeme>"
password = "<changeme>"
props = [
"mail.smtp.auth":"true",
"mail.smtp.socketFactory.port":"465",
"mail.smtp.socketFactory.class":"javax.net.ssl.SSLSocketFactory",
"mail.smtp.socketFactory.fallback":"false"
]
}
}
and then override them with the correct values in the external config:
grails {
mail {
username = "faruq#gmail.com"
password = "12345"
}
}
To be able to change the credentials dynamically at run time it gets rather more complicated. Under the covers the mail plugin creates a Spring bean which is an instance of JavaMailSenderImpl to handle the actual sending of emails, and this bean is configured by default with static settings from the config. But at runtime this class appears to call its own getUsername() and getPassword() every time it needs to send a message. So you could replace this bean with your own custom subclass of JavaMailSenderImpl that overrides these methods to pull the details from the request context (code example, not tested, and imports/error handling omitted):
src/groovy/com/example/RequestCredentialsMailSender.groovy
class RequestCredentialsMailSender extends JavaMailSenderImpl {
public String getUsername() {
return RequestContextHolder.requestAttributes?.currentRequest?.mailUsername ?: super.getUsername()
}
public String getPassword() {
return RequestContextHolder.requestAttributes?.currentRequest?.mailPassword ?: super.getPassword()
}
}
You'd have to register this bean in your resources.groovy, and duplicate a fair bit of the configuration from the mail plugin itself, which is less than ideal:
grails-app/conf/spring/resources.groovy
beans = {
mailSender(com.example.RequestCredentialsMailSender) {
def mailConf = application.config.grails.mail
host = mailConf.host
port = mailConf.port
username = mailConf.username // the default, if not set in request
password = mailConf.password
protocol = mailConf.protocol
javaMailProperties = mailConf.props
}
}
Now when you need to send mail from a controller you can do
request.mailUsername = Branch.get(2).mail
request.mailPassword = Branch.get(2).mailPassword
sendMail { ... }
Just wanted to verify Ian's answer and expand it.
In the default Config.groovy file I have the added external config line:
grails.config.locations = [
"file:./${appName}-config.groovy",
"classpath:${appName}-config.groovy"
]
....
// and here is the mail config as above
grails{
mail{
....
In the config file at the root level I have my config file: TestApp-config.groovy (where TestApp is the name of my app) as above:
grails {
mail {
username = "faruq#gmail.com"
password = "12345"
}
}
Didn't need anything past this and it worked great.
We can also use replyTo field if our aim is only to get the reply back on specific Email Id. We can dynamically pass an email id to "replyTo" field and can expect an email back on the same.
Example :
asynchronousMailService.sendMail
{
to ["xyz#gmail.com","pqr#gmail.com"]
subject "Subject Text"
if(ccs) cc ["xyz1#gmail.com","pqr1#gmail.com"]
if(bccs) bcc ["xyz2#gmail.com","pqr2#gmail.com"]
if(replyTo) replyTo "xyz#gmail.com"
if(attachBytes) attachBytes attachBytes
}
NOTE: Adding "replyTo" will only allow us to get the emails back on the specified email-id and will not send the email from the configured email.
It was suitable in my use case. Hope it helps !

How can one supply credentials during a Fetch call?

We're not talking about SSH since it's not yet implemented, but how can I supply credentials for the repository before I perform a fetch via HTTP/HTTPS? There doesn't seem to be a parameter for a Credentials instance, and nothing when constructing a Repository instance for storing credentials.
Within the FetchFixture.cs file, there is a Fetch() test using credentials:
[SkippableFact]
public void CanFetchIntoAnEmptyRepositoryWithCredentials()
{
InconclusiveIf(() => string.IsNullOrEmpty(Constants.PrivateRepoUrl),
"Populate Constants.PrivateRepo* to run this test");
string repoPath = InitNewRepository();
using (var repo = new Repository(repoPath))
{
Remote remote = repo.Network.Remotes.Add(remoteName, Constants.PrivateRepoUrl);
// Perform the actual fetch
repo.Network.Fetch(remote, new FetchOptions
{
Credentials = new Credentials
{
Username = Constants.PrivateRepoUsername,
Password = Constants.PrivateRepoPassword
}
});
}
}

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