Uploading a file to WebDAV server using AlamoFire - alamofire

I'm working on a private iOS14 app that will send files to a website server. User will just tap on a button, and the code will do all the work (hard coded username and password).
I would like to upload File.json to a WebDAV server (http://myWebsite.com/Files).
I would like to upload Image.png to a WebDAV server (http://myWebsite.com/Files).
The server requires a username & password (username: username, password: password).
func UploadJson(){
let username = "username"
let password = "password"
let credential = URLCredential(user: username, password: password, persistence: .forSession)
let fileURL = Bundle.main.url(forResource: "File", withExtension: "json")!
let http = "https://myWebiste.com/Files"
AF.upload(fileURL, to: http)
.authenticate(with: credential)
.response { response in
debugPrint(response)
}
}
I get a [Response]:
[Status Code]: 200
But no file has been uploaded.
I can use a Mac and login using the username and password and upload a file to the server, so I know the WebDAV folder is working. But the AlamoFire code isn't.
What am I missing? Do I need anything in the Files folder on the server to allow uploads? Currently it is empty.

Related

403 access denied to the website with proper login/pass through google script

var url = "https://web-site_name/page/?format=json&var_data-organization_dates&xlsexport=true";
var payload =
{
"login" : "login",
"password" : "pass",
};
var options =
{
"method" : "post",
"payload" : payload,
"followRedirects" : false
};
var login = UrlFetchApp.fetch("https://web-site_name/page/" , options);
var sessionDetails = login.getAllHeaders()['Set-Cookie'];
Logger.log(login.getAllHeaders());
here is the part of the code I try to use, to automate export of the data from web-site, i do have proper login and password and able to download file in json (opened in xsl) manually, I've got the address to the downloaded file in network in developer tools, but i have a problem on the first stage - when trying to authorize to the web-site - access denied. I've tried the code, given in answers on stackoverflow, but it still doesn't work.
How to make an url fetch request correctly, depends on the website you want to access and the authentication they uses
In the simplest case, your website requires HTTP basic authentification, in this case the correct syntax would be
var authHeader = 'Basic ' + Utilities.base64Encode(login + ':' + pass);
var options = {
headers: {Authorization: authHeader}
}
If your website uses a different authentication form, you might need to provide an access token.
In any case: the authentication credentials go into headers, not into payload!
payload is the data that you want to post = upload to the website.
If you want export data from the website - that is download data - you do not need a payload and the correct method would be get, not post. Btw., if the method is get, you do not need to specify it.
Please see here for more information and samples.

Authentification with ldap without user's password

I am trying to create login authentication with ldap js. I set up all Credentials and everything is working fine, but the problem is I can bind a user just with his Uid (user id aka username), it didn't ask for a password and I don't know how to fix this it must ask for Uid and userPAssword to connect
I tried to connect to with the same credentials including userPassword but it didn't work for me
ldapConfig.js
in this file i set up all ldap config
'url': 'ldap://*************',
'port': '***',
'timeout': '',
'connectTimeout': '',
'secret': '**********',
'reconnect': true,
'filtre': '(&(ObjectClass=*******)',
'search_dn': 'ou=******,dc=****,dc=****',
'domain': 'cn=******,dc=****,dc=****'
login.js
in this file i tried to connect to ldap server and it work realy fine and then i want to get user by uid
const server = ldapConfig.url
const ldapDomain = ldapConfig.domain
const password = ldapConfig.secret
const searchDomain = ldapConfig.search_dn
const client = ldap.createClient({
url: server
})
client.bind(ldapDomain, password, err => {
assert.ifError(err)
})
const opts = {
scope: 'sub',
filter: ldapConfig.filtre + `(mail=${request.body.mail}))`
}
client.search(searchDomain, opts, (err, res) => {
assert.ifError(err)
res.on('searchEntry', entry => {
console.log(entry.object)
} )
I hope it's clear . Thanks
Unauthenticated bind (a seemingly successful bind when you supply a userID and null password) may be enabled in your directory. If you are using OpenLDAP, as the quesstion tags indicate, check slapd.conf for allow bind_anon_cred.
Unless there is a specific need for unauthenticated bind, I disable it on the directory servers. In the rare cases where unauthenticated bind is required, all applications authenticating against the directory need to validate user input before attempting to bind -- that is, verify that the input username and password values are not null.

Enabling Reset Password and email verification for parse-server hosted locally

I am trying to enable reset password and email verification for my parse-server-example installed locally. I could see we have https://github.com/parse-server-modules/parse-mailgun.
But I am not clear how to use parse-mailgun in parse-server-example, I am completely lost with it.
Can somebody explain or suggest steps to enable it?
Regards
Atul
Create account with MailGun, and get apiKey and Domain from its website.
Copy and Paste below configuration under index.js file of your parse-server-example git folder at your local system.You can get this file under parse-server-example folder directly.
verifyUserEmails: true,
publicServerURL: 'https://yourproject.herokuapp.com/parse',
appName: 'Parse App',
emailAdapter: {
module: 'parse-server-simple-mailgun-adapter',
options: {
fromAddress: 'parse#example.com',
domain: '<domainProvidedFromMailGun>.mailgun.org',
apiKey: 'key-FromMailGun',
}
},
Push it to heroku app git, since I have piloted my parse-server to heroku so below cmd's will be valid.
git add .
git commit -m "mypush commit"
heroku git:remote -a fast-springs-29785
git push heroku master
https://github.com/ParsePlatform/parse-server
Email verification and password reset
Verifying user email addresses and enabling password reset via email requries an email adapter. As part of the parse-server package we provide an adapter for sending email through Mailgun. To use it, sign up for Mailgun, and add this to your initialization code:
var server = ParseServer({
...otherOptions,
// Enable email verification
verifyUserEmails: true,
// The public URL of your app.
// This will appear in the link that is used to verify email addresses and reset passwords.
// Set the mount path as it is in serverURL
publicServerURL: 'https://example.com/parse',
// Your apps name. This will appear in the subject and body of the emails that are sent.
appName: 'Parse App',
// The email adapter
emailAdapter: {
module: 'parse-server-simple-mailgun-adapter',
options: {
// The address that your emails come from
fromAddress: 'parse#example.com',
// Your domain from mailgun.com
domain: 'example.com',
// Your API key from mailgun.com
apiKey: 'key-mykey',
}
}
});
You can also use other email adapters contributed by the community such as parse-server-sendgrid-adapter or parse-server-mandrill-adapter.

How to get thumbnails for shared OneDrive files to unauthorized users? This useful OneDrive feature provided in the old API is broken now

My app uses OneDrive API feature to let unauthorized users get thumbnails for shared OneDrive files using old API request:
https:// apis.live.net/v5.0/skydrive/get_item_preview?type=normal&url=[shared_link_to_OneDrive_file]
This feature is broken now (any such links return XMLHttpRequest connection error 0x2eff).
And my Windows Store app can not longer provide this feature.
Anyone can try to check it, link to shared OneDrive file:
https://onedrive.live.com/redir?resid=AABF0E8064900F8D!27202&authkey=!AJTeSCuaHMc45eY&v=3&ithint=photo%2cjpg
links to a preview image for shared OneDrive file (according to old OneDrive API
"Displaying a preview of a OneDrive item" - https:// msdn.microsoft.com/en-us/library/jj680723.aspx):
https://apis.live.net/v5.0/skydrive/get_item_preview?type=normal&url=https%3A%2F%2Fonedrive.live.com%2Fredir%3Fresid%3DAABF0E8064900F8D!27202%26authkey%3D!AJTeSCuaHMc45eY%26v%3D3%26ithint%3Dphoto%252cjpg
generates error: SCRIPT7002: XMLHttpRequest: Network error 0x2eff
Сurrent OneDrive API thumbnail feature:
GET /drive/items/{item-id}/thumbnails/{thumb-id}/{size}
is just for authorized users and can not provide access to thumbnails for shared OneDrive files to unauthorized users
How can a Windows Store app let unauthorized users get thumbnails for shared OneDrive files (videos etc.) using the current OneDrive API?
Any ideas?
You need to make a call to the following API:
GET /drive/items/{item-id}/thumbnails/{thumb-id}/{size}/content
This call needs to use authorization and returns a redirect to a cache-safe thumbnail location. You can then use this new url to serve thumbnails to unauthenticated users.
e.g.
Request:
GET https://api.onedrive.com/v1.0/drive/items/D094522DE0B10F6D!152/thumbnails/0/small/content
Authorization: bearer <access token>
Response:
HTTP/1.1 302 Found
Location: https://qg3u2w.bn1302.livefilestore.com/y3m1LKnRaQvGEEhv_GU3mVsewg_-aizIXDaVczGwGFIqtNcVSCihLo7s2mNdUrKicuBnB2sGlSwMQTzQw7v34cHLkchKHL_5YC3IMx1SMcpndtdb9bmQ6y2iG4id0HHgCUlgctvYsDrE24XALwXv2KWRUwCCvDJC4hlkqYgnwGBUSQ
You can now use the link in the Location header to access the thumbnail without signing in. This url will change only if the contents of the file change.
You can read more in the documentation here.
I just figured it out. It is based on the information in this article from Microsoft...
https://learn.microsoft.com/en-ca/onedrive/developer/rest-api/api/driveitem_list_thumbnails?view=odsp-graph-online
... look at the section, "Getting thumbnails while listing DriveItems." It shows you the relevant JSON return structure from a call such as:
GET /me/drive/items/{item-id}/children?$expand=thumbnails
Basically, the JSON return structure gives you string URL's for each of the thumbnail formats. You then create URLSession's to upload these URL's (once you've converted them from String to URL)
Here is an excerpt of code using Swift (Apple):
////////////////////////////////////////////////////////////////////////////////
//
// Download a thumbnail with a URL and label the URLSession with an ID.
//
func downloadThumbnail(url: URL, id: String) {
// Create a URLSession. This is an object that controls the operation or flow
// control with respect to asynchronous operations. It sets the callback delegate
// when the operation is complete.
let urlSession: URLSession = {
//let config = URLSessionConfiguration.default
let config = URLSessionConfiguration.background(withIdentifier: id)
config.isDiscretionary = true
config.sessionSendsLaunchEvents = true
//config.identifier = "file download"
return URLSession(configuration: config, delegate: self as URLSessionDelegate, delegateQueue: OperationQueue.main)
}()
// Create the URLRequest. This is needed so that "Authorization" can be made, as well
// as the actual HTTP command. The url, on initialization, is the command... along
// with the "GET" setting of the httpMethod property.
var request = URLRequest(url: url)
// Set the Authorization header for the request. We use Bearer tokens, so we specify Bearer + the token we got from the result
request.setValue("Bearer \(self.accessToken)", forHTTPHeaderField: "Authorization")
request.httpMethod = "GET"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
// This initiates the asynchronous data task
let backgroundTask = urlSession.downloadTask(with: request)
//backgroundTask.earliestBeginDate = Date().addingTimeInterval(60 * 60)
backgroundTask.countOfBytesClientExpectsToSend = 60
backgroundTask.countOfBytesClientExpectsToReceive = 15 * 1024
backgroundTask.resume()
}
... of course you need to have the correct "accessToken," (shown above) but you also have to have written the generic callback function for URLSession, which is:
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask,
didFinishDownloadingTo location: URL) {
Swift.print("DEBUG: urlSession callback reached")
// This was the identifier that you setup URLSession with
let id = session.configuration.identifier
// "location" is the temporary URL that the thumbnail was downloaded to
let temp = location
// You can convert this URL into any kind of image object. Just Google it!
}
Cheers, Andreas

how to enable SSL connections in alamofire

how to enable ssl connections just as the AFNetworking did:
self.manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:kHostName]];
self.manager.securityPolicy.allowInvalidCertificates = YES;
I had neither username nor password in my case, just a post request like this
https://domain/request
and the parameter:
email=123#abc.com
UPDATED
I had solved this case since I changed the parameter encoding form .JSON to .URL.
What about :
let user = "user"
let password = "password"
Alamofire.request(.GET, "https://httpbin.org/basic-auth/\(user)/\(password)")
.authenticate(user: user, password: password)
.response {(request, response, _, error) in
println(response)
}
From https://github.com/Alamofire/Alamofire.
Invalid HTTPS certificates feature does not seem to be available yet - https://github.com/Alamofire/Alamofire/issues/116 .