Commit 26b784d8 authored by Kim, Subin's avatar Kim, Subin
Browse files

Merge remote-tracking branch 'origin/rkyoung7'

parents 4e0be6e8 22f69a2a
......@@ -2,12 +2,19 @@ import axios from "axios";
const signup = async (user) => {
const url = `/api/auth/signup`;
const { data } = await axios.post(url, user);
return data
const { data, status } = await axios.post(url, user);
return { data, status }
}
const login = async (user) => {
const url = `/api/auth/login`;
const { data, status } = await axios.post(url, user);
return { data, status }
}
const authApi = {
signup
signup,
login
};
export default authApi
\ No newline at end of file
import React from 'react';
import { Link } from "react-router-dom";
import { useState } from 'react';
import { Redirect, Link } from "react-router-dom";
import { Formik } from 'formik';
import * as Yup from 'yup';
import authApi from '../../apis/auth.api';
import catchErrors from "../../utils/catchErrors.js";
const LoginForm = () => {
const [success, setSuccess] = useState(false);
const [error, setError] = useState("");
if (success) {
return <Redirect to="/home" />;
}
return (
<>
<Formik
......@@ -17,9 +25,17 @@ const LoginForm = () => {
password: Yup.string()
.required('비밀번호를 입력해주세요.'),
})}
onSubmit={(values, { setSubmitting }) => {
onSubmit={async (values, { setSubmitting }) => {
try {
setError("")
const result = await authApi.login(values)
if (result.status === 201) {
setSuccess(true)
}
} catch (error) {
catchErrors(error, setError)
}
setTimeout(() => {
alert(JSON.stringify(values, null, 2));
setSubmitting(false);
}, 400);
}}
......
import React from 'react';
import { useState } from 'react';
import { Redirect } from "react-router-dom";
import { Formik } from 'formik';
import * as Yup from 'yup';
import authApi from '../../apis/auth.api';
import catchErrors from "../../utils/catchErrors.js";
const SignupForm = () => {
const [success, setSuccess] = useState(false);
const [error, setError] = useState("");
if (success) {
return <Redirect to="/login" />;
}
return (
<>
<div className="py-5">
......@@ -34,9 +44,19 @@ const SignupForm = () => {
.required('학번을 입력해주세요.')
.min(7, '학번을 정확히 입력해주세요.'),
})}
onSubmit={(values, { setSubmitting }) => {
onSubmit={async (values, { setSubmitting }) => {
try {
setError("")
const result = await authApi.signup(values)
// console.log('회원가입 요청 후 result 확인', result, '|', result.status)
if (result.status === 201) {
alert("회원가입이 완료되었습니다.")
setSuccess(true)
}
} catch (error) {
catchErrors(error, setError)
}
setTimeout(() => {
alert(JSON.stringify(values, null, 2));
setSubmitting(false);
}, 400);
}}
......
const config = {
env: process.env.NODE_ENV === 'production' ? 'production' : 'development',
port: process.env.PORT || 3001,
jwtSecret: 'lrfp8sQdoLG6eT',
jwtExpires: '30d',
cookieName: 'todayku',
cookieNameMb: 'confirmNum',
cookieMaxAge: 60 * 60 * 24 * 30 * 1000,
}
export default config
\ No newline at end of file
import jwt from "jsonwebtoken";
import { User } from '../db/index.js';
import config from "../config/app.config.js";
const signup = async (req, res) => {
console.log('server/signup req.body', req.body)
const { userId, password, userName, userStudNum } = req.body;
try {
const findId = await User.findOne({ where: { userID: userId } });
if (findId) {
throw new Error("이미 있는 회원정보 입니다.");
}
await User.create({
userID: userId,
password: password,
userName: userName,
studNum: userStudNum
});
res.status(201).json("success")
} catch (error) {
console.log(error)
return res.status(500).send(error.message || "회원가입 에러발생")
}
}
const login = async (req, res) => {
console.log('server/login req.body', req.body)
const { userId, password } = req.body;
try {
const user = await User.scope("withPassword").findOne({ where: { userID: userId } });
console.log('user확인', user)
if (!user) {
return res.status(404).send(`일치하는 정보가 없습니다.`);
}
const passwordMatch = await user.comparePassword(password);
if (passwordMatch) {
const signData = {
id: user.userID,
name: user.userName
};
const token = jwt.sign(signData, config.jwtSecret, {
expiresIn: config.jwtExpires,
});
res.cookie(config.cookieName, token, {
maxAge: config.cookieMaxAge,
path: "/",
httpOnly: config.env === "production",
secure: config.env === "production",
});
res.status(201).json(user)
} else {
res.status(401).send("비밀번호가 일치하지 않습니다.")
}
} catch (error) {
console.log(error)
return res.status(500).send("로그인 에러발생")
}
}
export default {
signup,
login
}
\ No newline at end of file
......@@ -7,9 +7,54 @@ const UserModel = (sequelize) => {
const User = sequelize.define(
"user",
{
userID:{
userID: {
type: DataTypes.STRING
},
userName: {
type: DataTypes.STRING
},
password: {
type: DataTypes.STRING
},
studNum: {
type: DataTypes.STRING
}
)
}
\ No newline at end of file
},
{
timestamps: true,
freezeTableName: true,
tableName: "users",
defaultScope: {
attributes: { exclude: ["password"] },
},
scopes: {
withPassword: {
attributes: { include: ["password"] },
},
},
}
);
User.beforeSave(async (user) => {
// if (!user.changed("password")) {
// return;
// }
if (user.password) {
const hashedPassword = await bcrypt.hash(user.password, 10);
user.password = hashedPassword;
}
});
User.prototype.comparePassword = async function (plainPassword) {
const passwordMatch = await bcrypt.compare(
plainPassword,
this.password
);
return passwordMatch;
};
return User
};
export default UserModel;
\ No newline at end of file
import express from "express";
import userRouter from './user.route.js';
const router = express.Router();
router.use('/auth', userRouter)
export default router;
\ No newline at end of file
import express from 'express';
import userCtrl from '../controllers/user.controller.js';
const router = express.Router();
router
.route("/signup")
.post(userCtrl.signup)
router
.route("/login")
.post(userCtrl.login)
export default router;
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment