Advertisement
Guest User

Untitled

a guest
Jul 21st, 2016
182
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import {Component, OnInit} from "@angular/core";
  2. import { AuthService } from "../../shared/auth.service";
  3.  
  4. import {User} from "../../shared/user.interface";
  5. import {ROUTER_DIRECTIVES} from "@angular/router";
  6. import {UserItemComponent} from "./user-item.component";
  7. import {PaginatePipe, PaginationControlsCmp, PaginationService} from 'ng2-pagination';
  8.  
  9.  
  10. @Component({
  11.     moduleId: module.id,
  12.     selector: 'rb-users-list',
  13.     templateUrl: 'users-list.component.html',
  14.     directives: [UserItemComponent, ROUTER_DIRECTIVES, PaginationControlsCmp],
  15.     pipes: [PaginatePipe],
  16.     providers: [AuthService, PaginationService, UserItemComponent]
  17.  
  18. })
  19. export class UsersListComponent implements OnInit {
  20.     users: User[] = [];
  21.  
  22.     constructor(private authService: AuthService) {}
  23.  
  24.     ngOnInit() {
  25.         this.getUsers();
  26.     }
  27.  
  28.     getNotification(evt) {
  29.         if(evt){
  30.             this.getUsers();
  31.             console.log('Pobrano użytkowników');
  32.         }
  33.     }
  34.  
  35.  
  36.     getUsers() {
  37.         //noinspection TypeScriptUnresolvedFunction
  38.         this.authService.getDataUsers();
  39.         this.authService.usersChanged.subscribe(
  40.             (data: User[]) => {
  41.                 this.users = data;
  42.             }
  43.         );
  44.  
  45.     }
  46. }
  47.  
  48.  
  49.  
  50.  
  51.  
  52. -------UserListComponent html-------
  53. <div class="row">
  54.     <div class="col-xs-12">
  55.         <a class="btn btn-success" [routerLink]="['new']">New user</a>
  56. </div>
  57. <div class="row">
  58.     <div class="col-xs-12">
  59.         <ul class="list-group">
  60.             <rb-user-item (notifyParent)="getNotification($event)" *ngFor="let user of users | paginate: { itemsPerPage: 3, currentPage: page }; let i = index" [user]="user" [userId]="i"></rb-user-item>
  61.         </ul>
  62.         <div class="is-text-centered">
  63.             <pagination-controls (pageChange)="page = $event"></pagination-controls>
  64.         </div>
  65.     </div>
  66. </div>
  67.  
  68.  
  69.  
  70.  
  71.  
  72.  
  73. import { Component, OnInit, OnDestroy } from '@angular/core';
  74. import { ActivatedRoute, Router } from "@angular/router";
  75. import { Subscription } from "rxjs/Rx";
  76. import {
  77.     FormArray,
  78.     FormGroup,
  79.     FormControl,
  80.     Validators,
  81.     FormBuilder,
  82.     REACTIVE_FORM_DIRECTIVES
  83. } from "@angular/forms";
  84. import {User} from "../../shared/user.interface";
  85. import {AuthService} from "../../shared/auth.service";
  86.  
  87.  
  88. @Component({
  89.     moduleId: module.id,
  90.     selector: 'rb-user-edit',
  91.     templateUrl: 'user-edit.component.html',
  92.     styles: [],
  93.     directives: [REACTIVE_FORM_DIRECTIVES]
  94. })
  95. export class UserEditComponent implements OnInit, OnDestroy {
  96.     userForm: FormGroup;
  97.  
  98.     error = false;
  99.     errorMessage = '';
  100.     errors: any;
  101.     errorName: string;
  102.     errorEmail: string;
  103.     private userIndex: number;
  104.     private user: User;
  105.     private isNew = true;
  106.     private subscription: Subscription;
  107.     private formLoaded = false;
  108.  
  109.  
  110.     constructor(private route: ActivatedRoute,
  111.                 private authService: AuthService,
  112.                 private formBuilder: FormBuilder,
  113.                 private router: Router) {}
  114.  
  115.     ngOnInit() {
  116.  
  117.         this.subscription = this.route.params.subscribe(
  118.             (params: any) => {
  119.                 if (params.hasOwnProperty('id')) {
  120.                     this.isNew = false;
  121.                     this.userIndex = +params['id'];
  122.                     //noinspection TypeScriptUnresolvedFunction
  123.                     this.authService.getUser(this.userIndex).subscribe(
  124.                         data => {
  125.                             this.user = data;
  126.                             this.formLoaded = true;
  127.                         }
  128.                     );
  129.                 } else {
  130.                     this.isNew = true;
  131.                     this.user = null;
  132.                 }
  133.  
  134.             }
  135.         );
  136.         this.initForm(this.formLoaded);
  137.     }
  138.  
  139.     onSubmit() {
  140.         const newUser = this.userForm.value;
  141.         newUser.id = this.userIndex;
  142.         if (this.isNew) {
  143.             this.authService.signupUserAdmin(this.userForm.value).subscribe(
  144.                 data => {
  145.                     this.errors = data;
  146.                     if( !this.errors.success ){
  147.                         this.errorName = this.errors.name;
  148.                         this.errorEmail = this.errors.email;
  149.                     }
  150.                     else{
  151.                         this.errorName = "";
  152.                         this.errorEmail = "";
  153.                         this.navigateBack();
  154.                     }
  155.                 }
  156.             );
  157.         } else {
  158.             this.authService.editUser(newUser).subscribe(
  159.                 data => {
  160.                     this.errors = data;
  161.                     if( !this.errors.success ){
  162.                         this.errorName = this.errors.name;
  163.                         this.errorEmail = this.errors.email;
  164.                     }
  165.                     else{
  166.                         this.errorName = "";
  167.                         this.errorEmail = "";
  168.                         this.navigateBack();
  169.                     }
  170.                 }
  171.             );
  172.         }
  173.     }
  174.  
  175.     onCancel() {
  176.         this.navigateBack();
  177.     }
  178.  
  179.  
  180.     ngOnDestroy() {
  181.         this.subscription.unsubscribe();
  182.     }
  183.  
  184.     private navigateBack() {
  185.         this.router.navigate(['users/']);
  186.     }
  187.  
  188.     private initForm(formLoaded: boolean) {
  189.         let userName = '';
  190.         let userEmail = '';
  191.         let userRole = '';
  192.  
  193.         if (!this.isNew && formLoaded) {
  194.             userName = this.user.name;
  195.             userEmail = this.user.email;
  196.             userRole = this.user.role;
  197.         }
  198.         this.userForm = this.formBuilder.group({
  199.             name: [userName, Validators.required],
  200.             email: [userEmail, Validators.compose([
  201.                 Validators.required,
  202.                 this.isEmail
  203.             ])],
  204.             password: ['', Validators.required],
  205.             confirmPassword: ['', Validators.compose([
  206.                 Validators.required,
  207.                 this.isEqualPassword.bind(this)
  208.             ])],
  209.             role: [userRole, Validators.required]
  210.         });
  211.     }
  212.  
  213.     isEmail(control: FormControl): {[s: string]: boolean} {
  214.         if (!control.value.match(/^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/)) {
  215.             return {noEmail: true};
  216.         }
  217.     }
  218.  
  219.     isEqualPassword(control: FormControl): {[s: string]: boolean} {
  220.         if (!this.userForm) {
  221.             return {passwordsNotMatch: true};
  222.  
  223.         }
  224.         if (control.value !== this.userForm.controls['password'].value) {
  225.             return {passwordsNotMatch: true};
  226.         }
  227.     }
  228.  
  229. }
  230.  
  231.  
  232.  
  233.  
  234.  
  235.  
  236.  
  237. -------UserEditComponent.html-------------------
  238. <div class="row">
  239.     <div class="col-xs-12">
  240.         <form [formGroup]="userForm" (ngSubmit)="onSubmit()">
  241.             <div class="row">
  242.                 <div class="col-xs-12">
  243.                     <button type="submit" class="btn btn-success" [disabled]="!userForm.valid">Save</button>
  244.                     <a class="btn btn-danger" (click)="onCancel()">Cancel</a>
  245.                 </div>
  246.             </div>
  247.             <div class="form-group">
  248.                 <label for="email">Name</label>
  249.                 <input *ngIf="!user" formControlName="name" type="text" id="name" #name class="form-control">
  250.                 <input *ngIf="user" formControlName="name" type="text" id="name" #name class="form-control" [(ngModel)]="user.name">
  251.                 <span>{{errorName}}</span>
  252.             </div>
  253.             <div class="form-group">
  254.                 <label for="email">E-Mail</label>
  255.                 <input *ngIf="!user" formControlName="email" type="email" id="email" #email class="form-control">
  256.                 <input *ngIf="user" formControlName="email" type="email" id="email" #email class="form-control" [(ngModel)]="user.email">
  257.                 <span>{{errorEmail}}</span>
  258.             </div>
  259.             <div class="form-group">
  260.                 <label for="password">Password</label>
  261.                 <input formControlName="password" type="password" id="password" class="form-control">
  262.             </div>
  263.             <div class="form-group">
  264.                 <label for="confirm-password">Confirm Password</label>
  265.                 <input formControlName="confirmPassword" type="password" id="confirm-password" #confirmPassword class="form-control">
  266.                 <span *ngIf="!confirmPassword.pristine && confirmPassword.errors != null && confirmPassword.errors['passwordsNotMatch']">Passwords do not match</span>
  267.             </div>
  268.             <div class="form-group">
  269.                 <label for="role">Select list:</label>
  270.                 <select formControlName="role" class="form-control" id="role" #role>
  271.                     <option>user</option>
  272.                     <option>admin</option>
  273.                 </select>
  274.             </div>
  275.         </form>
  276.     </div>
  277. </div>
  278.  
  279.  
  280.  
  281.  
  282.  
  283.  
  284.  
  285.  
  286. import { Injectable, EventEmitter} from "@angular/core";
  287.  
  288. import { User } from "./user.interface";
  289. import { Router } from "@angular/router";
  290. import {Headers, Http, Response} from "@angular/http";
  291. import 'rxjs/Rx';
  292. import {AuthHttp, AuthConfig, AUTH_PROVIDERS, JwtHelper} from "angular2-jwt/angular2-jwt";
  293.  
  294.  
  295. @Injectable()
  296. export class AuthService {
  297.   constructor(private router: Router, private http: Http) {}
  298.  
  299.   private userLoggedOut = new EventEmitter<any>();
  300.   private jwtHelper: JwtHelper = new JwtHelper();
  301.  
  302.   usersChanged = new EventEmitter<User[]>();
  303.   private users: User[] = [];
  304.  
  305.   signupUser(user: User){
  306.     const body = JSON.stringify(user);
  307.     const headers = new Headers();
  308.     headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
  309.  
  310.     //noinspection TypeScriptUnresolvedFunction
  311.     return this.http.post('../api/site/user/create/', body, {
  312.       headers: headers
  313.     }).map((data: Response) => data.json());
  314.   }
  315.  
  316.   signupUserAdmin(user: User){
  317.     user.token = localStorage.getItem('token');
  318.     const body = JSON.stringify(user);
  319.     const headers = new Headers();
  320.     headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
  321.  
  322.     //noinspection TypeScriptUnresolvedFunction
  323.     return this.http.post('../api/admin/users/create/', body, {
  324.       headers: headers
  325.     }).map((data: Response) => data.json());
  326.   }
  327.  
  328.   signinUser(user: User) {
  329.     const body = JSON.stringify(user);
  330.     const headers = new Headers();
  331.     headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
  332.    
  333.     //noinspection TypeScriptUnresolvedFunction
  334.     return this.http.post('../api/site/user/login/', body, {
  335.       headers: headers
  336.     }).map((data: Response) => data.json());
  337.   }
  338.  
  339.   getDataUsers() {
  340.     const body = '{"token": "'+localStorage.getItem('token')+'"}';
  341.     const headers = new Headers();
  342.     headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
  343.     //noinspection TypeScriptUnresolvedFunction
  344.     return this.http.post('../api/admin/users/get', body, {
  345.       headers: headers
  346.     }).map((data: Response) => data.json())
  347.         .subscribe((data: User[]) => {
  348.           this.users = data;
  349.           this.usersChanged.emit(this.users);
  350.         });
  351.   }
  352.  
  353.   getUser(id: Number) {
  354.     const body = '{"token": "'+localStorage.getItem('token')+'"}';
  355.     const headers = new Headers();
  356.     headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
  357.     //noinspection TypeScriptUnresolvedFunction
  358.     return this.http.post('../api/admin/users/get/'+id, body, {
  359.       headers: headers
  360.     }).map((data: Response) => data.json());
  361.   }
  362.  
  363.   editUser(user: User) {
  364.     user.token = localStorage.getItem('token');
  365.     const body = JSON.stringify(user);
  366.     const headers = new Headers();
  367.     headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
  368.     this.usersChanged.emit(this.users);
  369.     //noinspection TypeScriptUnresolvedFunction
  370.     return this.http.post('../api/admin/users/update/', body, {
  371.       headers: headers
  372.     }).map((data: Response) => data.json());
  373.   }
  374.  
  375.   deleteUser(user: User) {
  376.     user.token = localStorage.getItem('token');
  377.     const body = JSON.stringify(user);
  378.     const headers = new Headers();
  379.     headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
  380.     console.log(user);
  381.     //noinspection TypeScriptUnresolvedFunction
  382.     return this.http.post('../api/admin/users/delete', body, {
  383.       headers: headers
  384.     }).map((data: Response) => data.json());
  385.   }
  386.  
  387.   logout() {
  388.     localStorage.removeItem('token');
  389.     this.userLoggedOut.emit(null);
  390.     this.router.navigate(['/signin']);
  391.   }
  392.  
  393.   isAuthenticated(): boolean {
  394.     return localStorage.getItem('token') !== null;
  395.   }
  396.  
  397.   isAdmin(): boolean {
  398.  
  399.     var token = localStorage.getItem('token');
  400.     if(token !== null)
  401.       return this.jwtHelper.decodeToken(token).role == 'admin';
  402.     else
  403.       return false;
  404.   }
  405. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement