Using GitLab API to set external issues tracker settings? - jira

I'm using GitLab with an external issue tracker (JIRA), and it works well.
My problem is when I create a new GitLab project (using API), I have to go the GitLab's project settings and manually select the issue tracker I want to use and manually enter the project's id of my external issue tracker.
This screen will be more eloquent:
(source: bayimg.com)
(The two fields I am talking about are "Issue tracker" and "Project name or id in issues tracker")
So here is my question: is there any way to set up this two fields automatically, using API or other ? Currently, GitLab API does not mention anything about external issues tracker settings.

This code helped me to automatically set the GitLab's external issues-tracker settings, using Apache HttpClient and Jsoup.
This code is absolutely not 100% good, but it shows the main idea, wich is to recreate the corresponding POST request that the web form sends.
// 1 - Prepare the HttpClient object :
BasicCookieStore cookieStore = new BasicCookieStore();
LaxRedirectStrategy redirectStrategy = new LaxRedirectStrategy();
CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultCookieStore(cookieStore)
.setRedirectStrategy(redirectStrategy)
.build();
try {
// 2 - Second you need to get the "CSRF Token", from a <meta> tag in the edit page :
HttpUriRequest getCsrfToken = RequestBuilder.get()
.setUri(new URI("http://localhost/_NAMESPACE_/_PROJECT_NAME_/edit"))
.build();
CloseableHttpResponse responseCsrf = httpclient.execute(getCsrfToken);
try {
HttpEntity entity = responseCsrf.getEntity();
Document doc = Jsoup.parse(EntityUtils.toString(entity));
String csrf_token = doc.getElementsByAttributeValue("name", "csrf-token").get(0).attr("content");
// 3 - Fill and submit the "edit" form with new values :
HttpUriRequest updateIssueTracker = RequestBuilder
.post()
.setUri(new URI("http://localhost/_NAMESPACE_/_PROJECT_NAME_"))
.addParameter("authenticity_token", csrf_token)
.addParameter("private_token", "_MY_PRIVATE_TOKEN_")
.addParameter("_method", "patch")
.addParameter("commit", "Save changes")
.addParameter("utf8", "✓")
.addParameter("project[issues_tracker]", "jira")
.addParameter("project[issues_tracker_id]", "_MY_JIRA_PROJECT_NAME_")
.addParameter("project[name]", "...")
...
.build();
CloseableHttpResponse responseSubmit = httpclient.execute(updateIssueTracker, httpContext);
} finally {
responseCsrf.close();
}
} finally {
httpclient.close();
}
Change _NAMESPACE_/_PROJECT_NAME_ to make it corresponds to your project URL, change _MY_PRIVATE_TOKEN_ with your admin account's token, and change _MY_JIRA_PROJECT_NAME_ with ... your jira project's name.

Related

NopCommerce - How Can I use wsdl Service Reference in the plugin

Recently I'm working on a payment plugin for zarinpal.com gate way.
I have to add a service reference by this URL :
https://sandbox.zarinpal.com/pg/services/WebGate/wsdl
Every thing is ok but in PostProcessPayment I face with the error :
Could not find default endpoint element that references contract
'ServiceReference.PaymentGatewayImplementationServicePortType'
in the ServiceModel client configuration section. This might be
because no configuration file was found for your application,
or because no endpoint element matching this contract could be found
in the client element.
and this is my PostProcessPayment method :
public void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
{
string urlToRedirect = "";
var zarinpal =
new ServiceReference.PaymentGatewayImplementationServicePortTypeClient();
string outResult = "";
int code = zarinpal.PaymentRequest("5607e960-d64c-4a8b-b03b-0e645bef37d4"
, 2500, "Our Test Store Name"
, "test#gmail.com", "0999999999"
, "http://" + _webHelper.GetStoreLocation(false)
+ "/Plugins/ZarinPal/PDTHandler", out outResult);// test
if (code == 100)
{
urlToRedirect = string.Concat("https://sandbox.zarinpal.com/pg/StartPay/"
, outResult);
}
_httpContext.Response.Redirect(urlToRedirect);
}
I would better to mention that if i add the Service Reference to Nop.Web Project too, it works well, but I want to build this as a module and adding the Service Reference Manually to Nop.Web is Unpleasant.
could you please help me ?

A simple ASP .NET MVC API controller using roles

I wrote a web application using ASP .NET MVC and authorization system by default. I configured IdentityRole and input through external providers. Using the current database I have created my data context. Now I want to write a Xamarin.Android app and connect to my database, I want a simple API. But the feature that you want to access this API was only available to user with a certain role. The API is really very simple and therefore do not want to add to the draft WCF or WebAPI project. How to do it best?
First, you don't need a separate project to use Web Api; you can use both MVC and Web Api in the same project. For one off endpoints for things like in-site AJAX requests, just creating MVC actions that return JSON or XML would be fine, but if you're talking about a true API, even if it's fairly simplistic, I'd say go Web Api.
You'd protect your Web Api actions much the same as you would your MVC actions, using the [Authorize] attribute. If you need to restrict by role, you just pass a role(s) to that. However, the big difference here, especially if you're serving a mobile app, is that you'll need pass the authorization along with the request. That's generally accomplished using the Authorization header along with a bearer token. Basically, you would need to set up an endpoint that signs a user in and returns a token. Then, each subsequent request that needs authorization includes that token in the header.
I want to finish and to fully answer this question and close this topic. I've been searching for how to add the ability for a mobile client to connect to an existing site on ASP.NET MVC. In my search, I came across a great article Justin Hyland on March 2, 2014
In principle, everything in this article is well and clearly written, but I want to make a tiny contribution for clarity.
Under Setup WebAPIConfig stated that the need
added in the following code to the WebApiConfig Register method
But if we consider the case ASP.NET MVC we don't have such file. It's all very simple, you just need such a file to create the folder App_Start. The contents of the file can be left exactly as it is in the article.
To get rid of the bugs which will inevitably appear we need to install two nuget package: Microsoft.AspNet.WebApi and Microsoft.AspNet.WebApi.Owin.
Excellent! Now we can turn to the method to obtain the token and then adding the token to the query we can get the needed data closed by the attribute [Authorize].
A small remark. If You need to access a method which is closed for a specific role that to the Authenticate method from the article should add a few lines of code. Immediately after the line:
identity.AddClaim(new Claim(ClaimTypes.Name, user));
add the line:
identity.AddClaim(new Claim(ClaimTypes.Role, role));
where role you can get the following, for example:
var userIdentity = UserManager.FindAsync(user, password).Result;
var role = RoleManager.FindById(userIdentity.Roles.First().RoleId).Name;
User and password you have to send a request.
I also want to give an example of code which will send request and receive response. To not have to look for and immediately start coding.
async Task<string> GetToken(string userName, string password)
{
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>( "user", userName ),
new KeyValuePair<string, string> ( "password", password )
}
);
using (var client = new HttpClient())
{
HttpResponseMessage response = await client.PostAsync(APP_PATH + "/Authenticate", content);
var result = await response.Content.ReadAsStringAsync();
return result;
}
}
async Task<string> GetUserInfo(string token)
{
using (var client = CreateClient(token))
{
var response = await client.GetAsync(APP_PATH + "/ValidateToken");
return await response.Content.ReadAsStringAsync();
}
}
HttpClient CreateClient(string accessToken = "")
{
var client = new HttpClient();
if (!string.IsNullOrWhiteSpace(accessToken))
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
}
return client;
}
All have only to call the appropriate methods in the correct order. I hope that is useful to someone.
P.S.
If You create a new project in Visual Studio to get this functionality you just need to tick:

Get Error (error=access_denied) while logging in MVC5 application with facebook SDK

I have developed an application with ASP.NET MVC5. I have used Facebook external authentication in my application.
When I debug this application with the "Locallhost" domain, the Facebook login works well but when I publish the application in the main server,the AuthenticationManager.GetExternalLoginInfo() returns null and it gives me an error like this in the url:
http://xxxxx.com/Account/ExternalLoginCallback?ReturnUrl=%2Fen&error=access_denied#_=_
I have set the "Site URL" as "http://xxxx.com" and "Valid OAuth redirect URIs" as "http://xxxx.com/signin-facebook" in the Facebook development console.
My setting in the Startup.Outh.cs file is:
var FacebookOptions = new Microsoft.Owin.Security.Facebook.FacebookAuthenticationOptions();
FacebookOptions.AppId = ConfigurationManager.AppSettings["Facebook_User_Key"];
FacebookOptions.AppSecret = ConfigurationManager.AppSettings["Facebook_Secret_Key"];
FacebookOptions.Provider = new Microsoft.Owin.Security.Facebook.FacebookAuthenticationProvider()
{
OnAuthenticated = async context =>
{
context.Identity.AddClaim(new System.Security.Claims.Claim("FacebookAccessToken", context.AccessToken));
foreach (var claim in context.User)
{
var claimType = string.Format("urn:facebook:{0}", claim.Key);
string claimValue = claim.Value.ToString();
if (!context.Identity.HasClaim(claimType, claimValue))
context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "Facebook"));
}
}
};
FacebookOptions.SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie;
app.UseFacebookAuthentication(FacebookOptions);
I don't know why the external login does not work only in the server with my main domain name. please help me about this problem.
I encountered pretty much the same symptoms you describe:
shortly:
A Facebook authentication worked well on localhost, and after uploading the project to another server (and changing the site URL on Facebook console), authentication did not succeed.
I would recommend you roll back to the MVC template code, and if that works - notice any changes you have made to the middleware code (Startup.Auth.sc).
In particular pay attention to code that interacts with LOCAL configuration, such as Disk I/O and OS permissions for local services.
My particular case:
Starting from the Owin/Katana supported Visual Studio template of a WebAPI project, external login was working perfectly with Facebook, Microsoft and Google OAuth middleware, when testing on localhost.
Later I added come code to Startup.Auth.sc because I needed further authentication activity.
So this was the original code:
public void ConfigureAuth(IAppBuilder app)
{
// see WebAPI template of Visual Studio 2013/2015
...
app.UseFacebookAuthentication(
appId: 99999999,
appSecret: *******);
}
and this was replacement:
public void ConfigureAuth(IAppBuilder app)
{
// see WebAPI template of Visual Studio 2013/2015
...
app.UseFacebookAuthentication(GetFacebookAuth());
}
private FacebookAuthenticationOptions GetFacebookAuth()
{
string picRequest =
String.Format("/me/picture?redirect=false&width={0}&height={0}", ProfileInfoClaimsModel.PIC_SIDE_PX);
var facebookProvider = new FacebookAuthenticationProvider()
{
OnAuthenticated = async (context) =>
{
var client = new FacebookClient(context.AccessToken);
dynamic me = client.Get("/me?fields=id,name,locale");
dynamic mePicture = client.Get(picRequest);
// storing temporary social profile info TO A LOCAL FOLDER
// uploading the local folder to a service WITH A LOCAL CREDENTIAL FILE
...
}
};
var options = new FacebookAuthenticationOptions()
{
AppId = 0123456789,
AppSecret = ******,
Provider = facebookProvider,
};
return options;
}
You may notice that my comments will make the problem obvious - the code points to local resources.
Then I published the project to a virtual server (by Amazon EC2) running Windows Server 2012 with IIS 8.5.
From that moment I kept getting error=access_denied in the redirect from /signin-facebook.
I decided to follow this good old concept, and go back to the original template code. Pretty soon I figured out that I forgot to configure the new server. For instance, the folder the code refers to did not exist and the site had no permission to create it.
Obviously, that solved it.

Google OAuth on MVC5 ExternalLoginCallback?error=access_denied

I have set up my Google OAuth
And I have added the code into Startup.Auth.cs
app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
{
// LRC
ClientId = "xxxxxxxxx",
ClientSecret = "xxxxx"
//CallbackPath = new PathString("/signin-google")
});
But after I chose a google account to log in, it redirected me to the login page again,
I checked the network via Chrome and found that the access was denied.
http://www.liferunningclub.com.au/Account/ExternalLoginCallback?error=access_denied
I cannot figure it out.
Update
Now I did something else:
I added an annotation ([RequireHttps]) on the Account Controller
I enabled the SSL for my project.
I updated the url and re-direct url in Google Console to https
Tried to log in with Google, after I selected my Google account, it returned the same access_denied.
It would be better if the response from Google could give more detailed information.
I had the same problem using the latest ASP.Net MVC template with "Individual Accounts" selected.
The solution was to enable the Google+ API for my project in the Google Developer console.
I found my answer here (scroll down to "Changes to Google OAuth 2.0...").
The same error happened to me for Facebook provider.
Turns out the solution was as simple as updating the nuget package to 3.1.
It turns out that Facebook did a "force upgrade" of their graph API
from version 2.2 to 2.3 on 27th March 2017
For the record I'm using the following:
http://localhost:58364 in iisexpress with NO https
In Facebook I have the following settings configured for a test app:
In addition if you're using a sample template the error parameter returned isn't being consumed which can be misleading. You should add string error to ExternalLoginCallback
[AllowAnonymous]
public async Task<ActionResult> ExternalLoginCallback(string returnUrl, string error)
{
if (error != null)
{
return View("Error");
}
I had this problem as well. After I enabled the Google+ API the problem is not solved yet. Turns out I haven't set the 'Authorized JavaScript origins' in my google API console. So I set the authorized javascript origins, and the problem solved.
I had the same issue. I had Google+ API active and set JavaScript providers. Turns out that my version of Microsoft.Owin 3.1 was too old. I've updated every single nugget which had Microsoft.Owin.(whatever) in it's name and it started working fine (version 4.1)
Hope it helps!
This is most likely because you have not enabled the Google + API in the developer console.
So when your account trys to get the details about the Google Account, it says access_denied.
Simply go to the developer console and enable the Google + API
None of the above solution worked for me. Turns out In my case I was tweaking with Google OAuth Playground and I added https://developers.google.com/oauthplayground this url in Authorized Redirect Uris section of my Google Credentials for Client ID and Secrets.
When I removed it and retried, it worked fine.
PS: I had to reset the OAuth Playground settings that I had modified too.
EDIT
The other issue was, my code threw an Exception when the user was OnAthenticated EventHandler was triggered. Turns out a null reference which was resulting in access_denied status being returned.
GoogleOAuth2AuthenticationOptions googleOptions = new GoogleOAuth2AuthenticationOptions()
{
ClientId = "xxxxx.apps.googleusercontent.com",
ClientSecret = "XXXX",
Provider = new GoogleOAuth2AuthenticationProvider()
{
OnAuthenticated = (context) =>
{
try
{
TokenHelper tokenHelper = new TokenHelper();
// Any exception here will result in 'loginInfo == null' in AccountController.ExternalLoginCallback.
// Be sure to add exception handling here in case of production code.
context.Identity.AddClaim(new Claim(tokenHelper.AccessToken, context.AccessToken)); // From This line and onwards. tokenHelper's properties were null.
// For clarity, we don't check most values for null but RefreshToken is another kind of thing. It's usually
// not set unless we specially request it. Typically, you receive the refresh token only on the initial request,
// store it permanently and reuse it when you need to refresh the access token.
if (context.RefreshToken != null)
{
context.Identity.AddClaim(new Claim(tokenHelper.RefreshToken, context.RefreshToken));
}
// We want to use the e-mail account of the external identity (for which we doing OAuth). For that we save
// the external identity's e-mail address separately as it can be different from the main e-mail address
// of the current user.
context.Identity.AddClaim(new Claim(tokenHelper.Email, context.Email));
context.Identity.AddClaim(new Claim(tokenHelper.Name, context.Name));
context.Identity.AddClaim(new Claim(tokenHelper.IssuedOn, DateTime.Now.ToString()));
context.Identity.AddClaim(new Claim(tokenHelper.ExpiresIn,
((long)context.ExpiresIn.Value.TotalSeconds).ToString()));
return Task.FromResult(0);
}
catch (Exception ex)
{
throw;
}
},
},
AccessType = "offline",
UserInformationEndpoint= "https://www.googleapis.com/oauth2/v2/userinfo"
};
Default Google authentication no longer works, you can add updated Owin.Security.Provider.Google package through NuGet or find it here
Try to use https:// instead of http:

Facebook OAuth + AppHarbor workaround on random port

I a have a sample app, hosted on AppHarbor and now want to integrate authorization through facebook. So i downloaded nugget Facebook.Web.Mvc package to implement it.
After reading tutorial, in controller i have method:
public ActionResult Login(string returnUrl)
{
var oauthClient = new FacebookOAuthClient(FacebookApplication.Current) { RedirectUri = GetFacebookRedirectUri() };
if (!string.IsNullOrWhiteSpace(returnUrl))
{
returnUrl = Url.Action("Index", "Facebook");
}
dynamic parameters = new ExpandoObject();
parameters.scope = ExtendedPermissions;
var state = new { csrf_token = CalculateMD5Hash(Guid.NewGuid().ToString()), return_url = returnUrl };
parameters.state = Base64UrlEncode(Encoding.UTF8.GetBytes(JsonSerializer.Current.SerializeObject(state)));
SetFacebookCsrfToken(state.csrf_token);
string s = oauthClient.GetLoginUrl(parameters).AbsoluteUri;
ViewBag.FacebookLoginUrl = s;
//new LogEvent(s).Raise();
return View(new AccountModel());
}
View:
<a href="#ViewBag.FacebookLoginUrl" id="lUrl">
<div class="fblogin"></div>
In localhost this works for me.
But when i upload it to appharbor, i see, that generated link indicates to address + port 16013 (as support told always random port). So clicking it shows me facebook login window, than blank page.
I manually configured my app settings in facebook to this port but it did not helped.
Also i tried to access my site through this port - nothing.
Then i changed port number through jquery to 80, its also did not help.
you have had such problems?
I'm not familiar with the Facebook api, but I've had a similar problem.
I suspect that the returnUrl value being passed in is incorrect. It probably contains a port number that AppHarbor uses internally for load balancing.
See this article on how to create a public url for AppHarbor:
http://support.appharbor.com/kb/getting-started/workaround-for-generating-absolute-urls-without-port-number
Then make sure that the value in your returnUrl is publicly available.
You can now set the aspnet:UseHostHeaderForRequestUrl appSetting to true which effectively solves this problem. This can be done by adding a Configuration Variable to your application with the corresponding key and value.
Source on AppHarbor

Resources