Guest User

Untitled

a guest
Oct 23rd, 2018
243
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.02 KB | None | 0 0
  1. import { Component, OnInit } from '@angular/core';
  2. import {BlogPostService} from '../blog_post.service';
  3. import {UserService} from '../user.service';
  4. import {throwError} from 'rxjs'; // Angular 6/RxJS 6
  5. import {Router} from '@angular/router';
  6.  
  7. @Component({
  8. selector: 'app-login',
  9. templateUrl: './login.component.html',
  10. styleUrls: ['./login.component.css']
  11. })
  12. export class LoginComponent implements OnInit {
  13. public user: any;
  14.  
  15. /**
  16. * An array of all the BlogPost objects from the API
  17. */
  18. public posts;
  19.  
  20. /**
  21. * An object representing the data in the "add" form
  22. */
  23. public new_post: any;
  24.  
  25. constructor( private _userService: UserService, private router: Router) { }
  26.  
  27. ngOnInit() {
  28. this.getPosts();
  29. this.new_post = {};
  30. this.user = {
  31. username: '',
  32. password: ''
  33. };
  34. }
  35.  
  36. login() {
  37. this._userService.login({'username': this.user.username, 'password': this.user.password});
  38. this.router.navigateByUrl('/profile');
  39. }
  40.  
  41. refreshToken() {
  42. this._userService.refreshToken();
  43. }
  44.  
  45. logout() {
  46. this._userService.logout();
  47. }
  48.  
  49.  
  50.  
  51.  
  52. }
  53.  
  54. <h2>Log In</h2>
  55. <div class="row" *ngIf="!_userService.token">
  56. <div class="col-sm-4">
  57. <label>Username:</label><br />
  58. <input type="text" name="login-username" [(ngModel)]="user.username">
  59. <span *ngFor="let error of _userService.errors.username"><br />{{ error }}</span></div>
  60. <div class="col-sm-4">
  61. <label>Password:</label><br />
  62. <input type="password" name="login-password" [(ngModel)]="user.password">
  63. <span *ngFor="let error of _userService.errors.password"><br />{{ error }}</span>
  64. </div>
  65. <div class="col-sm-4">
  66. <button (click)="login()" class="btn btn-primary">Log In</button>&nbsp;
  67. </div>
  68. <div class="col-sm-12">
  69. <span *ngFor="let error of _userService.errors.non_field_errors">{{ error }}<br /></span>
  70. </div>
  71. </div>
  72.  
  73. import {Injectable} from '@angular/core';
  74. import {HttpClient, HttpHeaders} from '@angular/common/http';
  75.  
  76. @Injectable()
  77. export class UserService {
  78.  
  79. // http options used for making API calls
  80. private httpOptions: any;
  81.  
  82. // the actual JWT token
  83. public token: string;
  84.  
  85. // the token expiration date
  86. public token_expires: Date;
  87.  
  88. // the username of the logged in user
  89. public username: string;
  90.  
  91. // error messages received from the login attempt
  92. public errors: any = [];
  93.  
  94. constructor(private http: HttpClient) {
  95. this.httpOptions = {
  96. headers: new HttpHeaders({'Content-Type': 'application/json'})
  97. };
  98. }
  99.  
  100. // Uses http.post() to get an auth token from djangorestframework-jwt endpoint
  101. public login(user) {
  102. this.http.post('http://localhost:8000/api-token-auth/', JSON.stringify(user), this.httpOptions).subscribe(
  103. data => {
  104. console.log('login success', data);
  105. this.updateData(data['token']);
  106. },
  107. err => {
  108. console.error('login error', err);
  109. this.errors = err['error'];
  110. }
  111. );
  112. }
  113.  
  114. /**
  115. * Refreshes the JWT token, to extend the time the user is logged in
  116. */
  117. public refreshToken() {
  118. this.http.post('http://localhost:8000/api-token-refresh/', JSON.stringify({token: this.token}), this.httpOptions).subscribe(
  119. data => {
  120. console.log('refresh success', data);
  121. this.updateData(data['token']);
  122. },
  123. err => {
  124. console.error('refresh error', err);
  125. this.errors = err['error'];
  126. }
  127. );
  128. }
  129.  
  130. public logout() {
  131. this.token = null;
  132. this.token_expires = null;
  133. this.username = null;
  134. }
  135.  
  136. private updateData(token) {
  137. this.token = token;
  138. this.errors = [];
  139.  
  140. // decode the token to read the username and expiration timestamp
  141. const token_parts = this.token.split(/./);
  142. const token_decoded = JSON.parse(window.atob(token_parts[1]));
  143. this.token_expires = new Date(token_decoded.exp * 1000);
  144. this.username = token_decoded.username;
  145. }
  146.  
  147. }
  148.  
  149. <div class="row" *ngIf="_userService.token">
  150. <div class="col-sm-12">
  151. You are logged in as {{ _userService.username }}.<br />
  152. Token Expires: {{ _userService.token_expires }}<br />
  153.  
  154.  
  155.  
  156. <button (click)="refreshToken()" class="btn btn-primary">Refresh Token</button>&nbsp;
  157. <button (click)="logout()" class="btn btn-primary">Log Out</button>&nbsp;
  158. </div>
  159. </div>
  160.  
  161. import { Component, OnInit } from '@angular/core';
  162. import { ProfService } from './prof.service';
  163. import {BlogPostService} from '../blog_post.service';
  164. import {UserService} from '../user.service';
  165. import {throwError} from 'rxjs'; // Angular 6/RxJS 6
  166. import {Router} from '@angular/router';
  167.  
  168.  
  169. @Component({
  170. selector: 'app-profile',
  171. templateUrl: './profile.component.html',
  172. styleUrls: ['./profile.component.css']
  173. })
  174. export class ProfileComponent implements OnInit {
  175.  
  176. public user: any;
  177.  
  178. /**
  179. * An array of all the BlogPost objects from the API
  180. */
  181. public posts;
  182.  
  183. /**
  184. * An object representing the data in the "add" form
  185. */
  186. public new_post: any;
  187.  
  188.  
  189. constructor(private _blogPostService: BlogPostService, private _userService: UserService, private router: Router) { }
  190.  
  191.  
  192.  
  193. ngOnInit() {
  194. this.getPosts();
  195.  
  196. }
  197.  
  198.  
  199. getPosts() {
  200. this._blogPostService.list().subscribe(
  201. // the first argument is a function which runs on success
  202. data => {
  203. this.posts = data;
  204.  
  205. }
  206. },
  207. // the second argument is a function which runs on error
  208. err => console.error(err),
  209. // the third argument is a function which runs on completion
  210. () => console.log('done loading posts')
  211. );
  212. }
  213.  
  214. import {Injectable} from '@angular/core';
  215. import {HttpClient, HttpHeaders} from '@angular/common/http';
  216. import {UserService} from './user.service';
  217.  
  218. @Injectable()
  219. export class BlogPostService {
  220.  
  221. constructor(private http: HttpClient, private _userService: UserService) {
  222. }
  223.  
  224. // Uses http.get() to load data from a single API endpoint
  225. list() {
  226. return this.http.get('http://localhost:8000/profiles/id');
  227. }
  228.  
  229.  
  230. // helper function to build the HTTP headers
  231. getHttpOptions() {
  232. return {
  233. headers: new HttpHeaders({
  234. 'Content-Type': 'application/json',
  235. 'Authorization': 'JWT ' + this._userService.token
  236. })
  237. };
  238. }
  239.  
  240. }
Add Comment
Please, Sign In to add comment