Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { Component, OnInit } from '@angular/core';
- import {BlogPostService} from '../blog_post.service';
- import {UserService} from '../user.service';
- import {throwError} from 'rxjs'; // Angular 6/RxJS 6
- import {Router} from '@angular/router';
- @Component({
- selector: 'app-login',
- templateUrl: './login.component.html',
- styleUrls: ['./login.component.css']
- })
- export class LoginComponent implements OnInit {
- public user: any;
- /**
- * An array of all the BlogPost objects from the API
- */
- public posts;
- /**
- * An object representing the data in the "add" form
- */
- public new_post: any;
- constructor( private _userService: UserService, private router: Router) { }
- ngOnInit() {
- this.getPosts();
- this.new_post = {};
- this.user = {
- username: '',
- password: ''
- };
- }
- login() {
- this._userService.login({'username': this.user.username, 'password': this.user.password});
- this.router.navigateByUrl('/profile');
- }
- refreshToken() {
- this._userService.refreshToken();
- }
- logout() {
- this._userService.logout();
- }
- }
- <h2>Log In</h2>
- <div class="row" *ngIf="!_userService.token">
- <div class="col-sm-4">
- <label>Username:</label><br />
- <input type="text" name="login-username" [(ngModel)]="user.username">
- <span *ngFor="let error of _userService.errors.username"><br />{{ error }}</span></div>
- <div class="col-sm-4">
- <label>Password:</label><br />
- <input type="password" name="login-password" [(ngModel)]="user.password">
- <span *ngFor="let error of _userService.errors.password"><br />{{ error }}</span>
- </div>
- <div class="col-sm-4">
- <button (click)="login()" class="btn btn-primary">Log In</button>
- </div>
- <div class="col-sm-12">
- <span *ngFor="let error of _userService.errors.non_field_errors">{{ error }}<br /></span>
- </div>
- </div>
- import {Injectable} from '@angular/core';
- import {HttpClient, HttpHeaders} from '@angular/common/http';
- @Injectable()
- export class UserService {
- // http options used for making API calls
- private httpOptions: any;
- // the actual JWT token
- public token: string;
- // the token expiration date
- public token_expires: Date;
- // the username of the logged in user
- public username: string;
- // error messages received from the login attempt
- public errors: any = [];
- constructor(private http: HttpClient) {
- this.httpOptions = {
- headers: new HttpHeaders({'Content-Type': 'application/json'})
- };
- }
- // Uses http.post() to get an auth token from djangorestframework-jwt endpoint
- public login(user) {
- this.http.post('http://localhost:8000/api-token-auth/', JSON.stringify(user), this.httpOptions).subscribe(
- data => {
- console.log('login success', data);
- this.updateData(data['token']);
- },
- err => {
- console.error('login error', err);
- this.errors = err['error'];
- }
- );
- }
- /**
- * Refreshes the JWT token, to extend the time the user is logged in
- */
- public refreshToken() {
- this.http.post('http://localhost:8000/api-token-refresh/', JSON.stringify({token: this.token}), this.httpOptions).subscribe(
- data => {
- console.log('refresh success', data);
- this.updateData(data['token']);
- },
- err => {
- console.error('refresh error', err);
- this.errors = err['error'];
- }
- );
- }
- public logout() {
- this.token = null;
- this.token_expires = null;
- this.username = null;
- }
- private updateData(token) {
- this.token = token;
- this.errors = [];
- // decode the token to read the username and expiration timestamp
- const token_parts = this.token.split(/./);
- const token_decoded = JSON.parse(window.atob(token_parts[1]));
- this.token_expires = new Date(token_decoded.exp * 1000);
- this.username = token_decoded.username;
- }
- }
- <div class="row" *ngIf="_userService.token">
- <div class="col-sm-12">
- You are logged in as {{ _userService.username }}.<br />
- Token Expires: {{ _userService.token_expires }}<br />
- <button (click)="refreshToken()" class="btn btn-primary">Refresh Token</button>
- <button (click)="logout()" class="btn btn-primary">Log Out</button>
- </div>
- </div>
- import { Component, OnInit } from '@angular/core';
- import { ProfService } from './prof.service';
- import {BlogPostService} from '../blog_post.service';
- import {UserService} from '../user.service';
- import {throwError} from 'rxjs'; // Angular 6/RxJS 6
- import {Router} from '@angular/router';
- @Component({
- selector: 'app-profile',
- templateUrl: './profile.component.html',
- styleUrls: ['./profile.component.css']
- })
- export class ProfileComponent implements OnInit {
- public user: any;
- /**
- * An array of all the BlogPost objects from the API
- */
- public posts;
- /**
- * An object representing the data in the "add" form
- */
- public new_post: any;
- constructor(private _blogPostService: BlogPostService, private _userService: UserService, private router: Router) { }
- ngOnInit() {
- this.getPosts();
- }
- getPosts() {
- this._blogPostService.list().subscribe(
- // the first argument is a function which runs on success
- data => {
- this.posts = data;
- }
- },
- // the second argument is a function which runs on error
- err => console.error(err),
- // the third argument is a function which runs on completion
- () => console.log('done loading posts')
- );
- }
- import {Injectable} from '@angular/core';
- import {HttpClient, HttpHeaders} from '@angular/common/http';
- import {UserService} from './user.service';
- @Injectable()
- export class BlogPostService {
- constructor(private http: HttpClient, private _userService: UserService) {
- }
- // Uses http.get() to load data from a single API endpoint
- list() {
- return this.http.get('http://localhost:8000/profiles/id');
- }
- // helper function to build the HTTP headers
- getHttpOptions() {
- return {
- headers: new HttpHeaders({
- 'Content-Type': 'application/json',
- 'Authorization': 'JWT ' + this._userService.token
- })
- };
- }
- }
Add Comment
Please, Sign In to add comment