Unable to access file (url_private property) when file was uploaded by slackbot - slack

I'm trying to upload a file using slackbot and then posting it as a url_private link in my channel. Then when I click on the url_private link the browser throws the error:
The page isn’t redirecting properly An error occurred during a connection to xxx.slack.com. This problem can sometimes be caused by disabling or refusing to accept cookies.
My code:
client = WebClient(token=os.environ.get("SLACK_BOT_TOKEN"))
logger = logging.getLogger(__name__)
try:
result = client.files_upload(
initial_comment="Here's my file :smile:",
file=file_name,
)
logger.info(result)
os.environ['PRIVATE_URL'] = result["file"]["url_private"]
except SlackApiError as e:
logger.error("Error uploading file: {}".format(e))
def post_message_to_slack(blocks = None):
return requests.post('https://slack.com/api/chat.postMessage', {
'token': os.environ['USER_TOKEN'],
'channel': "#test",
'as_user': 'username',
'blocks': json.dumps(blocks)
}).json()
print(post_message_to_slack(blocks))
This is how I receive result:
The SLACK_BOT_TOKEN and USER_TOKEN has files:write, files:read permissions.
I don't know why I'm not able to access the file after I login to my slack account.

Related

Ruby gRPC server authentication SSL/TLS and a custom header with token

I need to connect to a server with authentication and a custom header.
The official gRPC docs show how to do it in Python but not in Ruby:
https://grpc.io/docs/guides/auth/#with-server-authentication-ssltls-and-a-custom-header-with-token
How can this be achieved in ruby ? There doesn't seem to be a metadata call credentials method.
I have tried the following but I'm getting Permission Denied.
channel_creds = GRPC::Core::ChannelCredentials.new()
auth_proc = proc { { 'authorization' => 'Plain ****' } }
call_creds = GRPC::Core::CallCredentials.new(auth_proc)
combined_creds = channel_creds.compose(call_creds)
#stub = Stub.new('host:port', combined_creds)
Nevermind, it was an error because of protection from the server that needed to be disabled, the above code works fine.

File Upload - Error executing ListObjects | AWS S3 & Laravel

I am getting the error below when i try to upload a file greater than 25mb to amazon s3 using laravel aws sdk, however files below 25mb are uploading successfully. I have everything setup correctly in my .env file. I have no idea why this is happening.
Any help would be appreciated.
Error:
Error executing "ListObjects" on
"bucketdomain/?prefix=b6d767d2f8ed5d21a44b0e5886680cb9%filename%2F&max-keys=1&encoding-type=url";
AWS HTTP error: cURL error 7: Failed to connect to bucketdomain
port 443: Network unreachable (see
http://curl.haxx.se/libcurl/c/libcurl-errors.html)
Save function in laravel:
$v = Storage::disk('s3')->put($path, file_get_contents($file), 'public');
unlink($file->getPathname());
return response()->json(["message" => "File uploaded successfully!"]);
Upload function in laravel:
if ($receiver->isUploaded() === false) {
throw new UploadMissingFileException();
}
$save = $receiver->receive();
if ($save->isFinished()) {
database entries...
return $this->saveChunkFile($file,$userFolderName,$path,$fileName);
}
$handler = $save->handler();
return response()->json([
"Percentage" => $handler->getPercentageDone()
]);
I am using reusable.js in client side to upload files in chunks & the code above is to handle the chunks and merge them when done and pass to the saveChunkFile function.
Picture:
The file is to be stored in the 2nd folder from top but there is not file that is why i think the error is thrown on size function and these files (chunks) are being generated and not stopping still.

Unable to get folder by id when using Boxr JWT get_user_token- Box API

I'm unable to a folder by providing an id to that folder using Boxr gem. Previously I didn't has the enterprise settings as shown in this post which I have now fixed. I'm creating a token using JWT authentication get_user_token method the following way.
token = Boxr::get_user_token("38521XXXX", private_key: ENV.fetch('JWT_PRIVATE_KEY'), private_key_password: ENV.fetch('JWT_PRIVATE_KEY_PASSWORD'), public_key_id: ENV.fetch('JWT_PUBLIC_KEY_ID'), client_id: ENV.fetch('BOX_CLIENT_ID'), client_secret: ENV.fetch('BOX_CLIENT_SECRET'))
I then pass this this token when creating a client.
client = Boxr::Client.new(token)
when I check the current user on client this is what I get:
client.current_user
=> {"type"=>"user",
"id"=>"60853XXXX",
"name"=>"OnlineAppsPoC",
"login"=>"AutomationUser_629741_06JgxiPtPj#boxdevedition.com",
"created_at"=>"2018-10-04T08:41:32-07:00",
"modified_at"=>"2018-10-04T08:41:50-07:00",
"language"=>"en",
"timezone"=>"America/Los_Angeles",
"space_amount"=>10737418240,
"space_used"=>0,
"max_upload_size"=>2147483648,
"status"=>"active",
"job_title"=>"",
"phone"=>"",
"address"=>"",
"avatar_url"=>"https://app.box.com/api/avatar/large/6085300897"}
When I run client.methods I see there is folder_from_id however when I call that method I get the following error:
pry(#<FormsController>)> client.folder_from_id("123456", fields: [])
Boxr::BoxrError: 404: Not Found
from /usr/local/bundle/gems/boxr-1.4.0/lib/boxr/client.rb:239:in `check_response_status'
I have the following settings:
I also authorize the application. Not sure what else to do.
token = Boxr::get_user_token(user_id,
private_key: ENV.fetch('JWT_PRIVATE_KEY'),
private_key_password: ENV.fetch('JWT_PRIVATE_KEY_PASSWORD'),
public_key_id: ENV.fetch('JWT_PUBLIC_KEY_ID'),
client_id: ENV.fetch('BOX_CLIENT_ID'),
client_secret: ENV.fetch('BOX_CLIENT_SECRET'))
client = Boxr::Client.new(token.access_token)
folder = client.folder_from_id(folder_id)
client.upload_file(file_path, folder)
For anybody using C# and BOXJWT.
You just need to have a boxManager set up and will get you with anything you need, say BoxFile, Folder etc.
If you have the folderID, well & good, but if you need to retrieve, this can be done as shown below:
string inputFolderId = _boxManager.GetFolder(RootFolderID).Folders.Where(i => i.Name == boxFolder).FirstOrDefault().Id; //Retrieves FolderId
Folder inputFolder = _boxManager.GetFolder(inputFolderId);

Uber Base Redirect Error

I currently have set up a developer account on uber and everything was fine running locally on my PC and http://localhost:7000/submit
I can log in and work with the API. This is great for testing out endpoints. However, my end goal is to use the endpoints on my mobile app. So I went to the redirect URL and switched it to https://my_new_url:7000/submit
I'm using Flask for my server and am using SSL in the following manner:
if __name__ == '__main__':
application.run(host='0.0.0.0',port=7000,ssl_context='adhoc')
However, when navigating to my base url I'm given the following error:
ERROR
THE BASE REDIRECT URI DOES NOT MATCH THE REQUESTED REDIRECT
The code for the base url looks as follows:
def get_redirect_uri(request):
"""Return OAuth redirect URI."""
parsed_url = urlparse(request.url)
if parsed_url.hostname == 'localhost':
return 'http://{hostname}:{port}/submit'.format(
hostname=parsed_url.hostname, port=parsed_url.port
)
return 'https://{hostname}/submit'.format(hostname=parsed_url.hostname)
#application.route('/', methods=['GET'])
def signup():
params = {
'response_type': 'code',
'redirect_uri': get_redirect_uri(request),
'scopes': ','.join(config.get('scopes')),
}
url = generate_oauth_service().get_authorize_url(**params)
return redirect(url)
Do I have to have the application whitelisted before I can change the redirect URL or am I mis-configuring something?
As stated in the error response you received from the /v1/oauth2/authorize endpoint, the problem is that the base of the URI you are sending must match the redirect URI used during the registration of your application in the Uber Developers Dashboard.
Also see this answer: https://stackoverflow.com/a/35638160/313113

Changing the "Upload failed" Message

I would like to change the "Upload failed" message to one returned from my server-side processing.
I can see the message I want in the onError callback but I'm not sure how to used that instead of the default message.
Thoughts, examples or further reading advice welcome (new here).
The implementation of what you're trying to do depends on whether you are using Fine Uploader Basic/Core or Regular/UI. This is because UI mode offers some extra goodies for displaying error messages and such.
A few properties/options that may benefit you:
Fine Uploader Basic/Core mode
text.defaultResponseError
Message sent to the onError callback if no specific information about the error can be determined. This is used if the server indicates failure in the response but does not include an “error” property in the response and the error code is 200 (XHR only)
var uploader = new qq.FineUploaderBasic({
/* ... */
text: {
defaultResponseError: "Oh noes! Upload fail."
}
});
The documentation on 'text'
Fine Uploader Regular/UI mode
failedUploadTextDisplay.mode option
Valid values are “default” (display the text defined in failUploadText next to each failed file), “none” (don’t display any text next to a failed file), and “custom” (display error response text from the server next to the failed file or Blob).
failedUploadTextDisplay.responseProperty option
The property from the server response containing the error text to display next to the failed file or Blob. This is ignored unless mode is “custom”.
var uploader = new qq.FineUploader({
/* ... */
text: {
defaultResponseError: "Oh noes! Upload fail."
},
failedUploadTextDisplay: {
mode: 'custom', // Display error responses from the server.
responseProperty: 'errorMsg' // Default is 'error', change this to match the
// property that contains the error message from
// your server
}
});
The documentation on failedUploadTextDisplay
For people who still use FineUploaded and above does not work, that is because the key is not changed to failUpload.
Usage for a custom message on UI end would be
text: {
failUpload: 'Your upload faile message goes here
},
More details can be found here - https://docs.fineuploader.com/branch/master/upgrading-to-4.html
If you want to display the server-side message, you can do it the below way:
failedUploadTextDisplay {
mode: 'custom',
responseProperty: 'server side error key goes here'
}
If you wish to completely remove it, i.e, not show the message below file if file upload has failed, use below
failedUploadTextDisplay {
mode: 'none'
}

Resources