Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Auth feature #270

Merged
merged 9 commits into from
Mar 29, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions SlackAPI.Tests/Conversations.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
using System.Linq;
using SlackAPI.RPCMessages;
using SlackAPI.Tests.Configuration;
using SlackAPI.Tests.Helpers;
using Xunit;

namespace SlackAPI.Tests
{
[Collection("Integration tests")]
public class Conversations
{
private readonly IntegrationFixture fixture;

public Conversations(IntegrationFixture fixture)
{
this.fixture = fixture;
}
[Fact]
public void ConversationList()
{
var client = this.fixture.UserClient;
ConversationsListResponse actual = null;
using (var sync = new InSync(nameof(SlackClient.ChannelLookup)))
{
client.GetConversationsList(response =>
{
actual = response;
sync.Proceed();
});
}

Assert.True(actual.ok, "Error while fetching conversation list.");
Assert.True(actual.channels.Any());

// check to null
var someChannel = actual.channels.First();
Assert.NotNull(someChannel.id);
Assert.NotNull(someChannel.name);
}
}
}
2 changes: 1 addition & 1 deletion SlackAPI.Tests/UserUIInteraction.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ public void TestGetAccessToken()

var accessTokenResponse = GetAccessToken(slackClientHelpers, clientId, clientSecret, redirectUrl, code);
Assert.True(accessTokenResponse.ok);
Assert.Equal("identify", accessTokenResponse.scope);
Assert.Contains("identify", accessTokenResponse.scope);
}
}

Expand Down
6 changes: 2 additions & 4 deletions SlackAPI/Channel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,14 @@ public class Channel : Conversation
{
public string name;
public string creator;
public string user;

public bool is_archived;
public bool is_member;
public bool is_general;
public bool is_channel;
public bool is_group;
public bool is_im;
//Is this deprecated by is_open?
public bool IsPrivateGroup { get { return id != null && id[0] == 'G'; } }

Expand All @@ -24,9 +26,5 @@ public class Channel : Conversation
public OwnedStampedMessage purpose;

public string[] members;

//im related properties
public bool is_im;
public string user;
}
}
12 changes: 2 additions & 10 deletions SlackAPI/SlackClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -108,14 +108,7 @@ protected virtual void Connected(LoginResponse loginDetails)
public void APIRequestWithToken<K>(Action<K> callback, params Tuple<string, string>[] getParameters)
where K : Response
{
Tuple<string, string>[] tokenArray = new Tuple<string, string>[]{
new Tuple<string,string>("token", APIToken)
};

if (getParameters != null && getParameters.Length > 0)
tokenArray = tokenArray.Concat(getParameters).ToArray();

APIRequest(callback, tokenArray, new Tuple<string, string>[0]);
APIRequest(callback, getParameters, new Tuple<string, string>[0], APIToken);
}

public void TestAuth(Action<AuthTestResponse> callback)
Expand Down Expand Up @@ -872,7 +865,6 @@ public void UploadFile(Action<FileUploadResponse> callback, byte[] fileData, str
Uri target = new Uri(Path.Combine(APIBaseLocation, useAsync ? "files.uploadAsync" : "files.upload"));

List<string> parameters = new List<string>();
parameters.Add(string.Format("token={0}", APIToken));

//File/Content
if (!string.IsNullOrEmpty(fileType))
Expand All @@ -892,7 +884,7 @@ public void UploadFile(Action<FileUploadResponse> callback, byte[] fileData, str
using (MultipartFormDataContent form = new MultipartFormDataContent())
{
form.Add(new ByteArrayContent(fileData), "file", fileName);
HttpResponseMessage response = PostRequest(string.Format("{0}?{1}", target, string.Join("&", parameters.ToArray())), form);
HttpResponseMessage response = PostRequestAsync(string.Format("{0}?{1}", target, string.Join("&", parameters.ToArray())), form, APIToken).Result;
string result = response.Content.ReadAsStringAsync().Result;
callback(result.Deserialize<FileUploadResponse>());
}
Expand Down
40 changes: 34 additions & 6 deletions SlackAPI/SlackClientBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Newtonsoft.Json;

Expand Down Expand Up @@ -33,7 +34,11 @@ protected SlackClientBase(IWebProxy proxySettings)

protected Uri GetSlackUri(string path, Tuple<string, string>[] getParameters)
{
string parameters = getParameters
string parameters = default;

if (getParameters != null && getParameters.Length > 0)
{
parameters = getParameters
.Where(x => x.Item2 != null)
.Select(new Func<Tuple<string, string>, string>(a =>
{
Expand All @@ -54,11 +59,19 @@ protected Uri GetSlackUri(string path, Tuple<string, string>[] getParameters)
return string.Format("{0}&{1}", a, b);
});

Uri requestUri = new Uri(string.Format("{0}?{1}", path, parameters));
}

Uri requestUri = default;

if (!string.IsNullOrEmpty(parameters))
requestUri = new Uri(string.Format("{0}?{1}", path, parameters));
else
requestUri = new Uri(path);

return requestUri;
}

protected void APIRequest<K>(Action<K> callback, Tuple<string, string>[] getParameters, Tuple<string, string>[] postParameters)
protected void APIRequest<K>(Action<K> callback, Tuple<string, string>[] getParameters, Tuple<string, string>[] postParameters, string token = "")
where K : Response
{
RequestPath path = RequestPath.GetRequestPath<K>();
Expand All @@ -68,12 +81,15 @@ protected void APIRequest<K>(Action<K> callback, Tuple<string, string>[] getPara
Uri requestUri = GetSlackUri(Path.Combine(APIBaseLocation, path.Path), getParameters);
HttpWebRequest request = CreateWebRequest(requestUri);

if (!string.IsNullOrEmpty(token))
request.Headers.Add("Authorization", "Bearer " + token);

//This will handle all of the processing.
RequestState<K> state = new RequestState<K>(request, postParameters, callback);
state.Begin();
}

public Task<K> APIRequestAsync<K>(Tuple<string, string>[] getParameters, Tuple<string, string>[] postParameters)
public Task<K> APIRequestAsync<K>(Tuple<string, string>[] getParameters, Tuple<string, string>[] postParameters, string token = "")
where K : Response
{
RequestPath path = RequestPath.GetRequestPath<K>();
Expand All @@ -83,6 +99,9 @@ public Task<K> APIRequestAsync<K>(Tuple<string, string>[] getParameters, Tuple<s
Uri requestUri = GetSlackUri(Path.Combine(APIBaseLocation, path.Path), getParameters);
HttpWebRequest request = CreateWebRequest(requestUri);

if (!string.IsNullOrEmpty(token))
request.Headers.Add("Authorization", "Bearer " + token);

//This will handle all of the processing.
var state = new RequestStateForTask<K>(request, postParameters);
return state.Execute();
Expand Down Expand Up @@ -111,9 +130,18 @@ protected HttpWebRequest CreateWebRequest(Uri requestUri)
return httpWebRequest;
}

protected HttpResponseMessage PostRequest(string requestUri, MultipartFormDataContent form)
protected Task<HttpResponseMessage> PostRequestAsync(string requestUri, MultipartFormDataContent form, string token)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FYI, this is the part I take issue with. We have a split client for handling async workflows specifically.

Calling .Result does not work as a way to invoke async from a sync call

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

And I'm realizing we did do .Result before. Ugh.

{
return httpClient.PostAsync(requestUri, form).Result;
var requestMessage = new HttpRequestMessage
{
Method = HttpMethod.Post,
Content = form,
RequestUri = new Uri(requestUri),
};

requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);

return httpClient.SendAsync(requestMessage);
}

public void RegisterConverter(JsonConverter converter)
Expand Down
9 changes: 2 additions & 7 deletions SlackAPI/SlackTaskClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -91,11 +91,7 @@ public Task<K> APIRequestWithTokenAsync<K>()
public Task<K> APIRequestWithTokenAsync<K>(params Tuple<string,string>[] postParameters)
where K : Response
{
Tuple<string, string>[] tokenArray = new Tuple<string, string>[]{
new Tuple<string,string>("token", APIToken)
};

return APIRequestAsync<K>(tokenArray, postParameters);
return APIRequestAsync<K>(new Tuple<string, string>[] { }, postParameters, APIToken);
}

public Task<AuthTestResponse> TestAuthAsync()
Expand Down Expand Up @@ -816,7 +812,6 @@ public async Task<FileUploadResponse> UploadFileAsync(byte[] fileData, string fi
Uri target = new Uri(Path.Combine(APIBaseLocation, useAsync ? "files.uploadAsync" : "files.upload"));

List<string> parameters = new List<string>();
parameters.Add(string.Format("token={0}", APIToken));

//File/Content
if (!string.IsNullOrEmpty(fileType))
Expand All @@ -836,7 +831,7 @@ public async Task<FileUploadResponse> UploadFileAsync(byte[] fileData, string fi
using (MultipartFormDataContent form = new MultipartFormDataContent())
{
form.Add(new ByteArrayContent(fileData), "file", fileName);
HttpResponseMessage response = PostRequest(string.Format("{0}?{1}", target, string.Join("&", parameters.ToArray())), form);
HttpResponseMessage response = await PostRequestAsync(string.Format("{0}?{1}", target, string.Join("&", parameters.ToArray())), form, APIToken);
string result = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
return result.Deserialize<FileUploadResponse>();
}
Expand Down