Skip to content

Commit

Permalink
feat: 로그인 구현 1차 (#25)
Browse files Browse the repository at this point in the history
  • Loading branch information
jm3789 committed Dec 15, 2023
1 parent 95af067 commit 191715f
Show file tree
Hide file tree
Showing 8 changed files with 173 additions and 52 deletions.
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,16 @@
"lint": "next lint"
},
"dependencies": {
"@auth/prisma-adapter": "^1.0.11",
"@emotion/react": "^11.11.1",
"@emotion/styled": "^11.11.0",
"@fontsource/roboto": "^5.0.8",
"@mui/icons-material": "^5.14.18",
"@mui/lab": "^5.0.0-alpha.155",
"@mui/material": "^5.14.18",
"bcryptjs": "^2.4.3",
"@mui/x-date-pickers": "^6.18.3",
"@prisma/client": "^5.6.0",
"bcryptjs": "^2.4.3",
"dayjs": "^1.11.10",
"fabric": "^5.3.0",
"material-ui-popup-state": "^5.0.10",
Expand Down
30 changes: 30 additions & 0 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,42 @@ datasource db {
url = env("DATABASE_URL")
}

model Account {
id String @id @map("_id") @db.ObjectId @default(auto())
userId String @db.ObjectId
providerType String
providerId String
providerAccountId String
refreshToken String?
accessToken String?
accessTokenExpires DateTime?
createdAt DateTime? @default(now())
updatedAt DateTime? @updatedAt
user User @relation(fields: [userId], references: [id])
@@unique([providerId, providerAccountId])
}

model Session {
id String @id @map("_id") @db.ObjectId @default(auto())
userId String @db.ObjectId
expires DateTime
sessionToken String @unique
accessToken String @unique
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
user User @relation(fields: [userId], references: [id])
}

model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
email String @unique
password String
nickname String
todos Todo[]
createdAt DateTime? @default(now())
updatedAt DateTime? @updatedAt
accounts Account[]
sessions Session[]
}

model Todo {
Expand Down
10 changes: 10 additions & 0 deletions src/AuthSession.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/* eslint-disable react/prop-types */

'use client';

import React from 'react';
import { SessionProvider } from 'next-auth/react';

export default function AuthSession({ children }) {
return <SessionProvider>{children}</SessionProvider>;
}
39 changes: 0 additions & 39 deletions src/app/api/auth/[...nextauth].js

This file was deleted.

82 changes: 82 additions & 0 deletions src/app/api/auth/[...nextauth]/route.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
/* eslint-disable no-console */

import bcrypt from 'bcryptjs';
import NextAuth from 'next-auth';
import CredentialsProvider from 'next-auth/providers/credentials';
import { PrismaAdapter } from '@auth/prisma-adapter';
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

const handler = NextAuth({
adapter: PrismaAdapter(prisma),
providers: [
CredentialsProvider({
name: 'Credentials',
credentials: {
email: {
label: 'Email',
type: 'text',
placeholder: '이메일 주소 입력',
},
password: {
label: 'Password',
type: 'password',
placeholder: '비밀번호 입력',
},
},
// 승인
async authorize(credentials) {
if (!credentials?.email || !credentials?.password) {
return null;
}
// Prisma를 사용하여 유저 정보를 가져옴
const user = await prisma.user.findUnique({
where: { email: credentials.email },
});

console.log(user);

if (!user) {
return null;
}
const isCorrectPassword = await bcrypt.compare(
credentials.password,
user.password,
);

if (!isCorrectPassword) {
return null;
}
console.log('로그인 완료');
return user;
},
}),
],
session: {
strategy: 'jwt',
},
callbacks: {
async jwt({ token, user, session }) {
if (user) {
return {
...token,
id: user.id,
};
}
return token;
},
async session({ session, token, user }) {
return {
...session,
user: {
...session.user,
id: token.id,
},
};
},
},
secret: process.env.NEXTAUTH_SECRET,
});

export { handler as GET, handler as POST };
5 changes: 3 additions & 2 deletions src/app/layout.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import './globals.css';
import { Container } from '@mui/material';
import Header from '../components/header';
import Footer from '../components/footer';
import AuthSession from '../AuthSession';

const inter = Inter({ subsets: ['latin'] });

Expand All @@ -18,8 +19,8 @@ export default function RootLayout({ children }) {
<html lang="en">
<body className={inter.className}>
<Header />
<Container sx={{ height: '100%', overflow: 'hidden' }}>
{children}
<Container sx={{ height: '100%', overflow: 'scroll' }}>
<AuthSession>{children}</AuthSession>
</Container>
<Footer />
</body>
Expand Down
20 changes: 16 additions & 4 deletions src/app/login/page.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

/* eslint-disable no-console, no-alert */

import { signIn } from 'next-auth/react';
import React, { useState } from 'react';
import {
Box,
Expand All @@ -20,14 +21,25 @@ export default function Login() {

const [isChecked, setChecked] = useState(false);

const handleLoginSubmit = (e) => {
const handleLoginSubmit = async (e) => {
e.preventDefault();
alert(`로그인 완료: ${email}`);
window.location = '/';
console.log(`이메일: ${email}`);
const result = await signIn('credentials', {
email,
password,
redirect: false,
});
if (!result.error) {
alert(`로그인 완료: ${email}`);
window.location = '/';
} else {
console.error(result.error);
alert('로그인 실패');
}
};

const handleChecked = (e) => {
// console.log(`${e.target.checked}`);
console.log(`${e.target.checked}`);
setChecked(e.target.checked);
};

Expand Down
36 changes: 30 additions & 6 deletions src/app/user/page.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,45 @@

import React from 'react';
import { Stack, Button, Link } from '@mui/material';
import { useSession, signOut } from 'next-auth/react';

const handleLogoutSubmit = (e) => {
e.preventDefault();
window.location = '/login';
signOut({ callbackUrl: '/', redirect: false });
alert('로그아웃되었습니다.');
};

export default function User() {
const { session, status } = useSession();

return (
<div>
<div style={{ display: 'flex', justifyContent: 'flex-end' }}>
<Button variant="text" onClick={handleLogoutSubmit} sx={{ margin: 3 }}>
로그아웃
</Button>
</div>
{status === 'authenticated' ? (
<div style={{ display: 'flex', justifyContent: 'flex-end' }}>
<Button
variant="text"
onClick={handleLogoutSubmit}
sx={{ margin: 3 }}
>
로그아웃
</Button>
{/* 현재 로그인중인 사용자 이메일 표시 */}
<div>
현재 로그인:
{status === 'authenticated' ? session?.user?.email : 'X'}
</div>
</div>
) : (
<div style={{ display: 'flex', justifyContent: 'flex-end' }}>
<Link href="/register" underline="hover" sx={{ margin: 1 }}>
회원가입
</Link>
<Link href="/login" underline="hover" sx={{ margin: 1 }}>
로그인
</Link>
</div>
)}

<Stack spacing={10} sx={{ padding: 3 }}>
<Link href="/" color="inherit" underline="hover">
설정
Expand Down

0 comments on commit 191715f

Please sign in to comment.