N
N
Nayob2020-09-21 14:52:00
User identification
Nayob, 2020-09-21 14:52:00

Authentication on the frontend after authorization on the backend. How to implement?

Actually there is this piece of code:

import axios from 'axios'
axios.defaults.withCredentials = true;

export default {
    name: 'Home',
    data(){
      return {
        username : "",
        password : ""
      }
    },
    methods: {
        login(e) {
            e.preventDefault();
            axios 
            .post('https://localhost:3011/login', {
                username: this.username,
                password: this.password,
            })
            .then(() => {this.$router.push("/")})
            .catch(error => console.log(error));
        },


after executing the login method, a session is created on the backend and a cookie with the session id is set. After that, the backend correctly processes requests based on the user's rights. How can this be used to control path access on the front?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
O
Oleg, 2020-09-21
@Nayob

As an option to make a point to get session data , the GET /authback will give data if there is a session or return a 401 error if the user is not authorized. In the vue store, create a user module:

export default {
  state: {
    user: null,
  },
  getters: {
    isAuthenticated: ({ user }) => Boolean(user),
  },
  actions: {
    getUser({ commit, dispatch }) {
      return this.$axios.get('/auth')
        .then(user => commit('setUser', user))
        .catch(() => dispatch('logout'));
    },
    login({ dispatch }, { email, password }) {
      return this.$axios.post('/login', {
        email, password,
      })
        .then(() => dispatch('getUser'));
    },
    logout({ commit }) {
      commit('unsetUser');
    },
  },
  mutations: {
    setUser(state, user) {
      state.user = user;
    },
    unsetUser(state) {
      state.user = null;
    },
  },
};

At the start of the application, we call getUser, if there is a session, we show something, otherwise, the authorization form, even at the root of the application, you can subscribe to store errors this.$store.subscribeActionand catch 401 to make a logout

K
Konstantin B., 2020-09-21
@Kostik_1993

No way. In addition to the option to throw an error from the backend and process it in axios

A
Aleks_Ko, 2020-09-21
@Aleks_Ko

firebase попробуйте. Там все есть и авторизация и база данных и документация адекватная

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question