getSession

developer.do·2023년 5월 13일
0

getSession을 통해 로그인 상태가 아니면 로그인화면으로 가게 만들어보자

index.페이지

<template>
  <div>인덱스 페이지</div>
</template>
<route lang="yaml">
meta:
  layout: default
</route>
<script setup lang="ts">
import axios from "axios";

const authStore = useAuthStore();
const userGetSession = async () => {
  const res = await axios.get("api/v1/session");
  const userAdmin = res.data.body;
  console.log(userAdmin);
  authStore.setUser(userAdmin.userId, userAdmin.userName);
};

onMounted(() => {
  userGetSession();
});
</script>

<style scoped></style>
Login 페이지.
const submitForm = async () => {
  if (loginCheck()) {
    return;
  }

  const loginUser = {
    id: loginId.value,
    pwd: loginPassword.value,
  };
  // 객체 하나에서 관리

  try {
    const res = await axios.post("/api/v1/user/login", loginUser);
    if (res.data.httpStatusCode !== 200) {
      return;
    }

    router.push("/admin");
  } catch (error) {
    console.log(error, "로그인에러");
  }
};
auth 페이지

import { defineStore } from "pinia";

export const useAuthStore = defineStore("auth", () => {
  const auth = ref({
    userId: "",
    userName: "",
  });
  const isAuthenticated = computed(
    () => auth.value.userId && auth.value.userId !== ""
  );
  const setUser = (id: string, name: string) => {
    auth.value.userId = id;
    auth.value.userName = name;
  };
  const clearUser = () => {
    auth.value.userId = "";
    auth.value.userName = "";
  };
  return {
    setUser,
    clearUser,
    isAuthenticated,
    auth,
  };
});

0개의 댓글