
+++ client/resources/api/index.js
... | ... | @@ -0,0 +1,74 @@ |
1 | +import axios from "axios"; | |
2 | +import store from "../../views/pages/AppStore"; | |
3 | + | |
4 | +const apiClient = axios.create({ | |
5 | + headers: {'Content-Type': 'application/json; charset=UTF-8'} | |
6 | +}) | |
7 | + | |
8 | +apiClient.interceptors.request.use( | |
9 | + config => { | |
10 | + config.headers.Authorization = store.state.authorization // 요청 시 AccessToken 추가 | |
11 | + return config; | |
12 | + }, | |
13 | + error => { | |
14 | + return Promise.reject(error); | |
15 | + } | |
16 | +) | |
17 | + | |
18 | +async function refreshAccessToken() { | |
19 | + try { | |
20 | + const refreshToken = store.state.refreshToken; // 스토어에서 리프레시 토큰 가져오기 | |
21 | + | |
22 | + // 리프레시 토큰을 포함하여 재발급 요청 | |
23 | + const res = await axios.post('/refresh/tknReissue.json', { | |
24 | + refreshToken: refreshToken // 리프레시 토큰 본문에 포함 | |
25 | + }); | |
26 | + | |
27 | + if (res.headers.authorization) { | |
28 | + // 새로 발급받은 AccessToken 저장 | |
29 | + store.commit('setAuthorization', res.headers.authorization); | |
30 | + // 필요한 경우 리프레시 토큰도 업데이트 | |
31 | + // store.commit('setRefresh', res.headers.refresh); | |
32 | + } | |
33 | + | |
34 | + return res; // 응답 반환 | |
35 | + } catch (error) { | |
36 | + console.error('Error refreshing access token:', error); | |
37 | + alert('토큰 재발급에 실패했습니다. 다시 로그인 해주세요.'); | |
38 | + store.commit("setStoreReset"); | |
39 | + window.location = '/login.page'; // 로그인 페이지로 리다이렉트 | |
40 | + } | |
41 | +} | |
42 | + | |
43 | +apiClient.interceptors.response.use( | |
44 | + response => { | |
45 | + return response; | |
46 | + }, | |
47 | + async error => { | |
48 | + const originalReq = error.config; | |
49 | + | |
50 | + // 403 오류 처리: 접근 권한 없음 | |
51 | + if (error.response.status === 403 && error.response.data.message === '접근 권한이 없습니다.') { | |
52 | + window.history.back(); | |
53 | + return Promise.reject(error); | |
54 | + } | |
55 | + | |
56 | + // 401 오류 처리: 토큰 만료 | |
57 | + if (error.response.status === 401 && !originalReq._retry) { | |
58 | + originalReq._retry = true; // 재요청 시도 플래그 설정 | |
59 | + try { | |
60 | + // 액세스 토큰 재발급 요청 | |
61 | + await refreshAccessToken(); // 리프레시 함수 호출 | |
62 | + | |
63 | + // 원래 요청 재시도 | |
64 | + return apiClient(originalReq); | |
65 | + } catch (refreshError) { | |
66 | + return Promise.reject(refreshError); | |
67 | + } | |
68 | + } | |
69 | + | |
70 | + return Promise.reject(error); | |
71 | + } | |
72 | +) | |
73 | + | |
74 | +export default apiClient; |
+++ client/resources/api/logOut.js
... | ... | @@ -0,0 +1,10 @@ |
1 | +import apiClient from "./index"; | |
2 | +import store from '../../views/pages/AppStore'; | |
3 | + | |
4 | +export const logOutProc = () => { | |
5 | + return apiClient.post(`/user/logout.json`, {}, { | |
6 | + headers: { | |
7 | + 'refresh': store.state.refresh | |
8 | + } | |
9 | + }); | |
10 | +}(파일 끝에 줄바꿈 문자 없음) |
+++ client/resources/api/login.js
... | ... | @@ -0,0 +1,5 @@ |
1 | +import apiClient from "./index"; | |
2 | + | |
3 | +export const loginProc = mber => { | |
4 | + return apiClient.post(`/user/login.json`, mber); | |
5 | +}(파일 끝에 줄바꿈 문자 없음) |
--- client/views/pages/AppRouter.js
+++ client/views/pages/AppRouter.js
... | ... | @@ -1,4 +1,5 @@ |
1 | 1 |
import { createWebHistory, createRouter } from "vue-router"; |
2 |
+import store from "./AppStore"; |
|
2 | 3 |
|
3 | 4 |
// 공통페이지 |
4 | 5 |
import Login from "./login/Login.vue"; |
... | ... | @@ -24,6 +25,21 @@ |
24 | 25 |
|
25 | 26 |
AppRouter.beforeEach((to, from, next) => { |
26 | 27 |
const routeExists = AppRouter.getRoutes().some(route => route.path === to.path || (route.name && route.name === to.name)); |
28 |
+ const authorState = store.state.roles; |
|
29 |
+ const { authorization } = to.meta; |
|
30 |
+ |
|
31 |
+ // 토큰이 없을 경우 |
|
32 |
+ if (authorState == null && to.path != '/login.page') { |
|
33 |
+ alert('로그인이 필요합니다.'); |
|
34 |
+ return next('/login.page'); |
|
35 |
+ } |
|
36 |
+ // 권한이 없을 경우 |
|
37 |
+ if(authorization){ |
|
38 |
+ if(!authorization.includes(authorState[0].authority)){ |
|
39 |
+ alert('접근 권한이 없습니다.'); |
|
40 |
+ return next(from.path); |
|
41 |
+ } |
|
42 |
+ } |
|
27 | 43 |
if (!routeExists) { |
28 | 44 |
next({ name: 'NotFoundPage' }); |
29 | 45 |
return; |
--- client/views/pages/AppStore.js
+++ client/views/pages/AppStore.js
... | ... | @@ -1,10 +1,63 @@ |
1 | 1 |
import { createStore } from "vuex"; |
2 | 2 |
import createPersistedState from "vuex-persistedstate"; |
3 |
+import { logOutProc } from "../../resources/api/logOut"; |
|
3 | 4 |
|
4 | 5 |
export default createStore({ |
5 | 6 |
plugins: [createPersistedState()], |
6 |
- state: {}, |
|
7 |
- getters: {}, |
|
8 |
- mutations: {}, |
|
9 |
- actions: {}, |
|
7 |
+ state: { |
|
8 |
+ authorization: null, |
|
9 |
+ // refresh: null, |
|
10 |
+ roles: [{authority: "ROLE_USER"}], |
|
11 |
+ }, |
|
12 |
+ getters: { |
|
13 |
+ getAuthorization: function () {}, |
|
14 |
+ // getRefresh: function () {}, |
|
15 |
+ getUserNm: function () {}, |
|
16 |
+ getRoles: function () {}, |
|
17 |
+ }, |
|
18 |
+ mutations: { |
|
19 |
+ setAuthorization(state, newValue) { |
|
20 |
+ state.authorization = newValue; |
|
21 |
+ }, |
|
22 |
+ // setRefresh(state, newValue) { |
|
23 |
+ // state.refresh = newValue; |
|
24 |
+ // }, |
|
25 |
+ setUserNm(state, newValue) { |
|
26 |
+ state.userNm = newValue; |
|
27 |
+ }, |
|
28 |
+ setUserId(state, newValue) { |
|
29 |
+ state.userId = newValue; |
|
30 |
+ }, |
|
31 |
+ setRoles(state, newValue) { |
|
32 |
+ state.roles = newValue; |
|
33 |
+ }, |
|
34 |
+ setStoreReset(state) { |
|
35 |
+ state.authorization = null; |
|
36 |
+ // state.refresh = null; |
|
37 |
+ state.userNm = null; |
|
38 |
+ state.userId = null; |
|
39 |
+ state.roles = [{authority: "ROLE_USER"}]; |
|
40 |
+ }, |
|
41 |
+ }, |
|
42 |
+ actions: { |
|
43 |
+ async logout({ commit }) { |
|
44 |
+ try { |
|
45 |
+ const res = await logOutProc(); |
|
46 |
+ alert(res.data.message); |
|
47 |
+ if (res.status == 200) { |
|
48 |
+ commit("setStoreReset"); |
|
49 |
+ } |
|
50 |
+ } catch(error) { |
|
51 |
+ const errorData = error.response.data; |
|
52 |
+ if (errorData.message != null && errorData.message != "") { |
|
53 |
+ alert(error.response.data.message); |
|
54 |
+ } else { |
|
55 |
+ alert("에러가 발생했습니다.\n관리자에게 문의해주세요."); |
|
56 |
+ } |
|
57 |
+ } |
|
58 |
+ }, |
|
59 |
+ setStoreReset({commit}) { |
|
60 |
+ commit("setStoreReset"); |
|
61 |
+ } |
|
62 |
+ }, |
|
10 | 63 |
});(파일 끝에 줄바꿈 문자 없음) |
--- client/views/pages/login/Login.vue
+++ client/views/pages/login/Login.vue
... | ... | @@ -1,6 +1,6 @@ |
1 | 1 |
<template> |
2 | 2 |
<div class="content"> |
3 |
- <div class="sub-title-area mb-110"> |
|
3 |
+ <div class="sub-title-area mb-110"> |
|
4 | 4 |
<h2>로그인</h2> |
5 | 5 |
<div class="breadcrumb-list"> |
6 | 6 |
<ul> |
... | ... | @@ -10,17 +10,18 @@ |
10 | 10 |
<li>로그인</li> |
11 | 11 |
</ul> |
12 | 12 |
</div> |
13 |
- </div> |
|
13 |
+ </div> |
|
14 | 14 |
<form action="login" class="login-form"> |
15 | 15 |
<dl> |
16 | 16 |
<dd class="mb-25"> |
17 | 17 |
<label for="id">아이디</label> |
18 |
- <input type="text" id="id" class="wfull" placeholder="아이디를 입력하세요."> |
|
18 |
+ <input type="text" id="id" class="wfull" placeholder="아이디를 입력하세요." v-model="member['loginId']"> |
|
19 | 19 |
</dd> |
20 |
- |
|
20 |
+ |
|
21 | 21 |
<dd class="mb-10"> |
22 | 22 |
<label for="pw">비밀번호</label> |
23 |
- <input type="text" id="pw" class="wfull" placeholder="비밀번호를 입력하세요."> |
|
23 |
+ <input type="password" id="pw" class="wfull" placeholder="비밀번호를 입력하세요." v-model="member['password']" |
|
24 |
+ @keyup.enter="fnLogin"> |
|
24 | 25 |
</dd> |
25 | 26 |
<dd class="check-area flex-end mb-25"> |
26 | 27 |
<input type="checkbox" class="margin-top"> |
... | ... | @@ -28,20 +29,78 @@ |
28 | 29 |
</dd> |
29 | 30 |
</dl> |
30 | 31 |
<!-- Bind the image source dynamically for loginicon --> |
31 |
- <button><img :src="loginicon" alt="Login Icon"><span>로그인</span></button> |
|
32 |
+ <button type="button" @click="fnLogin"><img :src="loginicon" alt="Login Icon"><span>로그인</span></button> |
|
32 | 33 |
</form> |
33 | 34 |
</div> |
34 | 35 |
</template> |
35 | 36 |
|
36 | 37 |
<script> |
38 |
+import { useStore } from "vuex"; |
|
39 |
+import { loginProc } from "../../../resources/api/login"; |
|
40 |
+import axios from "axios"; |
|
41 |
+ |
|
37 | 42 |
export default { |
38 |
- data() { |
|
39 |
- return { |
|
40 |
- // Define the image sources |
|
41 |
- homeicon: 'client/resources/images/icon/home.png', |
|
42 |
- loginicon: 'client/resources/images/icon/lock.png', |
|
43 |
- righticon: 'client/resources/images/icon/right.png', |
|
44 |
- }; |
|
45 |
- } |
|
43 |
+ data() { |
|
44 |
+ return { |
|
45 |
+ // Define the image sources |
|
46 |
+ homeicon: 'client/resources/images/icon/home.png', |
|
47 |
+ loginicon: 'client/resources/images/icon/lock.png', |
|
48 |
+ righticon: 'client/resources/images/icon/right.png', |
|
49 |
+ |
|
50 |
+ member: { |
|
51 |
+ loginId: null, |
|
52 |
+ password: null, |
|
53 |
+ }, |
|
54 |
+ store: useStore(), |
|
55 |
+ }; |
|
56 |
+ }, |
|
57 |
+ methods: { |
|
58 |
+ async fnLogin() { |
|
59 |
+ try { |
|
60 |
+ const response = await axios.post("/user/login.json", this.member, { |
|
61 |
+ headers: { |
|
62 |
+ "Content-Type": "application/json; charset=UTF-8", |
|
63 |
+ }, |
|
64 |
+ }); |
|
65 |
+ |
|
66 |
+ console.log(response); // 응답 확인 |
|
67 |
+ |
|
68 |
+ if (response.status === 200) { |
|
69 |
+ // 토큰 저장 로직 |
|
70 |
+ this.$store.commit("setAuthorization", response.headers.authorization); |
|
71 |
+ /** jwt토큰 복호화 **/ |
|
72 |
+ const base64String = this.$store.state.authorization.split(".")[1]; |
|
73 |
+ const base64 = base64String.replace(/-/g, "+").replace(/_/g, "/"); |
|
74 |
+ const jsonPayload = decodeURIComponent( |
|
75 |
+ atob(base64) |
|
76 |
+ .split("") |
|
77 |
+ .map((c) => { |
|
78 |
+ return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2); |
|
79 |
+ }) |
|
80 |
+ .join("") |
|
81 |
+ ); |
|
82 |
+ const mbr = JSON.parse(jsonPayload); |
|
83 |
+ //const mbr = JSON.parse(decodeURIComponent(escape(window.atob(base64String)))); // jwt claim 추출 |
|
84 |
+ console.log("리멤버미~", mbr); |
|
85 |
+ this.$store.commit("setUserId", mbr.userId); |
|
86 |
+ this.$store.commit("setUserNm", mbr.userNm); |
|
87 |
+ this.$store.commit("setRoles", mbr.roles); |
|
88 |
+ /** jwt토큰 복호화 **/ |
|
89 |
+ |
|
90 |
+ // 리다이렉트 처리 |
|
91 |
+ this.$router.push("/"); |
|
92 |
+ } |
|
93 |
+ } catch (error) { |
|
94 |
+ console.error("Login error:", error); // 에러 로그 |
|
95 |
+ const message = error.response?.data?.message || "로그인에 실패했습니다."; |
|
96 |
+ alert(message); |
|
97 |
+ } |
|
98 |
+ } |
|
99 |
+ }, |
|
100 |
+ watch: {}, |
|
101 |
+ computed: {}, |
|
102 |
+ components: {}, |
|
103 |
+ created() { }, |
|
104 |
+ mounted() { }, |
|
46 | 105 |
}; |
47 | 106 |
</script> |
Add a comment
Delete comment
Once you delete this comment, you won't be able to recover it. Are you sure you want to delete this comment?