All files / app/page/user user.component.ts

37.25% Statements 38/102
25% Branches 11/44
21.87% Functions 7/32
34.48% Lines 30/87

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 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 100 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 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 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 203 204 205 206 207 208 209  1x             1x 1x 1x   1x             1x 1x 1x               5x 1x 1x         1x   1x 1x     1x 1x 1x 1x 1x 1x 1x 1x   1x 1x                         1x 1x 1x                                                 1x 1x                               5x                                                                                                                                                                                                      
import { HttpErrorResponse } from '@angular/common/http';
import { Component, HostBinding, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { ReactiveFormsModule, UntypedFormBuilder, UntypedFormControl, UntypedFormGroup } from '@angular/forms';
import { Router, RouterLink } from '@angular/router';
import { defer, uniq } from 'lodash-es';
import { autorun, IReactionDisposer, runInAction } from 'mobx';
import { MobxAngularModule } from 'mobx-angular';
import { catchError, forkJoin, Observable, of, switchMap, throwError } from 'rxjs';
import { SettingsComponent } from '../../component/settings/settings.component';
import { LimitWidthDirective } from '../../directive/limit-width.directive';
import { userForm, UserFormComponent } from '../../form/user/user.component';
import { HasChanges } from '../../guard/pending-changes.guard';
import { isDeletorTag, tagDeleteNotice } from '../../mods/delete';
import { AdminService } from '../../service/admin.service';
import { ProfileService } from '../../service/api/profile.service';
import { UserService } from '../../service/api/user.service';
import { ConfigService } from '../../service/config.service';
import { ModService } from '../../service/mod.service';
import { Store } from '../../store/store';
import { scrollToFirstInvalid } from '../../util/form';
import { printError } from '../../util/http';
import { prefix, setPublic } from '../../util/tag';
 
@Component({
  selector: 'app-user-page',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.scss'],
  imports: [MobxAngularModule, RouterLink, SettingsComponent, ReactiveFormsModule, LimitWidthDirective, UserFormComponent]
})
export class UserPage implements OnInit, OnDestroy, HasChanges {
  private disposers: IReactionDisposer[] = [];
  @HostBinding('class') css = 'full-page-form';
 
  @ViewChild('form')
  userForm!: UserFormComponent;
 
  submitted = false;
  profileForm: UntypedFormGroup;
  serverError: string[] = [];
  externalErrors: string[] = [];
 
  constructor(
    private mod: ModService,
    private admin: AdminService,
    public config: ConfigService,
    public router: Router,
    public store: Store,
    private profiles: ProfileService,
    private users: UserService,
    private fb: UntypedFormBuilder,
  ) {
    mod.setTitle($localize`Create Profile`);
    this.profileForm = fb.group({
      active: [true],
      password: [''],
      role: [''],
      user: userForm(fb),
    });
  }
 
  saveChanges() {
    return !this.profileForm?.dirty;
  }
 
  ngOnInit(): void {
    this.disposers.push(autorun(() => {
      if (!this.store.view.tag) {
        runInAction(() => this.store.view.selectedUser = undefined);
      } else E{
        const tag = this.store.view.localTag + this.store.account.origin;
        this.users.get(tag).pipe(
          catchError(() => of(undefined)),
        ).subscribe(user => runInAction(() => {
          this.store.view.selectedUser = user;
          if (user) {
            this.profileForm.setControl('user', userForm(this.fb, true));
            defer(() => this.userForm.setUser(user));
          } else {
            this.profileForm.setControl('user', userForm(this.fb, false));
            defer(() => this.userForm.setUser({
              tag: this.store.view.localTag,
              origin: this.store.view.origin,
              readAccess: this.admin.readAccess.map(t => setPublic(prefix(t, this.store.view.localTag))),
              writeAccess: this.admin.writeAccess.map(t => setPublic(prefix(t, this.store.view.localTag))),
            }));
          }
        }));
      }
    }));
  }
 
  ngOnDestroy() {
    for (const dispose of this.disposers) dispose();
    this.disposers.length = 0;
  }
 
  get active() {
    return this.profileForm.get('active') as UntypedFormControl;
  }
 
  get password() {
    return this.profileForm.get('password') as UntypedFormControl;
  }
 
  get role() {
    return this.profileForm.get('role') as UntypedFormControl;
  }
 
  get user() {
    return this.profileForm.get('user') as UntypedFormGroup;
  }
 
  get tag() {
    return this.user.get('tag') as UntypedFormGroup;
  }
 
  save() {
    this.serverError = [];
    this.submitted = true;
    this.profileForm.markAllAsTouched();
    if (!this.profileForm.valid) {
      scrollToFirstInvalid();
      return;
    }
    const updates = {
      ...(this.store.view.selectedUser || {}),
      ...this.user.value,
      tag: this.store.view.localTag,
      origin: this.store.account.origin,
      readAccess: uniq([...this.user.value.readAccess, ...this.user.value.notifications]),
    };
    delete updates.notifications;
    this.externalErrors = [];
    try {
      if (!updates.external) delete updates.external;
      if (updates.external) updates.external = JSON.parse(updates.external);
    } catch (e: any) {
      this.externalErrors.push(e.message);
    }
    const entities: Observable<any>[] = [
      (this.store.view.selectedUser
        ? this.users.update(updates)
        : this.users.create(updates)).pipe(
        catchError((res: HttpErrorResponse) => {
          this.serverError.push(...printError(res));
          return throwError(() => res);
        }),
      )
    ];
    if (this.config.scim) {
      const profile = {
        tag: this.store.view.localTag + this.store.account.origin,
        password: this.profileForm.value.password,
        role: this.profileForm.value.role,
      };
      if (this.store.view.selectedUser) {
        if (this.password.touched) {
          entities.push(this.profiles.changePassword(profile));
        }
        if (this.active.touched) {
          entities.push(this.active.value ?
            this.profiles.activate(profile.tag) :
            this.profiles.deactivate(profile.tag));
        }
        if (this.role.touched) {
          entities.push(this.profiles.changeRole(profile));
        }
      } else {
        entities.push(this.profiles.create(profile).pipe(
          catchError((res: HttpErrorResponse) => {
            this.serverError.push(...printError(res));
            return throwError(() => res);
          }),
        ));
      }
    }
    forkJoin(entities).subscribe(() => {
      this.profileForm.markAsPristine();
      this.router.navigate(['/tag', this.tag.value + this.store.account.origin])
    });
  }
 
  delete() {
    // TODO: Better dialogs
    if (confirm($localize`Are you sure you want to delete this user?`)) {
      const deleteNotice = !isDeletorTag(this.store.view.selectedUser!.tag) && this.admin.getPlugin('plugin/delete')
        ? this.users.create(tagDeleteNotice(this.store.view.selectedUser!))
        : of(null);
      this.users.delete(this.store.view.localTag + this.store.account.origin).pipe(
        switchMap(() => deleteNotice),
        catchError((err: HttpErrorResponse) => {
          this.serverError = printError(err);
          return throwError(() => err);
        }),
      ).subscribe(() => {
        this.router.navigate(['/tag', this.store.view.localTag + this.store.account.origin]);
      });
    }
  }
 
  setTag(tag: string) {
    this.router.navigate(['/user', tag]);
  }
 
  clear() {
    this.router.navigateByUrl('/user');
  }
}