Advertisement
Guest User

Untitled

a guest
Apr 13th, 2017
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.14 KB | None | 0 0
  1. import { Component, OnInit, OnDestroy } from '@angular/core';
  2. import { FormGroup, FormControl, FormBuilder, Validators, ValidatorFn, AbstractControl } from '@angular/forms';
  3. import { ActivatedRoute, Params, Router } from '@angular/router';
  4. import { Observable } from 'rxjs/Observable';
  5. import { Subscription } from 'rxjs/Subscription';
  6.  
  7. import { User } from './user';
  8. import { Address } from './address';
  9. import { UserService } from './user.service';
  10. import { RoleService } from './role.service';
  11. import { Role } from './role';
  12.  
  13. @Component({
  14. selector: 'app-user-management',
  15. templateUrl: './user-form.component.html',
  16. styleUrls: ['./user-form.component.scss']
  17. })
  18. export class UserFormComponent implements OnInit, OnDestroy {
  19. userForm: FormGroup;
  20. user: User;
  21. roles: Observable<Role[]>;
  22. 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,}))$/;
  23. private readonly fields: string[] = [
  24. 'id', 'orgId', 'username', 'password', 'firstName',
  25. 'lastName', 'email', 'phoneNumber', 'website',
  26. 'language', 'address', 'roles', 'enabled',
  27. 'accountExpired', 'accountLocked', 'credentialsExpired', 'version'
  28. ];
  29. private formValidation = {
  30. username: {
  31. validators: Validators.required,
  32. formErrors: [],
  33. messages: {
  34. required: 'Username is required.',
  35. existedUsername: 'Username has been used. Please choose another one.'
  36. }
  37. },
  38. password: {
  39. validators: [this.passwordValidator()],
  40. formErrors: [],
  41. messages: {
  42. required: 'Password is required.',
  43. validPasswordFormat: `Password should contain at least 8 characters,
  44. one Uppercase Alphabet, one Lowercase Alphabet and one Number.`
  45. }
  46. },
  47. firstName: {
  48. validators: Validators.required,
  49. formErrors: [],
  50. messages: {
  51. required: 'First Name is required.'
  52. }
  53. },
  54. lastName: {
  55. validators: Validators.required,
  56. formErrors: [],
  57. messages: {
  58. required: 'Last Name is required.'
  59. }
  60. },
  61. email: {
  62. validators: [
  63. Validators.required,
  64. Validators.pattern(this.emailRex)
  65. ],
  66. formErrors: [],
  67. messages: {
  68. required: 'Email is required.',
  69. pattern: 'Please input a valid email.'
  70. }
  71. }
  72. };
  73. private sub: Subscription;
  74.  
  75. constructor(
  76. private route: ActivatedRoute,
  77. private router: Router,
  78. private userService: UserService,
  79. private roleService: RoleService,
  80. private fb: FormBuilder
  81. ) { }
  82.  
  83. ngOnInit() {
  84. this.roles = this.roleService.roles;
  85.  
  86. this.sub = this.route.params.subscribe(params => {
  87. const userId = params['uid'];
  88. const orgId = params['orgId'];
  89.  
  90. if (userId === 'add') {
  91. this.user = {
  92. id: -1,
  93. orgId,
  94. username: '',
  95. password: '',
  96. firstName: '',
  97. lastName: '',
  98. email: '',
  99. phoneNumber: '',
  100. website: '',
  101. language: '',
  102. address: <Address>{
  103. address: '',
  104. city: '',
  105. province: '',
  106. country: '',
  107. postalCode: ''
  108. },
  109. version: null,
  110. roles: [],
  111. enabled: false,
  112. accountExpired: false,
  113. accountLocked: false,
  114. credentialsExpired: false
  115. };
  116. this.formValidation.password.validators.push(Validators.required);
  117. this.formValidation.password.validators.push(this.passwordValidator());
  118. this.createForm();
  119. } else {
  120. this.userService.getUser(+userId)
  121. .subscribe(user => {
  122. this.user = user;
  123. this.createForm();
  124. });
  125. }
  126. });
  127. }
  128.  
  129. createForm() {
  130. const formData = this.fields
  131. .reduce((result, key) => {
  132. let value;
  133. let validation = this.formValidation[key];
  134.  
  135. let setValue = () => {
  136. if (key === 'roles') {
  137. let userRoles = this.user.roles[0];
  138.  
  139. if (userRoles !== undefined) {
  140. value = userRoles.id;
  141. } else {
  142. value = -1;
  143. }
  144. } else if (key === 'password') {
  145. value = '';
  146. } else {
  147. value = this.user[key];
  148. }
  149. };
  150.  
  151. let setResult = () => {
  152. if (key === 'address') {
  153. result[key] = this.createAddress();
  154. } else if (validation === undefined) {
  155. result[key] = [value];
  156. } else {
  157. result[key] = [value, validation.validators];
  158. }
  159. };
  160. setValue();
  161. setResult();
  162. return result;
  163. }, {});
  164.  
  165. this.userForm = this.fb.group(formData);
  166. this.userForm.valueChanges.subscribe(data => this.onValueChanged());
  167. }
  168.  
  169. onValueChanged() {
  170. if (!this.userForm) { return; }
  171. const form = this.userForm;
  172. for (const field in this.formValidation) {
  173. if (this.formValidation.hasOwnProperty(field)) {
  174. this.formValidation[field].formErrors = [];
  175. const control = form.get(field);
  176. if (control && control.dirty && !control.valid) {
  177. const messages = this.formValidation[field].messages;
  178. for (const key in control.errors) {
  179. if (control.errors.hasOwnProperty(key)) {
  180. this.formValidation[field].formErrors.push(messages[key]);
  181. }
  182. }
  183. }
  184. }
  185. }
  186. }
  187.  
  188. createAddress() {
  189. return this.fb.group({
  190. address: [this.user.address.address],
  191. city: [this.user.address.city],
  192. province: [this.user.address.province],
  193. country: [this.user.address.country],
  194. postalCode: [this.user.address.postalCode]
  195. });
  196. }
  197.  
  198. private errorHandler(error) {
  199. let errObj = error.json();
  200. if (errObj.status === 500 && errObj.code === 5001) {
  201. let fieldValidation = this.formValidation['username'];
  202. fieldValidation.formErrors.push(fieldValidation.messages.existedUsername);
  203. }
  204. }
  205.  
  206. onSubmit({ value, valid }: { value: User, valid: boolean }) {
  207. if (!valid) {
  208. return;
  209. }
  210.  
  211. this.roles.subscribe(roles => {
  212. const roleId = +value.roles;
  213. if (roleId >= 0) {
  214. value.roles = [roles.find(r => r.id === roleId)];
  215. } else {
  216. value.roles = [];
  217. }
  218.  
  219. value.orgId = +value.orgId;
  220. value.password = btoa(value.password);
  221.  
  222. if (value.id >= 0) {
  223. this.userService.updateUser(value)
  224. .subscribe(() => {}, error => this.errorHandler);
  225. } else {
  226. this.userService.addUser(value)
  227. .subscribe(() => {
  228. // Should navigate to its parent organization
  229. this.router.navigate(['../..'], { relativeTo: this.route });
  230. }, error => this.errorHandler);
  231. }
  232. });
  233. }
  234.  
  235. ngOnDestroy() {
  236. this.sub.unsubscribe();
  237. }
  238.  
  239. private passwordValidator(): ValidatorFn {
  240. return (control: AbstractControl): { [key: string]: any } => {
  241. const password = control.value as string;
  242. if (password.length === 0) {
  243. return null;
  244. }
  245.  
  246. const valid = password.length >= 8
  247. && !!password.match(/\d/) // has number
  248. && !!password.match(/[A-Z]/) // has uppercase
  249. && !!password.match(/[a-z]/) // has lowercase
  250. ;
  251. return !valid ? { 'validPasswordFormat': { password } } : null;
  252. };
  253. }
  254.  
  255. onDelete() {
  256. const id = +this.userForm.controls['id'].value;
  257. this.userService.deleteUser(id)
  258. .subscribe(() => {
  259. this.router.navigate(['../..'], { relativeTo: this.route });
  260. });
  261. }
  262. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement