"use strict";
/*
 * Copyright © 2020 Atomist, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.GitHubCredentialsResolver = void 0;
const configuration_1 = require("@atomist/automation-client/lib/configuration");
const decorators_1 = require("@atomist/automation-client/lib/decorators");
const RepoId_1 = require("@atomist/automation-client/lib/operations/common/RepoId");
const _ = require("lodash");
const types_1 = require("../../../typings/types");
let GitHubCredentialsResolver = class GitHubCredentialsResolver {
    async eventHandlerCredentials(context, id) {
        return this.credentials([
            obtainTokenFromConfiguration(this),
            ObtainTokenFromIncomingMessage,
            ObtainTokenFromGitHubApp,
            ObtainTokenFromProvider,
        ], context, id);
    }
    async commandHandlerCredentials(context, id) {
        return this.credentials([
            ObtainTokenFromIncomingMessage,
            obtainTokenFromConfiguration(this),
            ObtainTokenFromGitHubApp,
            ObtainTokenFromProvider,
        ], context, id);
    }
    async credentials(obtainTokens, context, id) {
        for (const obtainToken of obtainTokens) {
            const token = await obtainToken(context, id);
            if (hasToken(token)) {
                return { token };
            }
        }
        throw new Error("No GitHub token available! Please add a token to the SDM configuration at 'sdm.github.token' "
            + "or authenticate the GitHub SCM provider from the web app or CLI.");
    }
};
__decorate([
    decorators_1.Secret(decorators_1.Secrets.OrgToken),
    __metadata("design:type", String)
], GitHubCredentialsResolver.prototype, "orgToken", void 0);
GitHubCredentialsResolver = __decorate([
    decorators_1.Parameters()
], GitHubCredentialsResolver);
exports.GitHubCredentialsResolver = GitHubCredentialsResolver;
/**
 * Obtain a org or user token from the incoming event or command invocation
 */
const ObtainTokenFromIncomingMessage = async (ctx) => {
    // Try to obtain the token from the incoming event or command
    const actx = ctx;
    if (!!actx.trigger && !!actx.trigger.secrets) {
        let secret = actx.trigger.secrets.find(s => s.uri === decorators_1.Secrets.OrgToken);
        if (secret && hasToken(secret.value)) {
            return secret.value;
        }
        secret = actx.trigger.secrets.find(s => s.uri.startsWith(decorators_1.Secrets.UserToken));
        if (secret && hasToken(secret.value)) {
            return secret.value;
        }
    }
    return undefined;
};
/**
 * Obtain a token from an SCMProvider
 */
const ObtainTokenFromProvider = async (ctx, id) => {
    // Check the graph to see if we have a token on the provider
    if (!!id && (id.providerType === RepoId_1.ProviderType.github_com)) {
        const token = await fetchTokenByProviderType(types_1.ProviderType.github_com, ctx);
        if (hasToken(token)) {
            return token;
        }
    }
    return undefined;
};
/**
 * Obtain a token from an GitHubAppInstallation
 */
const ObtainTokenFromGitHubApp = async (ctx, id) => {
    // Check the graph to see if we have a token on the GitHubAppInstallation
    if (!!id && (id.providerType === RepoId_1.ProviderType.github_com)) {
        const token = await fetchTokenByGitHubAppName(id.owner, ctx);
        if (hasToken(token)) {
            return token;
        }
    }
    return undefined;
};
/**
 * Obtain a token from the SDM configuration
 */
function obtainTokenFromConfiguration(resolver) {
    return async () => {
        if (hasToken(configuration_1.configurationValue("token", "null"))) {
            return configuration_1.configurationValue("token");
        }
        else if (hasToken(configuration_1.configurationValue("sdm.github.token", "null"))) {
            return configuration_1.configurationValue("sdm.github.token");
        }
        return undefined;
    };
}
function hasToken(token) {
    if (!token) {
        return false;
        // "null" as string is being sent when the orgToken can't be determined by the api
    }
    else if (token === "null" || token === "undefined") {
        return false;
    }
    return true;
}
async function fetchTokenByProviderType(providerType, ctx) {
    const provider = await ctx.graphClient.query({
        name: "ScmProviderByType",
        variables: {
            providerType,
        },
    });
    return _.get(provider, "SCMProvider[0].credential.secret");
}
async function fetchTokenByGitHubAppName(owner, ctx) {
    const app = await ctx.graphClient.query({
        name: "GitHubAppInstallationByOwner",
        variables: {
            name: owner,
        },
    });
    return _.get(app, "GitHubAppInstallation[0].token.secret");
}
//# sourceMappingURL=GitHubCredentialsResolver.js.map