[PYTHON] Let's make a nervous breakdown application with Vue.js and Django-Rest-Framework [Part 6] ~ User Authentication 2 ~

<< Part 5

Implemented login

Login screen creation

Login.vue


<template>
  <v-form>
    <v-container>
      <v-row>
        <v-col cols="12">
          <v-text-field
            v-model="username"
            label="Username"
            outlined
          ></v-text-field>
        </v-col>
      </v-row>

      <v-row>
        <v-col cols="12">
          <v-text-field
            v-model="password"
            outlined
            label="Password"
            style="min-height: 96px"
            type="password"
          >
          </v-text-field>
        </v-col>
      </v-row>

      <div class="text-right">
        <v-btn depressed large color="primary">Login</v-btn>
      </div>
    </v-container>
  </v-form>
</template>

<script>
export default {
  name: 'Login',
  data: function () {
    return {
      username: null,
      password: null
    }
  },
  mounted () {
    //
  }
}
</script>

Fixed router / index.ts

router/index.ts


import Vue from 'vue'
import Router from 'vue-router'
import PlayScreen from '@/views/PlayScreen.vue'
import Login from '@/views/Login.vue'

Vue.use(Router)

export default new Router({
  mode:'history',
  routes: [
    {
      path: '/',
      redirect: 'login'
    },
    {
      path: '/login',
      name: 'login',
      component: Login
    },
    {
      path: '/playscreen',
      name: 'playscreen',
      component: PlayScreen
    },
  ]
})

When you do npm run dev, the created login screen will be displayed initially.

image.png

vuex installation

npm install vuex --save

install axios

axios is a "Promise-based HTTP client" (from official).

npm install axios --save

Prepare a common function to throw get and post requests with axios

Prepare a ʻapifolder directly undersrc`, and create common.ts directly under it to prepare common functions of axios.

concentratio #Project root directory
├── config
│   ├── ...
│
├── frontend
│   ├── ...
│   ├── ..
│   ├── .
│   └── src
│         └──api #Create
│             └──common.ts #Create
└── manage.py

src/api/common.ts


import axios from "axios";

const baseRequest = axios.create({
  baseURL: "http://localhost:8000",
  headers: {
      "Content-Type": "application/json",
  }
});

/**
 *GET request
 * @param url URL
 */
function get(url) {
  return baseRequest.get(url);
}

/**
 *POST request
 * @param url URL
 */
function post(url, payload) {
  return baseRequest.post(url, payload);
}

export default {
    get,
    post
};

Prepare vuex module for authentication

I thought that managing with a single getters or actions would only swell the source code, so I tried to divide it into modules for each function, but I was addicted to it for about half a day.
concentratio #Project root directory
├── config
│   ├── ...
│
├── frontend
│   ├── ...
│   ├── ..
│   ├── .
│   └── src
│         └──store #Create
│             └──authenticates #Create
│                 ├──actions.ts #Create
│                 └──index.ts.ts #Create
│                 └──mutations.ts #Create
└── manage.py

store/authenticates/actions.ts


import commonAxios from "../../api/common";

export default {
  LOGIN: function({ commit }, payload) {
    return new Promise((success, error) => {
      commonAxios.post("/api-token-auth/", payload).then(
        response => {
          //Processing on success
          commit("SET_TOKEN", response.data.token); // mutations.ts SET_Pass the token to the TOKEN function
          commonAxios.baseRequest.defaults.headers.common['Authorization'] = `JWT ${response.data.token}`;
          success();
        }
      );
    });
  }
}

If you forget to add "/ (slash)" at the end of the above url, it will be rejected by CORS and an error will occur. It took me a long time to notice this, and I was addicted to it for about an hour ...    

store/authenticates/index.ts


import actions from './actions';

export const state = {};

export default {
  namespaced: true, //Be sure to put it on or off, you will get an error when reading with mapActions of vue.
  state,
  actions,
  mutations
};

store/authenticates/mutations.ts


export default {
  SET_TOKEN: function(state, token) {
    state.token = token
  }
};

Create ʻindex.ts directly under src / store`

store/index.ts


import Vue from "vue";
import Vuex from "vuex";
import authModules from "./authenticates"; //Load the module under authenticates with the name authModules

Vue.use(Vuex);

export default new Vuex.Store({
  modules: {
    authModules: authModules,
  }
});

Fixed src / main.ts

src/main.ts


.
..
...
import store from "./store"; //add to
...
..
.
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>',
  vuetify: new Vuetify(),
  store //add to
});

Fixed Login.vue

Login.vue


<template>
  <v-form>
    <v-container>
      ...
      ..
      .

      <div class="text-right">
        <v-btn depressed large color="primary" @click="login">
Login
        </v-btn>
      </div>
    </v-container>
  </v-form>
</template>

<script>
import { mapActions } from "vuex";

export default {
  name: "Login",
  data: function() {
    return {
      username: null,
      password: null
    };
  },
  methods: {
    ...mapActions("authModules", ["LOGIN"]), //Modularized action.Read LOGIN function from ts
    login: function() {
      const data = {
        username: this.username,
        password: this.password
      };
      this.LOGIN(data).then(res => {
        console.log(res);
      });
    }
  },
  mounted() {
    //
  }
};
</script>

Check if response is returned

After entering the correct username and password, press the login button and check that the response is returned.

image.png

It's back!

After successful authentication, move to the top page.

Just replace console.log (res); in Login.vue withthis. $ Router.push ("/ playscreen");.

that's all

I was able to successfully transition to the top page from the login screen.

Recommended Posts

Let's make a nervous breakdown application with Vue.js and Django-Rest-Framework [Part 6] ~ User Authentication 2 ~
Let's make a nervous breakdown application with Vue.js and Django-Rest-Framework [Part 5] ~ User authentication ~
Let's make a nervous breakdown application with Vue.js and Django-Rest-Framework [Part 3] ~ Implementation of nervous breakdown ~
Let's make a nervous breakdown app with Vue.js and Django-Rest-Framework [Part 2] ~ Vue setup ~
Let's make a nervous breakdown app with Vue.js and Django-Rest-Framework [Part 1] ~ Django setup ~
Try to make a nervous breakdown application with Vue.js and Django-Rest-Framework [Part 4] ~ MySQL construction and DB migration with Docker ~
Let's make a WEB application for phone book with flask Part 1
Let's make a WEB application for phone book with flask Part 2
Let's make a WEB application for phone book with flask Part 3
Let's make a WEB application for phone book with flask Part 4
Let's make a simple game with Python 3 and iPhone
Let's make a Mac app with Tkinter and py2app
Let's make a websocket client with Python. (Access token authentication)
Let's make a GUI with python.
Let's make a breakout with wxPython
Let's make a graph with python! !!
Let's make a supercomputer with xCAT
Make a thermometer with Raspberry Pi and make it viewable with a browser Part 4
Let's make a shiritori game with Python
Let's make a voice slowly with Python
Let's make a simple language with PLY 1
Let's make a web framework with Python! (1)
Let's make a tic-tac-toe AI with Pylearn 2
Let's make a Twitter Bot with Python!
Let's make a web framework with Python! (2)
Let's make an A to B conversion web application with Flask! From scratch ...
Try creating a web application with Vue.js and Django (Mac)-(1) Environment construction, application creation
Let's replace UWSC with Python (5) Let's make a Robot
Let's make an app that can search similar images with Python and Flask Part1
Let's make an app that can search similar images with Python and Flask Part2
Let's make a Makefile and build it (super beginner)
[Let's play with Python] Make a household account book
How to make a shooting game with toio (Part 1)
Let's make dependency management with pip a little easier
Let's make a spherical grid with Rhinoceros / Grasshopper / GHPython
[Super easy] Let's make a LINE BOT with Python.
Easily create authentication, user management, and multilingual systems with Flask-AppBuilder
Make a tky2jgd plugin with no practicality in QGIS Part 2
Associate Python Enum with a function and make it Callable
Let's create a PRML diagram with Python, Numpy and matplotlib.
Make a tky2jgd plugin with no practicality in QGIS Part 1
Make a 2D RPG with Ren'Py (3) -Items and Tool Shop
Let's make a diagram that can be clicked with IPython
Make a BLE thermometer and get the temperature with Pythonista3