Skip to content
Open
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
56 changes: 39 additions & 17 deletions lib/transport.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import co from 'co';
import querystring from 'querystring';
import { AuthCalc } from 'httpauth';

import XMLHttpRequest from './xmlhttprequest';

Expand All @@ -24,12 +25,19 @@ export class Transport {
send() {}
}

/*
Standard HTTP authentication
- supports both Basic and Digest authentication
- chooses the method automatically
- works better with CORS (passes Authorization directly)
*/
export class Basic extends Transport {
/**
* @param {dav.Credentials} credentials user authorization.
*/
constructor(credentials) {
super(credentials);
this.auth = new AuthCalc(this.credentials.username, this.credentials.password);
}

send(request, url, options) {
Expand All @@ -39,25 +47,39 @@ export class Basic extends Transport {
let transformResponse = request.transformResponse;
let onerror = request.onerror;

let xhr = new XMLHttpRequest();
if (sandbox) sandbox.add(xhr);
xhr.open(
request.method,
url,
true /* async */,
this.credentials.username,
this.credentials.password
);
let result;
let retryCnt = 1;
while (retryCnt >= 0) {
retryCnt--;
let xhr = new XMLHttpRequest();
if (sandbox) sandbox.add(xhr);
xhr.open(
request.method,
url,
true /* async */
//WITHOUT login and password
//NO "withCredentials"
);

if (transformRequest) transformRequest(xhr);
this.auth.sign(xhr.request, {url: url, type: request.method, data: request.requestData});

let result;
try {
yield xhr.send(request.requestData);
result = transformResponse ? transformResponse(xhr) : xhr;
} catch (error) {
if (onerror) onerror(error);
throw error;
if (transformRequest) transformRequest(xhr);

try {
yield xhr.send(request.requestData);
result = transformResponse ? transformResponse(xhr) : xhr;
break; //of repeat loop
} catch (error) {
console.debug("dav.Transport.Basic::OnError: "+xhr.request.status);
//Authentication required? Reinitialize the auth context
if (xhr.request.status === 401 || xhr.request.status === 407) {
console.debug("Reinitializing the auth context...");
this.auth.updateServerResponse(xhr.request);
continue; //try again
}
if (onerror) onerror(error);
throw error;
}
}

return result;
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
"@babel/polyfill": "^7.0.0",
"co": "^4.6.0",
"debug": "^4.1.1",
"httpauth": "github:himselfv/httpauth",
"xmldom": "^0.1.27",
"xmlhttprequest": "^1.8.0"
},
Expand Down