Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[김혜선] sprint11 #684

Merged
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions @types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,3 +50,8 @@ export interface ISignUpUser {
password: string;
passwordConfirmation: string;
}

export interface ISignInUser {
email: string;
password: string;
}
39 changes: 34 additions & 5 deletions app/api/auth.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { ISignUpUser, IUser } from "@/@types";
import { ISignInUser, ISignUpUser, IUser } from "@/@types";
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

import type으로 작성하실 수 있을 것 같아요.

import { API_URL } from "@/app/containts";
import { saveTokens } from "./authTokens";

interface SignUpResponse {
success: boolean;
user: IUser;
message: string;
}

Expand All @@ -18,24 +18,53 @@ export async function signUp(data: ISignUpUser): Promise<SignUpResponse> {
body: JSON.stringify(data),
});
const json = await res.json();
//동일한 이메일, 닉네임이 있을 경우
if (res.status === 400) {
return {
success: true,
user: {} as IUser,
message: json.message,
};
} else {
return {
success: true,
user: json,
message: "회원 가입이 성공적으로 완료되었습니다.",
};
}
} catch (e) {
return {
success: false,
user: {} as IUser,
message: "회원 가입 중 오류가 발생했습니다. 다시 시도해주세요.",
};
}
}

//토큰 가져오기 -> 로그인 임
export async function signIn(userData: ISignInUser): Promise<SignUpResponse> {
const res = await fetch(`${API_URL}/auth/signIn`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(userData),
});
const json = await res.json();

// 토큰 저장
const accessToken = json.accessToken;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

destructuring 하면 좋을 것 같아요.

const refreshToken = json.refreshToken;
const userId = json.user.id;

saveTokens(accessToken, userId, refreshToken);

try {
return {
success: true,
message: "로그인이 성공적으로 완료되었습니다.",
};
} catch (e) {
return {
success: false,
message: "로그인 중 오류가 발생했습니다. 다시 시도해주세요.",
};
}
}
31 changes: 6 additions & 25 deletions app/api/authTokens.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,17 @@ import { API_URL } from "../containts";
// 토큰 저장 함수
export function saveTokens(
accessToken: string,
userid: string,
userid?: string,
refreshToken?: string
) {
localStorage.setItem("accessToken", accessToken);
if (refreshToken) {
localStorage.setItem("refreshToken", refreshToken);
}

//임시 유저 정보 저장
localStorage.setItem("userid", userid);
if (userid) {
//임시 유저 정보 저장
localStorage.setItem("userid", userid);
}
}

// 토큰 가져오기 함수
Expand All @@ -33,8 +34,7 @@ export async function refreshAccessToken(refreshToken: string) {
});
const data = await res.json();
const { accessToken } = data;
const { id } = data.user.id;
saveTokens(accessToken, id);
saveTokens(accessToken);
return accessToken;
}

Expand All @@ -44,29 +44,10 @@ export async function validateAndRefreshTokens() {
if (!accessToken || !refreshToken) {
throw new Error("No tokens found");
}

const isTokenExpired = false;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

false로 값을 고정시킨 이유가 있을까요.

if (isTokenExpired) {
return await refreshAccessToken(refreshToken);
}

return accessToken;
}

//토큰 가져오기
export async function getAccessToken() {
const res = await fetch(`${API_URL}/auth/signIn`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ email: "[email protected]", password: "z100004z" }),
});
const data = await res.json();
const accessToken = data.accessToken;
const refreshToken = data.refreshToken;
const userId = data.user.id;

// 토큰 저장
saveTokens(accessToken, userId, refreshToken);
}
2 changes: 1 addition & 1 deletion app/board/[id]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ export default function DetailBoard({ params }: { params: { id: string } }) {
{morePopup && (
<More
id={parseInt(params.id)}
url={`/editBoard/${params.id}`}
url={`/board/editBoard/${params.id}`}
funcName={deleteBoard}
redirectPageName="/board"
/>
Expand Down
2 changes: 1 addition & 1 deletion app/addBoard/page.tsx → app/board/addBoard/page.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"use client";
import styles from "./addBoard.module.css";
import { addBoard, uploadImage } from "../api/board";
import { addBoard, uploadImage } from "../../api/board";
import { useEffect, useRef, useState } from "react";
import FileInput from "@/components/fileInput";
import { useRouter } from "next/navigation";
Expand Down
17 changes: 4 additions & 13 deletions app/editBoard/[id]/page.tsx → app/board/editBoard/[id]/page.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"use client";
import styles from "../../addBoard/addBoard.module.css";
import { editBoard, getBoardItem, uploadImage } from "../../api/board";
import { editBoard, getBoardItem, uploadImage } from "@/app/api/board";
import { useEffect, useRef, useState } from "react";
import FileInput from "@/components/fileInput";
import { useRouter } from "next/navigation";
Expand Down Expand Up @@ -55,13 +55,6 @@ export default function EditBoard({ params }: { params: { id: string } }) {
setImage(file);
};

const handleTitleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const titleValue = e.target.value;
setBoardData((prevState) =>
prevState ? { ...prevState, title: titleValue } : null
);
};

if (!boardData) {
return;
}
Expand All @@ -80,9 +73,8 @@ export default function EditBoard({ params }: { params: { id: string } }) {
<input
type="text"
name="title"
value={boardData.title}
defaultValue={boardData.title}
id="title"
onChange={handleTitleChange}
placeholder="제목을 입력해주세요"
/>
</label>
Expand All @@ -94,9 +86,8 @@ export default function EditBoard({ params }: { params: { id: string } }) {
cols={30}
rows={10}
placeholder="내용을 입력해주세요"
>
{boardData.content && boardData.content}
</textarea>
defaultValue={boardData.content}
></textarea>
</label>
<label htmlFor="image" className={styles.imgTitle}>
이미지
Expand Down
17 changes: 14 additions & 3 deletions app/global.css
Original file line number Diff line number Diff line change
Expand Up @@ -124,9 +124,7 @@ table {
border-collapse: collapse;
border-spacing: 0;
}
body {
padding-top: 100px;
}

a {
color: inherit;
text-decoration: none;
Expand All @@ -141,6 +139,19 @@ h3 {
font-weight: 700;
margin-bottom: 24px;
}
.headerLeft {
display: flex;
align-items: center;
gap: 40px;
}
.nav {
display: flex;
gap: 40px;
}
.nav .active {
color: #3692ff;
font-weight: 600;
}

.primaryBtn {
background-color: #3692ff;
Expand Down
6 changes: 5 additions & 1 deletion app/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { Metadata } from "next";
import { Noto_Sans_KR } from "next/font/google";
import "./global.css";
import Header from "@/components/header";

const notoSansKr = Noto_Sans_KR({
// preload: true, 기본값
Expand All @@ -20,7 +21,10 @@ export default function RootLayout({
}>) {
return (
<html lang="ko">
<body className={notoSansKr.className}>{children}</body>
<body className={notoSansKr.className}>
<Header />
{children}
</body>
</html>
);
}
19 changes: 0 additions & 19 deletions app/page.tsx
Original file line number Diff line number Diff line change
@@ -1,22 +1,3 @@
"use client";
import Image from "next/image";
import styles from "./page.module.css";
import { getAccessToken } from "./api/authTokens";
import { useEffect } from "react";

export default function Home() {
//처음 메인 페이지 들어오면 토큰 발급
useEffect(() => {
const fetchAccessToken = async () => {
try {
const accessToken = await getAccessToken();
} catch (error) {
console.error("Error fetching access token:", error);
}
};

fetchAccessToken();
}, []); // 빈 배열은 컴포넌트가 처음 렌더링될 때 한 번만 실행

return <div>main</div>;
}
7 changes: 7 additions & 0 deletions app/product/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export default function Product() {
return (
<div>
<h1>product 페이지입니다.</h1>
</div>
);
}
Loading