하관우 하관우 03-21
2025-03-21 하관우 토큰 재발급 로그인 수정 내정보 수정 App.vue 이미지 클릭시 상위로 이동동
@d719c9732ecc4fb4c43562765e0e8074fb662ba3
client/resources/api/index.js
--- client/resources/api/index.js
+++ client/resources/api/index.js
@@ -1,149 +1,61 @@
-import axios from "axios";
+import axios from 'axios';
 import store from "../../views/pages/AppStore";
 
 const apiClient = axios.create({
-  headers: { 'Content-Type': 'application/json; charset=UTF-8' }
+  headers: {
+    'Content-Type': 'application/json; charset=UTF-8',
+  }
 });
-
-// 동시에 여러 요청이 401 에러가 발생했을 때 관리하기 위한 변수
-let isRefreshing = false;
-let failedQueue = [];
-
-const processQueue = (error, token = null) => {
-  failedQueue.forEach(prom => {
-    if (error) {
-      prom.reject(error);
-    } else {
-      prom.resolve(token);
-    }
-  });
-
-  failedQueue = [];
-};
 
 apiClient.interceptors.request.use(
   config => {
-    // Bearer 접두사 추가 (API 요구사항에 따라 필요한 경우)
-    if (store.state.authorization) {
-      config.headers.Authorization = store.state.authorization;
-    }
+    config.headers.Authorization = store.state.authorization; // 요청 시 AccessToken 추가
     return config;
   },
   error => {
     return Promise.reject(error);
   }
-);
-
-async function refreshAccessToken() {
-  try {
-    // 리프레시 토큰 존재 여부 확인
-    if (!store.state.refreshToken) {
-      throw new Error('리프레시 토큰이 없습니다.');
-    }
-
-    console.log('토큰 재발급 시도:', new Date().toISOString());
-
-    // 서버의 구현에 맞게 요청 형식 수정
-    // 백엔드는 요청 바디가 아닌 쿠키에서 refreshToken을 읽으므로
-    // 빈 객체로 보내고 withCredentials를 true로 설정
-    const res = await axios.post('/refresh/tknReissue.json', {}, {
-      withCredentials: true,
-      timeout: 10000 // 10초 타임아웃 설정
-    });
-
-    console.log('토큰 재발급 응답:', res.status);
-
-    // 백엔드는 응답 헤더에 Authorization으로 새 토큰을 보냄
-    const newToken = res.headers['authorization'];
-
-    if (newToken) {
-      // 새 토큰을 스토어에 저장
-      store.commit('setAuthorization', newToken);
-      return newToken;
-    } else {
-      console.error('응답 헤더에 토큰이 없습니다:', res.headers);
-      throw new Error('토큰이 포함되어 있지 않습니다.');
-    }
-  } catch (error) {
-    console.error('토큰 재발급 오류:', error);
-
-    // 네트워크나 서버 오류 구분
-    if (!navigator.onLine) {
-      alert('네트워크 연결을 확인해주세요.');
-    } else if (error.response && (error.response.status === 401 || error.response.status === 403)) {
-      alert('세션이 만료되었습니다. 다시 로그인해 주세요.');
-      store.commit("setStoreReset");
-      window.location = '/login.page';
-    } else {
-      alert('토큰 재발급에 실패했습니다. 다시 로그인해 주세요.');
-      store.commit("setStoreReset");
-      window.location = '/login.page';
-    }
-
-    throw error;
-  }
-}
+)
 
 apiClient.interceptors.response.use(
   response => {
     return response;
   },
   async error => {
-    const originalReq = error.config;
-
-    // 응답이 없는 경우(네트워크 오류) 처리
-    if (!error.response) {
-      console.error('네트워크 오류:', error);
-      return Promise.reject(error);
-    }
-
-    // 403 오류 처리: 접근 권한 없음
-    if (error.response.status === 403 && error.response.data.message === '접근 권한이 없습니다.') {
+    if (error.response.status == 403 && error.response.data.message == '접근 권한이 없습니다.') {
       window.history.back();
-      return Promise.reject(error);
     }
-
-    // 401 오류 처리: 토큰 만료
-    if (error.response.status === 401 && !originalReq._retry) {
-      originalReq._retry = true;
-
-      // 이미 토큰 재발급 중인 경우 대기열에 추가
-      if (isRefreshing) {
-        return new Promise((resolve, reject) => {
-          failedQueue.push({ resolve, reject });
-        }).then(token => {
-          originalReq.headers['Authorization'] = token;
-          return apiClient(originalReq);
-        }).catch(err => {
-          return Promise.reject(err);
-        });
-      }
-
-      isRefreshing = true;
-
+    const originalReq = error.config;
+    // 토큰의 만료기간이 끝난경우
+    if (error.response.status == 401 && error.response.data.message == 'Token expired' && !originalReq._retry) {
+      originalReq._retry = true; // 재요청 시도(한번만 실행)
       try {
-        // 액세스 토큰 재발급 요청
-        const newToken = await refreshAccessToken();
-
-        // 성공적으로 토큰을 재발급받은 경우
-        originalReq.headers['Authorization'] = newToken;
-
-        // 대기 중인 요청 처리
-        processQueue(null, newToken);
-
-        // 재요청
-        return apiClient(originalReq);
+        const res = await axios.post('/refresh/tknReissue.json', {});
+        store.commit('setAuthorization', res.headers.authorization); // 새로 발급 받은 AccessToken 저장
+        originalReq.headers.Authorization = store.state.authorization; // 새로 발급 받은 AccessToken을 기존 요청에 추가
+        /** jwt토큰 디코딩 **/
+        const base64String = store.state.authorization.split('.')[1];
+        const base64 = base64String.replace(/-/g, '+').replace(/_/g, '/');
+        const jsonPayload = decodeURIComponent(atob(base64).split('').map(c => {
+          return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
+        }).join(''));
+        const mbr = JSON.parse(jsonPayload);
+        // const mbr = JSON.parse(decodeURIComponent(escape(window.atob(base64String)))); // jwt claim 추출
+        store.commit("setUserNm", mbr.userNm);
+        store.commit('setRoles', mbr.roles);
+        /** jwt토큰 디코딩 **/
+        return apiClient(originalReq); // 원래 요청 재시도 /pathname + search
       } catch (refreshError) {
-        // 대기 중인 모든 요청에 오류 전파
-        processQueue(refreshError, null);
+        const redirect = window.location.pathname + window.location.search;
+        sessionStorage.setItem("redirect", redirect);
+        alert('세션이 종료되었습니다.\n로그인을 새로 해주세요.');
+        store.commit("setStoreReset");
+        window.location = '/login.page';
         return Promise.reject(refreshError);
-      } finally {
-        isRefreshing = false;
       }
     }
-
     return Promise.reject(error);
   }
-);
+)
 
 export default apiClient;
(파일 끝에 줄바꿈 문자 없음)
 
client/resources/api/logOut.js (deleted)
--- client/resources/api/logOut.js
@@ -1,10 +0,0 @@
-import apiClient from "./index";
-import store from '../../views/pages/AppStore';
-
-export const logOutProc = () => {
-    return apiClient.post(`/user/logout.json`, {}, {
-        headers: {
-            'refresh': store.state.refresh
-        }
-    });
-}(파일 끝에 줄바꿈 문자 없음)
 
client/resources/api/login.js (deleted)
--- client/resources/api/login.js
@@ -1,5 +0,0 @@
-import apiClient from "./index";
-
-export const loginProc = mber => {
-    return apiClient.post(`/user/login.json`, mber);
-}(파일 끝에 줄바꿈 문자 없음)
 
client/resources/api/user.js (added)
+++ client/resources/api/user.js
@@ -0,0 +1,31 @@
+import apiClient from "./index";
+import store from '../../views/pages/AppStore';
+
+// 로그인
+export const loginProc = mber => {
+    return apiClient.post(`/user/login.json`, mber);
+}
+
+// 로그아웃
+export const logOutProc = () => {
+    return apiClient.post(`/user/logout.json`, {}, {
+        headers: {
+            'refresh': store.state.refresh
+        }
+    });
+}
+
+// 아이디로 유저 찾기
+export const findByIdProc = userId => {
+    return apiClient.get(`/user/${userId}/users.json`);
+}
+
+// 유저 정보 변경
+export const updateUsers = (userId, updateUserDTO) => {
+    return apiClient.put(`/user/${userId}/users.json`, updateUserDTO);
+}
+
+// 유저 비밀번호 변경
+export const updatePassword = (userId, passwordDTO) => {
+    return apiClient.put(`/user/${userId}/updatePassword.json`, passwordDTO);
+}(파일 끝에 줄바꿈 문자 없음)
client/views/App.vue
--- client/views/App.vue
+++ client/views/App.vue
@@ -1,9 +1,10 @@
+App.vue
 <template>
  <div class="wrapper">
     <Header />
     <div class="container "><router-view /></div>
     <Footer />
-    <button class="scroll-up">
+    <button class="scroll-up"  @click="scrollToTop">
       <img src="../resources/images/icon/top.png" alt="">
     </button>
   </div>
@@ -17,7 +18,15 @@
   components: {
     Header: Header,
     Footer: Footer,
-  }
+  },
+  methods: {
+    scrollToTop() {
+      window.scrollTo({
+        top: 0,
+        behavior: 'smooth' // 부드러운 스크롤 효과
+      });
+    },
+  },
 }
 </script>
 <style></style>
(파일 끝에 줄바꿈 문자 없음)
client/views/layout/Header.vue
--- client/views/layout/Header.vue
+++ client/views/layout/Header.vue
@@ -8,10 +8,13 @@
             <div class="nav-wrap">
                 <nav>
                     <ul>
-                        <li>기록물</li>
-                        <li>언론에서 바라본 구미시</li>
-                        <li>회원관리</li>
-                        <li>카테고리 관리</li>
+                        <li v-if="$store.state.roles[0]?.authority === 'ROLE_ADMIN'">기록물</li>
+                        <li v-if="$store.state.roles[0]?.authority === 'ROLE_ADMIN'">언론에서 바라본 구미시</li>
+                        <li v-if="$store.state.roles[0]?.authority === 'ROLE_ADMIN'">회원관리</li>
+                        <li v-if="$store.state.roles[0]?.authority === 'ROLE_ADMIN'">카테고리 관리</li>
+
+                        <li v-if="$store.state.roles[0]?.authority === 'ROLE_USER'">기록물</li>
+                        <li v-if="$store.state.roles[0]?.authority === 'ROLE_USER'">언론에서 바라본 구미시</li>
                     </ul>
                 </nav>
             </div>
@@ -33,6 +36,7 @@
     </header>
 </template>
 <script>
+import { logOutProc } from "../../resources/api/user"
 export default {
     data() {
         return {
@@ -42,9 +46,18 @@
     },
     methods: {
         logout() {
-            this.$store.commit('setStoreReset'); // 로그아웃 뮤테이션 호출
-            this.isUserNm = null; // 사용자 이름 초기화
-            this.$router.push({ path: '/Login.page' }); // 로그인 페이지로 리다이렉트
+            // 백엔드 로그아웃 API 호출
+            logOutProc()
+                .then(() => {
+                    console.log('로그아웃 성공 - 서버 측 쿠키 삭제 완료');
+                    this.$store.commit('setStoreReset'); // 로그아웃 성공 후 스토어 초기화
+                    this.$router.push({ path: '/Login.page' }); // 로그인 페이지로 리다이렉트
+                })
+                .catch(err => {
+                    console.error('로그아웃 처리 중 오류:', err);
+                    this.$store.commit('setStoreReset'); // 오류가 있어도 스토어는 초기화
+                    this.$router.push({ path: '/Login.page' }); // 로그인 페이지로 리다이렉트
+                });
         }
     },
     watch: {},
client/views/pages/AppStore.js
--- client/views/pages/AppStore.js
+++ client/views/pages/AppStore.js
@@ -1,42 +1,57 @@
 import { createStore } from "vuex";
 import createPersistedState from "vuex-persistedstate";
-import { logOutProc } from "../../resources/api/logOut";
+import { logOutProc } from "../../resources/api/user";
 
 export default createStore({
   plugins: [createPersistedState()],
   state: {
     authorization: null,
-    // refresh: null,
-    roles: [],
+    refresh: null, // 리프레시 토큰을 추가
+    userId: null, // 사용자 ID 추가
+    loginId: null, // 로그인 ID 추가
+    userNm: null, // 사용자 이름 추가
+    roles: [], // 사용자 권한
   },
   getters: {
-    getAuthorization: function () {},
-    // getRefresh: function () {},
-    getUserNm: function () {},
-    getRoles: function () {},
+    getAuthorization(state) {
+      return state.authorization; // authorization 반환
+    },
+    getRefresh(state) {
+      return state.refresh; // 리프레시 토큰 반환
+    },
+    getUserNm(state) {
+      return state.userNm; // 사용자 이름 반환
+    },
+    getRoles(state) {
+      return state.roles; // 사용자 권한 반환
+    },
   },
   mutations: {
     setAuthorization(state, newValue) {
-      state.authorization = newValue;
+      state.authorization = newValue; // authorization 설정
     },
-    // setRefresh(state, newValue) {
-    //   state.refresh = newValue;
-    // },
+    setRefresh(state, newValue) {
+      state.refresh = newValue; // 리프레시 토큰 설정
+    },
+    setLoginId(state, newValue) {
+      state.loginId = newValue; // 로그인 ID 설정
+    },
     setUserNm(state, newValue) {
-      state.userNm = newValue;
+      state.userNm = newValue; // 사용자 이름 설정
     },
     setUserId(state, newValue) {
-      state.userId = newValue;
+      state.userId = newValue; // 사용자 ID 설정
     },
     setRoles(state, newValue) {
-      state.roles = newValue;
+      state.roles = newValue; // 사용자 권한 설정
     },
     setStoreReset(state) {
       state.authorization = null;
-      // state.refresh = null;
+      state.refresh = null; // 리프레시 토큰 초기화
       state.userNm = null;
       state.userId = null;
       state.roles = [];
+      state.loginId = null;
     },
   },
   actions: {
@@ -44,20 +59,21 @@
       try {
         const res = await logOutProc();
         alert(res.data.message);
-        if (res.status == 200) {
+        if (res.status === 200) {
           commit("setStoreReset");
         }
-      } catch(error) {
+      } catch (error) {
+        console.error("Logout error:", error); // 에러 로그 추가
         const errorData = error.response.data;
-        if (errorData.message != null && errorData.message != "") {
-          alert(error.response.data.message);
+        if (errorData.message) {
+          alert(errorData.message);
         } else {
           alert("에러가 발생했습니다.\n관리자에게 문의해주세요.");
         }
       }
     },
-    setStoreReset({commit}) {
+    setStoreReset({ commit }) {
       commit("setStoreReset");
-    }
+    },
   },
-});
(파일 끝에 줄바꿈 문자 없음)
+});
client/views/pages/login/Login.vue
--- client/views/pages/login/Login.vue
+++ client/views/pages/login/Login.vue
@@ -5,7 +5,7 @@
             <div class="breadcrumb-list">
                 <ul>
                     <!-- Bind the image source dynamically for homeicon -->
-                    <li><img :src="homeicon" alt="Home Icon"><p></p></li>
+                    <li><img :src="homeicon" alt="Home Icon"></li>
                     <li><img :src="righticon" alt="Home Icon"></li>
                     <li>로그인</li>
                 </ul>
@@ -36,7 +36,6 @@
 
 <script>
 import { useStore } from "vuex";
-import { loginProc } from "../../../resources/api/login";
 import axios from "axios";
 
 export default {
@@ -66,35 +65,37 @@
                 console.log(response); // 응답 확인
 
                 if (response.status === 200) {
-                    // 토큰 저장 로직
-                    this.$store.commit("setAuthorization", response.headers.authorization);
-                    /** jwt토큰 복호화 **/
-                    const base64String = this.$store.state.authorization.split(".")[1];
-                    const base64 = base64String.replace(/-/g, "+").replace(/_/g, "/");
-                    const jsonPayload = decodeURIComponent(
-                        atob(base64)
-                            .split("")
-                            .map((c) => {
-                                return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2);
-                            })
-                            .join("")
-                    );
-                    const mbr = JSON.parse(jsonPayload);
-                    //const mbr = JSON.parse(decodeURIComponent(escape(window.atob(base64String)))); // jwt claim 추출
-                    console.log("리멤버미~", mbr);
-                    this.$store.commit("setUserId", mbr.userId);
-                    this.$store.commit("setUserNm", mbr.userNm);
-                    this.$store.commit("setRoles", mbr.roles);
-                    /** jwt토큰 복호화 **/
+                    const newToken = response.headers.authorization;
+                    this.store.commit("setAuthorization", newToken);
+
+                    // JWT 디코딩
+                    const mbr = this.decodeJwt(newToken);
+                    if (mbr) {
+                        this.store.commit("setUserId", mbr.userId);
+                        this.store.commit("setLoginId", mbr.loginId);
+                        this.store.commit("setUserNm", mbr.userNm);
+                        this.store.commit("setRoles", mbr.roles);
+                    }
 
                     // 리다이렉트 처리
                     this.$router.push("/");
                 }
             } catch (error) {
-                console.error("Login error:", error); // 에러 로그
+                console.error("Login error:", error);
                 const message = error.response?.data?.message || "로그인에 실패했습니다.";
                 alert(message);
             }
+        },
+        decodeJwt(token) {
+            const base64String = token.split(".")[1];
+            const base64 = base64String.replace(/-/g, "+").replace(/_/g, "/");
+            const jsonPayload = decodeURIComponent(
+                atob(base64)
+                    .split("")
+                    .map(c => "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2))
+                    .join("")
+            );
+            return JSON.parse(jsonPayload);
         }
     },
     watch: {},
client/views/pages/user/MyInfo.vue
--- client/views/pages/user/MyInfo.vue
+++ client/views/pages/user/MyInfo.vue
@@ -1,69 +1,209 @@
 <template>
     <div class="content">
-      <div class="sub-title-area mb-110">
+        <div class="sub-title-area mb-110">
             <h2>내 정보 수정</h2>
             <div class="breadcrumb-list">
                 <ul>
-                    <li><img :src="homeicon" alt="Home Icon"><p></p></li>
+                    <li><img :src="homeicon" alt="Home Icon"></li>
                     <li><img :src="righticon" alt="Home Icon"></li>
                     <li>내 정보 수정</li>
                 </ul>
             </div>
-      </div>
-      <h3>기본정보</h3>
+        </div>
+        <h3>기본정보</h3>
         <form action="" class="info-form mb-50">
             <dl>
-                <dd >
+                <dd>
                     <label for="id" class="require">아이디</label>
-                    <input type="text" id="id" value="admin" readonly>
+                    <input type="text" id="id" v-model="$store.state.loginId" readonly>
                 </dd>
                 <div class="hr"></div>
-                
-                <dd >
+
+                <dd>
                     <label for="name" class="require">이름</label>
-                    <input type="text" id="name" value="관리자">
-                    
+                    <input type="text" id="name" v-model="userInfo.userNm">
+
                 </dd>
-               
+
             </dl>
         </form>
         <h3>비밀번호 변경</h3>
         <form action="" class="pwchange-form mb-50">
             <dl>
-                <dd >
-                    <label for="id">아이디</label>
-                    <input type="text" id="id" placeholder="아이디를 입력하세요.">
+                <dd>
+                    <label for="id">현재 비밀번호</label>
+                    <input type="password" id="id" placeholder="비밀번호를 입력하세요." v-model="userPassword.oldPassword">
                 </dd>
                 <div class="hr"></div>
-                <dd >
-                    <label for="pw">비밀번호</label>
-                    <input type="text" id="pw" placeholder="비밀번호를 입력하세요.">
-                    <div class="invalid-feedback"><img :src="erroricon" alt=""><span>영문, 숫자, 특수문자를 최소 한가지씩 조합하고 8자 이상 ~ 20자 이내로 입력해주세요.</span></div>
+                <dd>
+                    <label for="pw">새 비밀번호</label>
+                    <input type="password" id="pw" placeholder="새 비밀번호를 입력하세요." v-model="userPassword.newPassword"
+                        @input="validatePassword">
+                    <div class="invalid-feedback" v-if="!isPasswordValid && userPassword.newPassword !== null">
+                        <img :src="erroricon" alt="">
+                        <span>영문, 숫자, 특수문자를 최소 한 가지씩 조합하고 8자 이상 ~ 20자 이내로 입력해주세요.</span>
+                    </div>
                 </dd>
                 <div class="hr"></div>
-                <dd >
-                    <label for="pw">비밀번호</label>
-                    <input type="text" id="pw" placeholder="비밀번호를 입력하세요.">
-                    
+                <dd>
+                    <label for="pwCheck">새 비밀번호 확인</label>
+                    <input type="password" id="pwCheck" placeholder="새 비밀번호를 입력하세요." v-model="newPasswordCheck">
+                    <div class="invalid-feedback" v-if="newPasswordCheck !== null && !passwordsMatch">
+                        <img :src="erroricon" alt=""><span>비밀번호가 일치하지 않습니다.</span>
+                    </div>
                 </dd>
             </dl>
         </form>
         <div class="btn-group flex-end">
-            <button class="signout">회원탈퇴</button>
-            <button class="update">수정</button>
+            <button class="signout" type="button" @click="fnDeleteUser">회원탈퇴</button>
+            <button class="update" type="button" @click="fnUpdateUser">수정</button>
         </div>
     </div>
 </template>
 
 <script>
+import axios from "axios";
+import { updateUsers, logOutProc, updatePassword } from "../../../resources/api/user"
 export default {
-  data() {
-    return {
-      // Define the image sources
-      homeicon: 'client/resources/images/icon/home.png',
-      erroricon: 'client/resources/images/icon/error.png',
-      righticon: 'client/resources/images/icon/right.png',
-    };
-  }
+    data() {
+        return {
+            // Define the image sources
+            homeicon: 'client/resources/images/icon/home.png',
+            erroricon: 'client/resources/images/icon/error.png',
+            righticon: 'client/resources/images/icon/right.png',
+
+            userInfo: {
+                userNm: this.$store.state.userNm,
+                userSttus: "1",
+                useAt: "Y"
+            },
+
+            userPassword: {
+                oldPassword: null,
+                newPassword: null
+            },
+            newPasswordCheck: null,
+            isPasswordValid: false // 비밀번호 유효성 체크를 위한 변수
+
+        };
+    },
+    methods: {
+        resetForm() {
+            // 사용자 정보 초기화
+            this.userPassword = {
+                oldPassword: null,
+                newPassword: null,
+            };
+            this.newPasswordCheck = null; // 비밀번호 확인 초기화
+        },
+        validatePassword() {
+            // 빈 문자열이나 null 체크
+            if (!this.userPassword.newPassword) {
+                this.isPasswordValid = false; // 빈 문자열일 경우 유효성 false
+                return;
+            }
+
+            // 정규식: 영문, 숫자, 특수문자를 최소 한 가지씩 조합하고 8자 이상 20자 이내
+            const passwordRegex = /^(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[!@#$%^&*])[A-Za-z\d!@#$%^&*]{8,20}$/;
+            this.isPasswordValid = passwordRegex.test(this.userPassword.newPassword);
+        },
+        async fnDeleteUser() {
+            try {
+                this.userInfo.userSttus = "0";
+                this.userInfo.useAt = "N";
+                // 사용자 정보를 업데이트하는 API 호출
+                const response = await updateUsers(this.$store.state.userId, this.userInfo);
+
+                console.log(response); // 응답 확인
+
+                if (response.status === 200) {
+                    logOutProc()
+                        .then(() => {
+                            console.log('로그아웃 성공 - 서버 측 쿠키 삭제 완료');
+                            this.$store.commit('setStoreReset'); // 로그아웃 성공 후 스토어 초기화
+                            this.$router.push({ path: '/Login.page' }); // 로그인 페이지로 리다이렉트
+                        })
+                        .catch(err => {
+                            console.error('로그아웃 처리 중 오류:', err);
+                            this.$store.commit('setStoreReset'); // 오류가 있어도 스토어는 초기화
+                            this.$router.push({ path: '/Login.page' }); // 로그인 페이지로 리다이렉트
+                        });
+                }
+            } catch (error) {
+                console.error("User error:", error); // 에러 로그
+                const message = error.response?.data?.message || "회원탈퇴퇴에 실패했습니다.";
+                alert(message);
+            }
+        },
+        //사용자 이름 벨류데이션 체크
+        isValidationUser() {
+            return this.userInfo.userNm == null || this.userInfo.userNm == '';
+        },
+        //사용자 비밀번호 벨류데이션 체크
+        isValidationPasswdord() {
+            return this.userPassword.oldPassword == null || this.userPassword.oldPassword == '' || this.userPassword.newPassword == null || this.userPassword.newPassword == '' || this.newPasswordCheck == null || this.newPasswordCheck == ''
+        },
+        async fnUpdateUser() {
+            if (this.isValidationUser()) {
+                if (this.isValidationPasswdord()) {
+                    alert("수정 할 내용이 없습니다.");
+                } else {
+                    if (confirm("비밀번호 변경을 하시겠습니까?")) {
+                        const response = await updatePassword(this.$store.state.userId, this.userPassword);
+                        if (response.status == 200) {
+                            this.resetForm();
+                            alert("비밀번호가 변경되었습니다.");
+                            window.location.reload(); // 페이지 새로 고침
+                        }
+                    }
+                }
+            } else {
+                if (this.$store.state.userNm !== this.userInfo.userNm) {
+                    if (this.isValidationPasswdord()) {
+                        if (confirm("회원정보를 변경을 하시겠습니까?")) {
+                            const response = await updateUsers(this.$store.state.userId, this.userInfo);
+                            if (response.status == 200) {
+                                this.$store.commit("setUserNm", this.userInfo.userNm);
+                                this.resetForm();
+                                alert("회원정보가 변경되었습니다.");
+                                window.location.reload(); // 페이지 새로 고침
+                            }
+                        }
+                    } else {
+                        if (confirm("회원과 비밀번호를 변경하시겠습니까?")) {
+                            const res = await updateUsers(this.$store.state.userId, this.userInfo);
+                            const response = await updatePassword(this.$store.state.userId, this.userPassword);
+                            if (res.status == 200 && response.status == 200) {
+                                this.resetForm();
+                                alert("회원과 비밀번호를 변경되었습니다.");
+                                window.location.reload(); // 페이지 새로 고침
+                            }
+                        }
+                    }
+                } else {
+                    if (this.isValidationPasswdord()) {
+                        alert("수정 할 내용이 없습니다.");
+                    } else {
+                        if (confirm("비밀번호 변경을 하시겠습니까?")) {
+                            const response = await updatePassword(this.$store.state.userId, this.userPassword);
+                            if (response.status == 200) {
+                                this.resetForm();
+                                alert("비밀번호가 변경되었습니다.");
+                                window.location.reload(); // 페이지 새로 고침
+                            }
+                        }
+                    }
+                }
+            }
+        },
+    },
+    watch: {},
+    computed: {
+        passwordsMatch() {
+            return this.userPassword.newPassword === this.newPasswordCheck;
+        }
+    },
+    components: {},
+    mounted() { },
 };
-</script>
+</script>
(파일 끝에 줄바꿈 문자 없음)
Add a comment
List