var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
import '@iotize/tap/service/impl/group';
import '@iotize/tap/service/impl/interface';
import { debug } from './debug';
import { hashLoginPassword } from './utility';
const TAG = 'BasicAuth';
export class BasicAuth {
    constructor(tap, options = {
        hashPassword: false,
    }) {
        this.tap = tap;
        this.options = options;
    }
    get hashPassword() {
        var _a;
        return ((_a = this.options) === null || _a === void 0 ? void 0 : _a.hashPassword) || false;
    }
    /**
     * Tap login
     *
     */
    login(params) {
        return __awaiter(this, void 0, void 0, function* () {
            const { username, password } = params;
            let response;
            if (this.hashPassword) {
                debug(TAG, `Using hash password login`);
                response = yield this.tap.service.interface.loginWithHash({
                    username,
                    password: hashLoginPassword(password),
                });
            }
            else {
                debug(TAG, `Using regular login`);
                response = yield this.tap.service.interface.login({
                    username,
                    password,
                });
            }
            response.successful();
            return {};
        });
    }
    logout() {
        return __awaiter(this, void 0, void 0, function* () {
            (yield this.tap.service.interface.logout()).successful();
        });
    }
    /**
     * Change password for the groupId
     * @param newPassword the new password for the userId
     * @param userId the user id for which we want to change the password
     */
    changePassword(newPassword, userId) {
        return __awaiter(this, void 0, void 0, function* () {
            if (this.hashPassword) {
                const passwordBytes = hashLoginPassword(newPassword);
                (yield this.tap.service.group.changePasswordKey(userId, passwordBytes)).successful();
            }
            else {
                (yield this.tap.service.group.changePassword(userId, newPassword)).successful();
            }
        });
    }
}
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYmFzaWMtYXV0aC5qcyIsInNvdXJjZVJvb3Qi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