Skip to content

Commit

Permalink
Feature: 로그인 기능 구현
Browse files Browse the repository at this point in the history
- 토큰을 받아서 쿠키에 저장함
    - 사실 토큰은 없어도 기능에 문제 없음
    - But, 학번만으로 예약 가능하면 악용 가능성있으므로 차단
- libraryRequest.js: 핸들러 추가하여 로깅
- TODOS
    - 자동 로그인 구현
        - 토큰 확인만 하면 됨
    - 로깅한 것 DEV에서만 하도록 해야함
  • Loading branch information
NohJanghan committed Sep 23, 2024
1 parent 9c25ec7 commit 87820af
Show file tree
Hide file tree
Showing 4 changed files with 197 additions and 29 deletions.
107 changes: 107 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
"gatsby": "^5.13.7",
"gatsby-source-filesystem": "^5.13.1",
"react": "^18.2.0",
"react-cookie": "^7.2.0",
"react-day-picker": "^9.0.9",
"react-dom": "^18.2.0",
"swiper": "^11.1.14"
Expand Down
38 changes: 32 additions & 6 deletions src/pages/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ import Header from "../components/header"
import "swiper/css";
import "swiper/css/pagination";
import { logInFormContainer } from "../styles/logInForm.module.css"
import { login } from "../scripts/libraryRequest"
import { navigate } from "gatsby"
import { useCookies } from "react-cookie"


const IndexPage = () => {
Expand All @@ -22,13 +25,36 @@ const IndexPage = () => {
[e.target.name]: e.target.value
})
}

const [cookies, setCookie, removeCookie] = useCookies(['accessToken', 'refreshToken', 'tokenType', 'userId'])
async function onClickLogin(e) {
console.log('[Login] try to login')
if(e.target.disabled) {
alert("로그인중입니다.")
return false
}

function login(e) {
console.log('try to login')
e.target.disabled = true
// await login(userData)
// TODO: 로그인 함수 구현 필요
e.target.disabled = false
// 로그인 처리
const userId = userData.id
await login(userData.id, userData.pw).then((res) => {
if(res.status === 400 || res.status === 401) {
alert("입력한 정보를 다시 확인해주세요.")
e.target.disabled = false
} else if(res.status === 200) {
setCookie('accessToken', res.data['access_token'], {path: '/', maxAge: res.data['expires_in']})
setCookie('refreshToken', res.data['refresh_token'])
setCookie('tokenType', res.data['token_type'])
setCookie('userId', userId)
navigate('/reservation')
} else {
throw new Error(res)
}
}).catch((err) => {
alert('로그인에 실패했습니다. 다시 시도해주세요.')
e.target.disabled = false
console.error(err)
})
}
return (
<Swiper
Expand Down Expand Up @@ -66,7 +92,7 @@ const IndexPage = () => {
<div>
<input onChange={onInputChange} value={userData.pw} placeholder="Password" type="password" name="pw"/>
</div>
<button onClick={login} type="button">Log in</button>
<button onClick={onClickLogin} type="button">Log in</button>
</form>
</div>
</Layout>
Expand Down
80 changes: 57 additions & 23 deletions src/scripts/libraryRequest.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,36 @@
import axios from 'axios'
import axios, { AxiosError } from 'axios'

const requestUrl = 'https://n1ba6bpzj7.execute-api.ap-northeast-2.amazonaws.com/default/'

function httpResponseHandler(res) {
console.log(`[HttpRequest Done] ${res.status} | ${JSON.stringify(res.data)}`)
// 예외처리는 실제로 데이터 처리하는 곳에서 하기로 함
// if(res.status !== 200) {
// return {
// status: res.status,
// body: res.data
// }
// } else {
// return res.data
// }
return res
}

function axiosErrorHandler(err) {
if(err instanceof AxiosError) {
//handle
if(err.response) {
return {
status: err.response.status,
data: err.response.data
}
}
} else {
console.error('❌ AxiosError: ' + err)
throw err
}
}

// Access Token 요청
// 방 예약에 필요 없음
export async function login(id, pw) {
Expand All @@ -13,13 +42,12 @@ export async function login(id, pw) {
password: pw
}
// 포스트 요청에 param을 넘기기 위해서 data에 null을 전달해야함
await axios.post(requestUrl + "oauth/token", null, {params: params}, {
await axios.post(requestUrl + "oauth/token", params, {headers: {"Content-Type": 'application/x-www-form-urlencoded'}}, {
// withCredentials: true // HTTPonly Cookie 설정을 위함. but 도서관 서버에서 쿠키를 안씀.
}).then((res) => {
console.log(res)
data = res
}).catch(console.error)
return data.data
}).then(httpResponseHandler).then((body) => data = body).catch((err) => {
data = axiosErrorHandler(err)
})
return data
}

export async function refresh(refresh_token) {
Expand All @@ -30,13 +58,12 @@ export async function refresh(refresh_token) {
refresh_token: refresh_token
}
// 포스트 요청에 param을 넘기기 위해서 data에 null을 전달해야함
await axios.post(requestUrl + "oauth/token", null, {params: params}, {
await axios.post(requestUrl + "oauth/token", params, {headers: {'Content-Type': 'application/x-www-form-urlencoded'}}, {
// withCredentials: true // HTTPonly Cookie 설정을 위함. but 도서관 서버에서 쿠키를 안씀.
}).then((res) => {
console.log(res)
data = res
}).catch(console.error)
return data.data
}).then(httpResponseHandler).then((body) => data = body).catch((err) => {
data = axiosErrorHandler(err)
})
return data
}

export async function getReservedDates(userId, startDate, endDate, roomId) {
Expand All @@ -47,23 +74,26 @@ export async function getReservedDates(userId, startDate, endDate, roomId) {
ROOM_ID: roomId
}
await axios.get(requestUrl + "api/v1/mylibrary/facilityreservation/" + userId,{params: params}
).then((res) => {
data = res
}).catch(console.error)
return data.data.result
).then(httpResponseHandler).then((body) => data = body).catch((err) => {
data = axiosErrorHandler(err)
})
return data.result
}

export async function getUserInfo(userId, targetDate) {
export async function getUserInfo(userId, targetDate = undefined) {
let data = {}
const params = targetDate ? {RES_YYYYMMDD: targetDate} : {}

data = await axios.get(requestUrl + "api/v1/mylibrary/facilityreservation/info/" + userId, {params: params})

return data.data
await axios.get(requestUrl + "api/v1/mylibrary/facilityreservation/info/" + userId, {params: params})
.then(httpResponseHandler).then((body) => data = body).catch((err) => {
data = axiosErrorHandler(err)
})
return data
}

// 방 정보 요청
export async function getRoomInfo(userId, roomId, date) {
let data = {}
const params = {
ROOM_ID: roomId,
RES_YYYYMMDD: date
Expand All @@ -72,7 +102,11 @@ export async function getRoomInfo(userId, roomId, date) {
// END_DT_YYYYMMDD
}

return await axios.get(requestUrl + "api/v1/mylibrary/facilityreservation/room/" + userId, {params: params}).then((res) => res.data)
await axios.get(requestUrl + "api/v1/mylibrary/facilityreservation/room/" + userId, {params: params}).then((res) => res.data)
.then(httpResponseHandler).then((body) => data = body).catch((err) => {
data = axiosErrorHandler(err)
})
return data
}

// 예약 요청
Expand All @@ -87,7 +121,7 @@ export async function reserveRoom(userId, roomId, date, time, remark = '', isAdm
}

// post 요청시에는 data에 null을 전달해야함.
await axios.post(requestUrl + "api/v1/mylibrary/facilityreservation/room/" + userId, null, {params: params})
await axios.post(requestUrl + "api/v1/mylibrary/facilityreservation/room/" + userId, null, {params: params}).then(httpResponseHandler)
// no return
return null
}
Expand Down

0 comments on commit 87820af

Please sign in to comment.