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

Add support for Basic authentication #7

Merged
merged 1 commit into from
Sep 28, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
49 changes: 46 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,39 @@ interface LoginCredentials {
password: string;
}

enum ChallengeType {
Basic,
Digest,
Unknown
};

function getAuthType(
challenge: string,
): ChallengeType {
const parts = challenge.split(' ');
let challengeType = ChallengeType.Unknown;

if (parts) {
if (parts[0] === 'Basic') {
challengeType = ChallengeType.Basic;
} else if (parts[0] === 'Digest') {
challengeType = ChallengeType.Digest;
}
}

return challengeType;
}

function getBasicAuthHeader(
credentials: LoginCredentials,
): string {
const auth = Buffer.from(`${credentials.username}:${credentials.password}`).toString('base64');
return [
'Basic',
auth,
].join(' ');
}

function getAuthHeader(
credentials: LoginCredentials,
method: string,
Expand Down Expand Up @@ -144,15 +177,25 @@ async function sendCommand(
request,
response,
} = err;
const challengeHeader = response.headers['www-authenticate'];
if (response.status === 401 && challengeHeader) {
const challengeHeader = response?.headers['www-authenticate'];
if (response?.status === 401) {
if (failCount >= 3) {
throw new Error('Authentication failed. Check credentials');
}

const { username, password } = config;
const credentials = { username, password };
const authHeader = getAuthHeader(credentials, request.method, requestURI, challengeHeader);

const authType = getAuthType(challengeHeader);
let authHeader;
if (authType === ChallengeType.Digest) {
authHeader = getAuthHeader(credentials, request.method, requestURI, challengeHeader);
} else if (authType === ChallengeType.Basic) {
authHeader = getBasicAuthHeader(credentials);
} else {
throw new Error('Authentication failed and the challenge type is unknown.');
}

return sendCommand(
config,
command,
Expand Down