Docker-in-Docker (DinD) capabilities of public runners deactivated. More info

account-settings-modal.component.ts 12.1 KB
Newer Older
Deng, Qian's avatar
Deng, Qian committed
1
import { ChangeDetectorRef } from '@angular/core';
2
// Copyright Project Harbor Authors
wy65701436's avatar
wy65701436 committed
3 4 5 6 7 8 9 10 11 12 13 14
//
// 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.
15 16 17
import { Component, OnInit, ViewChild, AfterViewChecked } from "@angular/core";
import { NgForm } from "@angular/forms";
import { Router, NavigationExtras } from "@angular/router";
18
import { ConfirmationMessage } from '../../shared/confirmation-dialog/confirmation-message';
19

20 21 22 23 24
import { SessionUser } from "../../shared/session-user";
import { SessionService } from "../../shared/session.service";
import { InlineAlertComponent } from "../../shared/inline-alert/inline-alert.component";
import { MessageHandlerService } from "../../shared/message-handler/message-handler.service";
import { SearchTriggerService } from "../../base/global-search/search-trigger.service";
25 26 27 28 29 30
import { AccountSettingsModalService } from './account-settings-modal-service.service';
import {  ConfirmationDialogComponent } from "../../shared/confirmation-dialog/confirmation-dialog.component";
import {
  ConfirmationTargets,
  ConfirmationButtons
} from "../../shared/shared.const";
Yogi_Wang's avatar
Yogi_Wang committed
31 32
import { randomWord } from '../../shared/shared.utils';
import { ResetSecret } from './account';
33 34
import { CopyInputComponent } from "../../../lib/components/push-image/copy-input.component";
import { CommonRoutes } from "../../../lib/entities/shared.const";
35
@Component({
Deng, Qian's avatar
Deng, Qian committed
36 37 38
  selector: "account-settings-modal",
  templateUrl: "account-settings-modal.component.html",
  styleUrls: ["./account-settings-modal.component.scss", "../../common.scss"]
39 40
})
export class AccountSettingsModalComponent implements OnInit, AfterViewChecked {
Deng, Qian's avatar
Deng, Qian committed
41 42 43 44 45 46 47 48 49 50 51 52 53 54
  opened = false;
  staticBackdrop = true;
  originalStaticData: SessionUser;
  account: SessionUser;
  error: any = null;
  emailTooltip = "TOOLTIP.EMAIL";
  mailAlreadyChecked = {};
  isOnCalling = false;
  formValueChanged = false;
  checkOnGoing = false;
  RenameOnGoing = false;
  originAdminName = "admin";
  newAdminName = "admin@harbor.local";
  renameConfirmation = false;
Yogi_Wang's avatar
Yogi_Wang committed
55 56
  showSecretDetail = false;
  resetForms = new ResetSecret();
57
  showGenerateCli: boolean = false;
58
  @ViewChild("confirmationDialog")
59
  confirmationDialogComponent: ConfirmationDialogComponent;
Deng, Qian's avatar
Deng, Qian committed
60 61

  accountFormRef: NgForm;
62
  @ViewChild("accountSettingsFrom", {static: true}) accountForm: NgForm;
Yogi_Wang's avatar
Yogi_Wang committed
63
  @ViewChild("resetSecretFrom", {static: true}) resetSecretFrom: NgForm;
64 65
  @ViewChild(InlineAlertComponent) inlineAlert: InlineAlertComponent;
  @ViewChild("copyInput") copyInput: CopyInputComponent;
Deng, Qian's avatar
Deng, Qian committed
66 67 68 69 70 71

  constructor(
    private session: SessionService,
    private msgHandler: MessageHandlerService,
    private router: Router,
    private searchTrigger: SearchTriggerService,
72
    private accountSettingsService: AccountSettingsModalService,
Deng, Qian's avatar
Deng, Qian committed
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
    private ref: ChangeDetectorRef
  ) {}

  private validationStateMap: any = {
    account_settings_email: true,
    account_settings_full_name: true
  };
  ngOnInit(): void {
    // Value copy
    this.account = Object.assign({}, this.session.getCurrentUser());
    this.originalStaticData = Object.assign({}, this.session.getCurrentUser());
  }

  ngAfterViewChecked(): void {
    if (this.accountFormRef !== this.accountForm) {
      this.accountFormRef = this.accountForm;
      if (this.accountFormRef) {
        this.accountFormRef.valueChanges.subscribe(data => {
          if (this.error) {
            this.error = null;
          }
          this.formValueChanged = true;
          if (this.account.username === this.originAdminName) {
            this.inlineAlert.close();
          }
        });
      }
100
    }
Deng, Qian's avatar
Deng, Qian committed
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
  }

  getValidationState(key: string): boolean {
    return this.validationStateMap[key];
  }

  handleValidation(key: string, flag: boolean): void {
    if (flag) {
      // Checking
      let cont = this.accountForm.controls[key];
      if (cont) {
        this.validationStateMap[key] = cont.valid;
        // Check email existing from backend
        if (cont.valid && key === "account_settings_email") {
          if (
            this.formValueChanged &&
            this.account.email !== this.originalStaticData.email
          ) {
            if (this.mailAlreadyChecked[this.account.email]) {
              this.validationStateMap[key] = !this.mailAlreadyChecked[
                this.account.email
              ].result;
              if (!this.validationStateMap[key]) {
                this.emailTooltip = "TOOLTIP.EMAIL_EXISTING";
              }
              return;
127
            }
Steven Zou's avatar
Steven Zou committed
128

Deng, Qian's avatar
Deng, Qian committed
129 130 131 132
            // Mail changed
            this.checkOnGoing = true;
            this.session
              .checkUserExisting("email", this.account.email)
Yogi_Wang's avatar
Yogi_Wang committed
133
              .subscribe((res: boolean) => {
Deng, Qian's avatar
Deng, Qian committed
134 135 136 137 138 139 140 141
                this.checkOnGoing = false;
                this.validationStateMap[key] = !res;
                if (res) {
                  this.emailTooltip = "TOOLTIP.EMAIL_EXISTING";
                }
                this.mailAlreadyChecked[this.account.email] = {
                  result: res
                }; // Tag it checked
Yogi_Wang's avatar
Yogi_Wang committed
142
              }, error => {
Deng, Qian's avatar
Deng, Qian committed
143 144 145 146
                this.checkOnGoing = false;
                this.validationStateMap[key] = false; // Not valid @ backend
              });
          }
Steven Zou's avatar
Steven Zou committed
147
        }
Deng, Qian's avatar
Deng, Qian committed
148 149 150 151 152
      }
    } else {
      // Reset
      this.validationStateMap[key] = true;
      this.emailTooltip = "TOOLTIP.EMAIL";
Steven Zou's avatar
Steven Zou committed
153
    }
Deng, Qian's avatar
Deng, Qian committed
154
  }
Steven Zou's avatar
Steven Zou committed
155

Deng, Qian's avatar
Deng, Qian committed
156 157 158
  isUserDataChange(): boolean {
    if (!this.originalStaticData || !this.account) {
      return false;
159
    }
Deng, Qian's avatar
Deng, Qian committed
160 161 162 163
    for (let prop in this.originalStaticData) {
      if (this.originalStaticData[prop] !== this.account[prop]) {
        return true;
      }
164
    }
Deng, Qian's avatar
Deng, Qian committed
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
    return false;
  }

  public get isValid(): boolean {
    return (
      this.accountForm &&
      this.accountForm.valid &&
      this.error === null &&
      this.validationStateMap["account_settings_email"]
    ); // backend check is valid as well
  }

  public get showProgress(): boolean {
    return this.isOnCalling;
  }

  public get checkProgress(): boolean {
    return this.checkOnGoing;
  }

  public get canRename(): boolean {
    return (
      this.account &&
      this.account.has_admin_role &&
      this.originalStaticData.username === "admin" &&
      this.account.user_id === 1
    );
  }

  onRename(): void {
    this.account.username = this.newAdminName;
    this.RenameOnGoing = true;
  }

  confirmRename(): void {
    if (this.canRename) {
        this.session
      .updateAccountSettings(this.account)
Yogi_Wang's avatar
Yogi_Wang committed
203
      .subscribe(() => {
Deng, Qian's avatar
Deng, Qian committed
204
        this.session.renameAdmin(this.account)
Yogi_Wang's avatar
Yogi_Wang committed
205
        .subscribe(() => {
Deng, Qian's avatar
Deng, Qian committed
206 207 208
            this.msgHandler.showSuccess("PROFILE.RENAME_SUCCESS");
            this.opened = false;
            this.logOut();
Yogi_Wang's avatar
Yogi_Wang committed
209
        }, error => {
Deng, Qian's avatar
Deng, Qian committed
210
            this.msgHandler.handleError(error);
211
        });
Yogi_Wang's avatar
Yogi_Wang committed
212
      }, error => {
Deng, Qian's avatar
Deng, Qian committed
213 214 215 216 217 218 219
        this.isOnCalling = false;
        this.error = error;
        if (this.msgHandler.isAppLevel(error)) {
          this.opened = false;
          this.msgHandler.handleError(error);
        } else {
          this.inlineAlert.showInlineError(error);
220
        }
Deng, Qian's avatar
Deng, Qian committed
221
      });
222
    }
Deng, Qian's avatar
Deng, Qian committed
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
  }

  // Log out system
  logOut(): void {
    // Naviagte to the sign in route
    // Appending 'signout' means destroy session cache
    let navigatorExtra: NavigationExtras = {
      queryParams: { signout: true }
    };
    this.router.navigate([CommonRoutes.EMBEDDED_SIGN_IN], navigatorExtra);
    // Confirm search result panel is close
    this.searchTrigger.closeSearch(true);
  }

  open() {
    // Keep the initial data for future diff
    this.originalStaticData = Object.assign({}, this.session.getCurrentUser());
    this.account = Object.assign({}, this.session.getCurrentUser());
    this.formValueChanged = false;

    // Confirm inline alert is closed
    this.inlineAlert.close();

    // Clear check history
    this.mailAlreadyChecked = {};

    // Reset validation status
    this.validationStateMap = {
      account_settings_email: true,
      account_settings_full_name: true
    };
254
    this.showGenerateCli = false;
Deng, Qian's avatar
Deng, Qian committed
255 256
    this.opened = true;
  }
257 258

    close() {
Steven Zou's avatar
Steven Zou committed
259 260 261 262
        if (this.formValueChanged) {
            if (!this.isUserDataChange()) {
                this.opened = false;
            } else {
Deng, Qian's avatar
Deng, Qian committed
263 264 265 266 267 268 269 270 271
                if (this.RenameOnGoing) {
                    this.RenameOnGoing = false;
                    this.opened = false;
                } else {
                    // Need user confirmation
                    this.inlineAlert.showInlineConfirmation({
                        message: "ALERT.FORM_CHANGE_CONFIRMATION"
                    });
                }
Steven Zou's avatar
Steven Zou committed
272 273 274 275
            }
        } else {
            this.opened = false;
        }
276 277 278 279 280 281 282
    }

    submit() {
        if (!this.isValid || this.isOnCalling) {
            return;
        }

283
        // Double confirm session is valid
284 285 286 287 288
        let cUser = this.session.getCurrentUser();
        if (!cUser) {
            return;
        }

Deng, Qian's avatar
Deng, Qian committed
289 290 291 292 293 294 295 296
        if (this.RenameOnGoing && !this.renameConfirmation) {
            this.renameConfirmation = true;
            this.inlineAlert.showInlineWarning({
                message: "PROFILE.RENAME_CONFIRM_INFO"
            });
            return;
        }

297 298
        this.isOnCalling = true;

Deng, Qian's avatar
Deng, Qian committed
299 300 301 302 303
        if (this.RenameOnGoing && this.renameConfirmation) {
            this.confirmRename();
        } else {
            this.session
                .updateAccountSettings(this.account)
Yogi_Wang's avatar
Yogi_Wang committed
304
                .subscribe(() => {
Deng, Qian's avatar
Deng, Qian committed
305
                    this.isOnCalling = false;
Steven Zou's avatar
Steven Zou committed
306
                    this.opened = false;
Deng, Qian's avatar
Deng, Qian committed
307
                    this.msgHandler.showSuccess("PROFILE.SAVE_SUCCESS");
Yogi_Wang's avatar
Yogi_Wang committed
308
                }, error => {
Deng, Qian's avatar
Deng, Qian committed
309 310 311 312 313 314 315 316 317 318
                    this.isOnCalling = false;
                    this.error = error;
                    if (this.msgHandler.isAppLevel(error)) {
                        this.opened = false;
                        this.msgHandler.handleError(error);
                    } else {
                        this.inlineAlert.showInlineError(error);
                    }
                });
        }
319 320
    }

Deng, Qian's avatar
Deng, Qian committed
321 322 323
  confirmNo($event: any): void {
    if (this.RenameOnGoing) {
      this.RenameOnGoing = false;
Deng, Qian's avatar
Deng, Qian committed
324
    }
Deng, Qian's avatar
Deng, Qian committed
325 326 327 328 329 330 331 332 333 334
    if (this.renameConfirmation) {
        this.renameConfirmation = false;
    }
  }
  confirmYes($event: any): void {
    if (this.RenameOnGoing) {
      this.RenameOnGoing = false;
    }
    if (this.renameConfirmation) {
        this.renameConfirmation = false;
Steven Zou's avatar
Steven Zou committed
335
    }
Deng, Qian's avatar
Deng, Qian committed
336 337 338
    this.inlineAlert.close();
    this.opened = false;
  }
339 340 341 342 343 344
  onSuccess(event) {
    this.inlineAlert.showInlineSuccess({message: 'PROFILE.COPY_SUCCESS'});
  }
  onError(event) {
    this.inlineAlert.showInlineError({message: 'PROFILE.COPY_ERROR'});
  }
345 346 347 348 349 350 351 352 353 354 355 356 357
  generateCli(userId): void {
    let generateCliMessage = new ConfirmationMessage(
      'PROFILE.CONFIRM_TITLE_CLI_GENERATE',
      'PROFILE.CONFIRM_BODY_CLI_GENERATE',
      '',
      userId,
      ConfirmationTargets.TARGET,
      ConfirmationButtons.CONFIRM_CANCEL);
  this.confirmationDialogComponent.open(generateCliMessage);
  }
  showGenerateCliFn() {
    this.showGenerateCli = !this.showGenerateCli;
  }
Yogi_Wang's avatar
Yogi_Wang committed
358 359 360 361 362 363 364 365 366 367
  confirmGenerate(event): void {
    this.account.oidc_user_meta.secret = randomWord(9);
    this.resetCliSecret(this.account.oidc_user_meta.secret);
  }

  resetCliSecret(secret) {
    let userId = this.account.user_id;
    this.accountSettingsService.saveNewCli(userId, {secret: secret}).subscribe(cliSecret => {
      this.account.oidc_user_meta.secret = secret;
      this.closeReset();
368 369 370 371 372
      this.inlineAlert.showInlineSuccess({message: 'PROFILE.GENERATE_SUCCESS'});
    }, error => {
      this.inlineAlert.showInlineError({message: 'PROFILE.GENERATE_ERROR'});
    });
  }
Yogi_Wang's avatar
Yogi_Wang committed
373 374 375 376 377
  disableChangeCliSecret() {
    return this.resetSecretFrom.invalid || (this.resetSecretFrom.value.input_secret !== this.resetSecretFrom.value.confirm_secret);
  }
  closeReset() {
    this.showSecretDetail = false;
378
    this.showGenerateCliFn();
Yogi_Wang's avatar
Yogi_Wang committed
379 380
    this.resetSecretFrom.resetForm(new ResetSecret());
  }
Deng, Qian's avatar
Deng, Qian committed
381
}