Guest User

Untitled

a guest
Jun 2nd, 2018
43
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import React from 'react';
  2. import { Redirect } from 'react-router-dom';
  3. import axios from 'axios';
  4.  
  5. export default class Login extends React.Component {
  6.     constructor() {
  7.         super();
  8.  
  9.         this.state = {
  10.             authenticated: false
  11.         }
  12.    
  13.         this.handleSubmit = this.handleSubmit.bind(this);
  14.         this.login = this.login.bind(this);
  15.     }
  16.  
  17.     componentWillMount() {
  18.         if(localStorage.getItem("token")) {
  19.             axios.post("/api/identifyToken", {
  20.                 token: localStorage.getItem("token")
  21.             }).then(res => {
  22.                 console.log(res);
  23.                 this.setState({
  24.                     authenticated: true
  25.                 });
  26.             }).catch(err => {
  27.                 console.log(err.response);
  28.                 this.setState({
  29.                     authenticated: false
  30.                 });
  31.             });
  32.         } else {
  33.             this.setState({
  34.                 authenticated: false
  35.             });
  36.         }
  37.     }
  38.  
  39.     handleSubmit(e) {
  40.         e.preventDefault();
  41.         this.login(this.inputUsername.value, this.inputPassword.value);
  42.     }
  43.  
  44.     async login(username, password) {
  45.         try {
  46.             const response = await axios.post("/api/login", {
  47.                 username: username,
  48.                 password: password
  49.             });
  50.  
  51.             localStorage.setItem("token", response.data.error.token);
  52.  
  53.             this.setState({
  54.                 authenticated: true
  55.             });
  56.  
  57.         } catch(e) {
  58.  
  59.             this.setState({
  60.                 authenticated: false
  61.             });
  62.  
  63.             console.log(e.response);
  64.         }
  65.     }
  66.  
  67.  
  68.     render() {
  69.  
  70.         if(this.state.authenticated) {
  71.             return <Redirect to="/home"/>;
  72.         }
  73.  
  74.         return (
  75.             <div>
  76.                 <form onSubmit={this.handleSubmit}>
  77.                     <label htmlFor="username">Username</label>
  78.                     <input type="text" id="usernme" ref={el => this.inputUsername = el}/>
  79.                     <label htmlFor="password">Password</label>
  80.                     <input type="text" id="password" ref={el => this.inputPassword = el}/>
  81.                     <button type="submit">Log In</button>
  82.                 </form>
  83.             </div>
  84.         );
  85.     }
  86. }
Add Comment
Please, Sign In to add comment