0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Vite×React×Nest.js×PostgreSQL】セッションをダッシュボードに組み込む

Last updated at Posted at 2025-12-06

前回の記事の続きです。

今回は、ログイン成功後にダッシュボードにセッション情報を組み込む方法についてです。

Frontendの修正

App.tsxからpropsを受け取るためにTopOnDashboard関数の引数にsetIsLoggedIn, setUserNameを入れています。

Navbar が依存している App.tsx のisLoggedIn / userNameが更新されます。

src/pages/dashboard/top/page.tsx
import { useLocation, useNavigate } from 'react-router-dom';
import axios from 'axios';
import React, { useEffect, useState } from 'react';
import Swal from 'sweetalert2';
import { SideBar } from '../../sideBar/page';

interface TopProps {
  setIsLoggedIn: (value: boolean) => void;
  setUserName: (value: string | undefined) => void;
}

export const TopOnDashboard: React.FC<TopProps> = ({setIsLoggedIn, setUserName}) => { //{ setIsLoggedIn, setUserName }
  const navigate = useNavigate();

  const adminSessionUrl = import.meta.env.VITE_ADMIN_SESSION_CHECK as string;
  const getOneUserUrl = import.meta.env.VITE_ADMIN_USER_GET_ONE as string | undefined;
  // sign-up画面から受け取る email
  const { state } = useLocation();

  // 設定ファイルからURL情報が読み込めない場合(Can note read data from .env file)
  if (!getOneUserUrl) {
    Swal.fire({
      title: '設定情報を取得できません。',
      text: '管理者に報告してください。',
      icon: 'error',
    }).then(() => {
      // トップページに戻る(Back To TopPage)
      navigate('/');
    });
    return null;
  }

  useEffect(() => {
    if (!state) {
      Swal.fire({
        title: 'ユーザー情報を確認できません。',
        text: 'もう一度ログイン画面からやり直してください。',
        icon: 'error',
      }).then(() => navigate('/admin_user/sign-up'));
    }
  }, [state]);

  // セッションチェック
  useEffect(()=>{
    const session = async ()=>{
      const response = await axios.get(adminSessionUrl,{withCredentials:true});
      // Http Statusが200以外(ログイン中以外)の場合
      if(response.data.status !== 200){
        setIsLoggedIn(false);
        navigate('/');
        return
      }
      // ログイン中
      setIsLoggedIn(true);
      setUserName(response.data.user.name);
    };
    session();
  },[]);

  /*
  if (!state) {
    Swal.fire({
      title: 'ユーザー情報を確認できません。',
      text: 'もう一度ログイン画面からやり直してください。',
      icon: 'error',
    }).then(() => {
      // ログインページに戻る(Back To TopPage)
      navigate('/admin_user/sign-up');  
    });
  }
  */

  // email で一意のユーザー情報を取得する
  useEffect(() => {
    const fetchUser = async () => {
      try {
        const res = await axios.post(getOneUserUrl, { email: state });
        console.log('サーバから受け取ったデータは:', res);
        if (res.data.status) {
          throw new Error(res.data.message); // UserResponse の場合
        }
        // ユーザー情報を取得する
        setUserName(res.data.user_name);
        setIsLoggedIn(true);
      } catch (error) {
        //データが取得できない場合
        Swal.fire({
          title: 'ユーザー情報を確認できません。',
          text: 'もう一度ログイン画面からやり直してください。',
          icon: 'error',
          confirmButtonColor: '#d33',
        }).then((result) => {
          // ログインページに戻る(Back To TopPage)
          if (result.isConfirmed) {
            navigate('/');
          }
        });
      }
    };
    fetchUser();
  }, []);

  // 管理者、それ以外でダッシュボードの表示方法が異なる
  return (
    <div className="p-4">
      <SideBar />
    </div>
  );
};

サイト

【初学者向け】セッションの概念と仕組みをCookie抜きで説明する

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?