A
A
Arthurysh2021-10-30 20:39:00
Laravel
Arthurysh, 2021-10-30 20:39:00

When I try to display the username I get {"message":"Unauthenticated."}. How to fix?

I'm trying to display user data in the profile, but I get {"message": "Unauthenticated."}, but in fact I'm logged in. Also, after logging out, when I try to log in again, I get an error 422.
617d819bcf65a540212596.png
user.js

import Api from "./Api";
import Csrf from "./Csrf";

export default {
  async register(form) {
    await Csrf.getCookie();

    return Api.post("/Registration", form);
  },

  async login(loginform) {
    await Csrf.getCookie();

    return Api.post("/Login", loginform);
  },

  async logout() {
    await Csrf.getCookie();

    return Api.post("/Logout");
  },

  auth() {
    return Api.get("/user");
  }
};


csrf.js
import Api from "./Api";
import Cookie from "js-cookie";

export default {
  getCookie() {
    let token = Cookie.get("XSRF-TOKEN");

    if (token) {
      return new Promise(resolve => {
        resolve(token);
      });
    }

    return Api.get("/csrf-cookie");
  }
};

LoginController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;

class LoginController extends Controller
{
    public function login(Request $request)
    {
        $request->validate([
            'email' => ['required'],
            'password' => ['required']
        ]);

        if (Auth::attempt($request->only('email', 'password'))) {
            return response()->json(Auth::user(), 200);
        }

        throw ValidationException::withMessages([
            'email' => ['The provided credentials are incorrect.']
        ]);
    }

    public function logout()
    {
        Auth::logout();
    }
}

vue.js
template>
  <div class="sidebar-container">
    <div class="bread-crumbs">
      <div class="bread-crumb back-main-page">
        <router-link to="/">
        <img src="@/assets/backArrowProfile.png" alt="" />
          <a class="on-main-link" href="#">На главную</a>
          </router-link>
      </div>
    </div>
    <div class="user-profile-block">
      <div class="user-image">
        <img src="@/assets/testUserPhoto.png" alt="" />
      </div>
      <div class="user-info-block" v-if="user">
        <p class="user-name">{{ user.name }}</p>
        <p class="user-email">{{ user.email }}</p>
      </div>
    </div>
    <sidebar-menu
      :userRole="userRole"
      @activateItemMenu="sendActiveItemId"
    ></sidebar-menu>
  </div>
</template>

<script>
import User from "@/apis/User";
import SidebarMenu from "@/components/ProfilePage/SidebarMenu.vue";

export default {
  data() {
    return {
      user: null
    }
  },
  components: { SidebarMenu },
  props: {
    userRole: {
      type: String,
      required: true,
    },
  },
  methods: {
    sendActiveItemId(itemMenuID) {
      this.$emit("activatedId", itemMenuID);
    },
  },
  mounted() {
     User.auth().then(response => {
       this.user = response.data;
     });
  },
};
</script>

api.php
<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

Route::post('/Registration', '[email protected]');
Route::post('/Login', '[email protected]');
Route::post('/Logout', '[email protected]');

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aetae, 2021-10-30
@Aetae

I don't see where your login is happening.
In any case, I suspect that what mountedhappens before something getCookie()works for you, and therefore sends a request before authorization. If this is the case, then wait to draw the component\request the user until you are sure of the authorization.
Minor quibble:

new Promise(resolve => {
  resolve(token);
});
->
Promise.resolve(token);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question