Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { Component, OnInit, OnDestroy } from '@angular/core';
- import { FormGroup, FormControl, FormBuilder, Validators, ValidatorFn, AbstractControl } from '@angular/forms';
- import { ActivatedRoute, Params, Router } from '@angular/router';
- import { Observable } from 'rxjs/Observable';
- import { Subscription } from 'rxjs/Subscription';
- import { User } from './user';
- import { Address } from './address';
- import { UserService } from './user.service';
- import { RoleService } from './role.service';
- import { Role } from './role';
- @Component({
- selector: 'app-user-management',
- templateUrl: './user-form.component.html',
- styleUrls: ['./user-form.component.scss']
- })
- export class UserFormComponent implements OnInit, OnDestroy {
- userForm: FormGroup;
- user: User;
- roles: Observable<Role[]>;
- private readonly emailRex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
- private readonly fields: string[] = [
- 'id', 'orgId', 'username', 'password', 'firstName',
- 'lastName', 'email', 'phoneNumber', 'website',
- 'language', 'address', 'roles', 'enabled',
- 'accountExpired', 'accountLocked', 'credentialsExpired', 'version'
- ];
- private formValidation = {
- username: {
- validators: Validators.required,
- formErrors: [],
- messages: {
- required: 'Username is required.',
- existedUsername: 'Username has been used. Please choose another one.'
- }
- },
- password: {
- validators: [this.passwordValidator()],
- formErrors: [],
- messages: {
- required: 'Password is required.',
- validPasswordFormat: `Password should contain at least 8 characters,
- one Uppercase Alphabet, one Lowercase Alphabet and one Number.`
- }
- },
- firstName: {
- validators: Validators.required,
- formErrors: [],
- messages: {
- required: 'First Name is required.'
- }
- },
- lastName: {
- validators: Validators.required,
- formErrors: [],
- messages: {
- required: 'Last Name is required.'
- }
- },
- email: {
- validators: [
- Validators.required,
- Validators.pattern(this.emailRex)
- ],
- formErrors: [],
- messages: {
- required: 'Email is required.',
- pattern: 'Please input a valid email.'
- }
- }
- };
- private sub: Subscription;
- constructor(
- private route: ActivatedRoute,
- private router: Router,
- private userService: UserService,
- private roleService: RoleService,
- private fb: FormBuilder
- ) { }
- ngOnInit() {
- this.roles = this.roleService.roles;
- this.sub = this.route.params.subscribe(params => {
- const userId = params['uid'];
- const orgId = params['orgId'];
- if (userId === 'add') {
- this.user = {
- id: -1,
- orgId,
- username: '',
- password: '',
- firstName: '',
- lastName: '',
- email: '',
- phoneNumber: '',
- website: '',
- language: '',
- address: <Address>{
- address: '',
- city: '',
- province: '',
- country: '',
- postalCode: ''
- },
- version: null,
- roles: [],
- enabled: false,
- accountExpired: false,
- accountLocked: false,
- credentialsExpired: false
- };
- this.formValidation.password.validators.push(Validators.required);
- this.formValidation.password.validators.push(this.passwordValidator());
- this.createForm();
- } else {
- this.userService.getUser(+userId)
- .subscribe(user => {
- this.user = user;
- this.createForm();
- });
- }
- });
- }
- createForm() {
- const formData = this.fields
- .reduce((result, key) => {
- let value;
- let validation = this.formValidation[key];
- let setValue = () => {
- if (key === 'roles') {
- let userRoles = this.user.roles[0];
- if (userRoles !== undefined) {
- value = userRoles.id;
- } else {
- value = -1;
- }
- } else if (key === 'password') {
- value = '';
- } else {
- value = this.user[key];
- }
- };
- let setResult = () => {
- if (key === 'address') {
- result[key] = this.createAddress();
- } else if (validation === undefined) {
- result[key] = [value];
- } else {
- result[key] = [value, validation.validators];
- }
- };
- setValue();
- setResult();
- return result;
- }, {});
- this.userForm = this.fb.group(formData);
- this.userForm.valueChanges.subscribe(data => this.onValueChanged());
- }
- onValueChanged() {
- if (!this.userForm) { return; }
- const form = this.userForm;
- for (const field in this.formValidation) {
- if (this.formValidation.hasOwnProperty(field)) {
- this.formValidation[field].formErrors = [];
- const control = form.get(field);
- if (control && control.dirty && !control.valid) {
- const messages = this.formValidation[field].messages;
- for (const key in control.errors) {
- if (control.errors.hasOwnProperty(key)) {
- this.formValidation[field].formErrors.push(messages[key]);
- }
- }
- }
- }
- }
- }
- createAddress() {
- return this.fb.group({
- address: [this.user.address.address],
- city: [this.user.address.city],
- province: [this.user.address.province],
- country: [this.user.address.country],
- postalCode: [this.user.address.postalCode]
- });
- }
- private errorHandler(error) {
- let errObj = error.json();
- if (errObj.status === 500 && errObj.code === 5001) {
- let fieldValidation = this.formValidation['username'];
- fieldValidation.formErrors.push(fieldValidation.messages.existedUsername);
- }
- }
- onSubmit({ value, valid }: { value: User, valid: boolean }) {
- if (!valid) {
- return;
- }
- this.roles.subscribe(roles => {
- const roleId = +value.roles;
- if (roleId >= 0) {
- value.roles = [roles.find(r => r.id === roleId)];
- } else {
- value.roles = [];
- }
- value.orgId = +value.orgId;
- value.password = btoa(value.password);
- if (value.id >= 0) {
- this.userService.updateUser(value)
- .subscribe(() => {}, error => this.errorHandler);
- } else {
- this.userService.addUser(value)
- .subscribe(() => {
- // Should navigate to its parent organization
- this.router.navigate(['../..'], { relativeTo: this.route });
- }, error => this.errorHandler);
- }
- });
- }
- ngOnDestroy() {
- this.sub.unsubscribe();
- }
- private passwordValidator(): ValidatorFn {
- return (control: AbstractControl): { [key: string]: any } => {
- const password = control.value as string;
- if (password.length === 0) {
- return null;
- }
- const valid = password.length >= 8
- && !!password.match(/\d/) // has number
- && !!password.match(/[A-Z]/) // has uppercase
- && !!password.match(/[a-z]/) // has lowercase
- ;
- return !valid ? { 'validPasswordFormat': { password } } : null;
- };
- }
- onDelete() {
- const id = +this.userForm.controls['id'].value;
- this.userService.deleteUser(id)
- .subscribe(() => {
- this.router.navigate(['../..'], { relativeTo: this.route });
- });
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement