Commit 42b6aaf5 authored by 이재연's avatar 이재연
Browse files

로그인 수정중

parent a870ddb1
const users=[
{ id:'wodus', password:'123'},
{id:'kim', password:'456'},
]
export function signIn({id,password}){
const user=users.find(user=>user.id===id && user.password===password);
if (user===undefined) throw new Error();
return user;
}
\ No newline at end of file
import React from 'react'
import {Route, Redirect} from "react-router-dom"
function AuthRoute({})
\ No newline at end of file
...@@ -2,20 +2,55 @@ import React, { useState, useEffect, useRef } from 'react'; ...@@ -2,20 +2,55 @@ import React, { useState, useEffect, useRef } from 'react';
import { Link, Redirect } from 'react-router-dom'; import { Link, Redirect } from 'react-router-dom';
import Nav1 from '../Components/MainNav'; import Nav1 from '../Components/MainNav';
import Nav2 from '../Components/SubNav'; import Nav2 from '../Components/SubNav';
import { Form, Col, Container, Button, Row } from 'react-bootstrap'; import { Form, Col, Container, Button, Row, Alert } from 'react-bootstrap';
import axios from 'axios'
import catchErrors from '../utils/catchErrors'
import { handleLogin } from '../utils/auth'
function Login(){
const [validated,setValidated]=useState(false); const INIT_USER = {
id: '',
password: ''
}
function Login() {
const handleSubmit=(e)=>{ const [validated, setValidated] = useState(false);
const form =e.currentTarget; const [user, setUser] = useState(INIT_USER)
if(form.checkValidity() === false){ //checkValidity 는 입력 요소에 유효한 데이터가 포함되어 있는지 확인 const [error, setError] = useState('')
e.preventDefault(); const [success, setSuccess] = useState(false)
e.stopPropagation();
async function handleSubmit(event) {
event.preventDefault()
const form = event.currentTarget;
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
} }
setValidated(true); setValidated(true);
try {
setError('')
await axios.post('api/auth/login', user)
handleLogin()
setSuccess(true)
} catch (error) {
catchErrors(error, setError)
}
if (success) {
return <Redirect to='/' />
}
}
function handleChange(event) {
const { name, value } = event.target
setUser({ ...user, [name]: value })
} }
return ( return (
<div> <div>
<Nav1 /> <Nav1 />
...@@ -24,15 +59,22 @@ function Login(){ ...@@ -24,15 +59,22 @@ function Login(){
<Row className="justify-content-center"> <Row className="justify-content-center">
<Col md={5} xs={10} className="border" style={{ background: '#F7F3F3' }}> <Col md={5} xs={10} className="border" style={{ background: '#F7F3F3' }}>
<h3 className="text-center mt-5">Login</h3> <h3 className="text-center mt-5">Login</h3>
<Form noValidate validated={validated} onSubmit={handleSubmit} className="p-5"> {error && <Alert variant='danger'>
{error}
</Alert>}
<Form noValidate validated={validated}
onSubmit={handleSubmit}
className="p-5">
<Form.Group controlId="formBasicId"> <Form.Group controlId="formBasicId">
<Form.Row> <Form.Row>
<Col sm={4} xs={6} as={Form.Label} for="id"> 아이디</Col> <Col sm={4} xs={6} as={Form.Label} for="id"> 아이디</Col>
<Col sm={8} xs={12} as={Form.Control} <Col sm={8} xs={12} as={Form.Control}
required required
type="text" type="text"
id="id" name="id"
placeholder="ID" placeholder="ID"
value={user.id}
onChange={handleChange}
style={{ width: '160px' }}> style={{ width: '160px' }}>
</Col> </Col>
<Form.Control.Feedback className="text-center" type="invalid"> 아이디를 입력하세요.</Form.Control.Feedback> <Form.Control.Feedback className="text-center" type="invalid"> 아이디를 입력하세요.</Form.Control.Feedback>
...@@ -44,8 +86,10 @@ function Login(){ ...@@ -44,8 +86,10 @@ function Login(){
<Col sm={4} xs={6} as={Form.Label} for="password">비밀번호</Col> <Col sm={4} xs={6} as={Form.Label} for="password">비밀번호</Col>
<Col sm={8} xs={12} as={Form.Control} <Col sm={8} xs={12} as={Form.Control}
type="password" type="password"
id="password" name="password"
value={user.password}
placeholder="Password" placeholder="Password"
onChange={handleChange}
style={{ width: '160px' }} style={{ width: '160px' }}
required /> required />
<Form.Control.Feedback className="text-center" type="invalid"> <Form.Control.Feedback className="text-center" type="invalid">
...@@ -63,6 +107,7 @@ function Login(){ ...@@ -63,6 +107,7 @@ function Login(){
</Container> </Container>
</div> </div>
) )
} }
export default Login export default Login
\ No newline at end of file
import React, { useState, useEffect, useRef } from 'react'; import React, { useState } from 'react';
import axios from 'axios' import axios from 'axios'
import Nav1 from '../Components/MainNav'; import Nav1 from '../Components/MainNav';
import Nav2 from '../Components/SubNav'; import Nav2 from '../Components/SubNav';
...@@ -18,12 +18,13 @@ function Signup() { ...@@ -18,12 +18,13 @@ function Signup() {
const [user, setUser] = useState(true) const [user, setUser] = useState(true)
const [error, setError] = useState('') const [error, setError] = useState('')
const [validated, setValidated] = useState(false);
function handleChange(event) { function handleChange(event) {
const { name, value } = event.target const { name, value } = event.target
setUser({ ...user, [name]: value }) setUser({ ...user, [name]: value })
} }
const [validated, setValidated] = useState(false);
async function handleSubmit(event) { async function handleSubmit(event) {
event.preventDefault() event.preventDefault()
...@@ -43,7 +44,25 @@ function Signup() { ...@@ -43,7 +44,25 @@ function Signup() {
} catch (error) { } catch (error) {
catchErrors(error, setError) catchErrors(error, setError)
} }
} }
function checkPassword(event){
const p1=user.password
const p2=user.password2
if(p1 !== p2){
event.preventDefault();
event.stopPropagation();
alert('비밀번호가 일치하지 않습니다.')
return false
}else{
return true
}
}
return ( return (
<div> <div>
...@@ -124,7 +143,8 @@ function Signup() { ...@@ -124,7 +143,8 @@ function Signup() {
style={{ width: '160px' }} style={{ width: '160px' }}
value={user.password} value={user.password}
required required
onChange={handleChange} /> onChange={handleChange}
/>
<Form.Control.Feedback className="text-center" type="invalid"> <Form.Control.Feedback className="text-center" type="invalid">
비밀번호를 입력하세요. 비밀번호를 입력하세요.
</Form.Control.Feedback> </Form.Control.Feedback>
...@@ -140,7 +160,8 @@ function Signup() { ...@@ -140,7 +160,8 @@ function Signup() {
style={{ width: '160px' }} style={{ width: '160px' }}
value={user.password2} value={user.password2}
required required
onChange={handleChange} /> onChange={handleChange}
/>
<Form.Control.Feedback type="invalid"> 비밀번호를 한번 입력하세요. <Form.Control.Feedback type="invalid"> 비밀번호를 한번 입력하세요.
</Form.Control.Feedback> </Form.Control.Feedback>
</Form.Row> </Form.Row>
...@@ -159,7 +180,9 @@ function Signup() { ...@@ -159,7 +180,9 @@ function Signup() {
</Form.Row> </Form.Row>
</Form.Group> </Form.Group>
<Button <Button
style={{ background: '#91877F', borderColor: '#91877F' }} type="submit" block> style={{ background: '#91877F', borderColor: '#91877F' }} type="submit" block
onClick={checkPassword}
>
Sign Up Sign Up
</Button> </Button>
</Form> </Form>
......
import axios from "axios"
export function handleLogin(){
localStorage.setItem('loginStatus','true')
}
export async function handleLogout(){
localStorage.removeItem('loginStatus')
await axios.get('/api/auth/logout')
}
\ No newline at end of file
...@@ -6,6 +6,7 @@ import productRouter from './routes/product.routes.js'; ...@@ -6,6 +6,7 @@ import productRouter from './routes/product.routes.js';
import path from 'path' import path from 'path'
import kakaopayRoutes from './routes/kakaopay.routes.js' import kakaopayRoutes from './routes/kakaopay.routes.js'
import config from './config.js' import config from './config.js'
import authRouter from './routes/auth.routes.js'
import cors from 'cors' import cors from 'cors'
connectDb() connectDb()
...@@ -22,6 +23,7 @@ app.use(express.static(path.join(process.cwd(), 'dist'))) ...@@ -22,6 +23,7 @@ app.use(express.static(path.join(process.cwd(), 'dist')))
// app.use('/', indexRouter); // app.use('/', indexRouter);
app.use('/', kakaopayRoutes) app.use('/', kakaopayRoutes)
app.use('/api/users',userRouter) app.use('/api/users',userRouter)
app.use('/api/auth/login',authRouter)
app.use('/api/products', productRouter) app.use('/api/products', productRouter)
app.listen(config.port, () => { app.listen(config.port, () => {
......
...@@ -3,7 +3,8 @@ const config = { ...@@ -3,7 +3,8 @@ const config = {
port: process.env.PORT || 3001, port: process.env.PORT || 3001,
jwtSecret: process.env.JWT_SECRET || 'My_Secret_Key', jwtSecret: process.env.JWT_SECRET || 'My_Secret_Key',
mongoDbUri: process.env.MONGEDB_URI || 'mongodb://localhost/shopping-mall', mongoDbUri: process.env.MONGEDB_URI || 'mongodb://localhost/shopping-mall',
kakaoAdminKey: 'b2dda7685c5b2990684d813e362cff07' kakaoAdminKey: 'b2dda7685c5b2990684d813e362cff07',
cookieMaxAge: 60 * 60 * 24 * 7 * 1000
} }
// const config = { // const config = {
......
import User from '../schemas/User.js'
import bcrypt from 'bcryptjs'
import jwt from 'jsonwebtoken'
import config from '../config.js'
const login = async(req,res)=>{
const {id, password} =req.body
console.log(id,password)
try{
const user=await User.findOne({id}).select('+password')
if(!user){
return res.Status(404).send(`${id}가 존재하지 않습니다.`)
}
const passwordMatch= await bcrypt.compare(password, user.password)
if(passwordMatch){
const token=jwt.sign({userId:user._id},config.jwtSecret,{
expiresIn:'3d'
})
res.cookie('token',token,{
maxAge:config.cookieMaxAge,
httpOnly:true,
secure:config.env ==='production'
})
res.send('로그인 되었습니다.')
}else{
res.Status(401).send('비밀번호가 일치하지 않습니다.')
}
}catch(error){
console.log(error)
res.Status(500).send('로그인 실패. 다시 시도하세요.')
}
}
export default {login}
\ No newline at end of file
import User from "../models/User.js"; import User from "../schemas/User.js";
import isLength from 'validator/lib/isLength.js' import isLength from 'validator/lib/isLength.js'
import bcrypt from 'bcryptjs'
const signup = async (req, res) => { const signup = async (req, res) => {
console.log(req.body) console.log(req.body)
console.log('req.body.name=', req.body.name) const { name, number1, number2, id, password, tel } = req.body
const { name, number1, number2, id, password, password2, tel } = req.body
try { try {
if(!isLength(password,{min:8, max:15})){ if(!isLength(password,{min:8, max:15})){
return res.status(422).send('비밀번호는 8-15자리로 입력해주세요.') return res.status(422).send('비밀번호는 8-15자리로 입력해주세요.')
...@@ -14,6 +14,7 @@ const signup = async (req, res) => { ...@@ -14,6 +14,7 @@ const signup = async (req, res) => {
return res.status(422).send(`${id}가 이미 사용중입니다.`) return res.status(422).send(`${id}가 이미 사용중입니다.`)
} }
const hash=await bcrypt.hash(password,10) const hash=await bcrypt.hash(password,10)
const newUser = await new User ({ const newUser = await new User ({
...@@ -22,8 +23,7 @@ const signup = async (req, res) => { ...@@ -22,8 +23,7 @@ const signup = async (req, res) => {
number2, number2,
id, id,
password:hash, password:hash,
password2:hash, tel,
tel
}).save() }).save()
console.log(newUser) console.log(newUser)
res.json(newUser) res.json(newUser)
...@@ -35,4 +35,4 @@ const signup = async (req, res) => { ...@@ -35,4 +35,4 @@ const signup = async (req, res) => {
} }
export default signup export default { signup }
\ No newline at end of file \ No newline at end of file
import mongoose from "mongoose";
const { String } = mongoose.Schema.Types
const UserSchema = new mongoose.Schema({
name: {
type: String,
required: true, // 꼭 필요한 값
},
id: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true,
},
number1:{
type:String,
required:true,
unique:true
},
number2:{
type:String,
required:true,
unique:true
},
tel:{
type:String,
required:true,
unique:true
},
role: {
type: String,
required: true,
default: 'user',
enum: ['user', 'admin', 'root']
}
}, {
timestamps: true
})
export default mongoose.models.User || mongoose.model('User', UserSchema)
\ No newline at end of file
...@@ -12,12 +12,14 @@ ...@@ -12,12 +12,14 @@
"author": "", "author": "",
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
"bcryptjs": "^2.4.3",
"cors": "^2.8.5", "cors": "^2.8.5",
"express": "^4.17.1", "express": "^4.17.1",
"jsonwebtoken": "^8.5.1",
"mongoose": "^5.11.9", "mongoose": "^5.11.9",
"multer": "^1.4.2",
"node-fetch": "^2.6.1", "node-fetch": "^2.6.1",
"nodemon": "^2.0.6", "nodemon": "^2.0.6",
"validator": "^13.5.2", "validator": "^13.5.2"
"multer": "^1.4.2"
} }
} }
import express from "express";
import authCtrl from '../controllers/auth.controller.js';
const router = express.Router()
router.route('/api/auth/login')
.post(authCtrl.login)
export default router
\ No newline at end of file
import mongoose from 'mongoose' import mongoose from 'mongoose'
const { String, Number, Array } = mongoose.Schema.Types const { String} = mongoose.Schema.Types
const ProductSchema = new mongoose.Schema({ const ProductSchema = new mongoose.Schema({
pro_name: { pro_name: {
......
import mongoose from 'mongoose' import mongoose from "mongoose";
const { String } = mongoose.Schema.Types const { String } = mongoose.Schema.Types
...@@ -10,35 +10,30 @@ const UserSchema = new mongoose.Schema({ ...@@ -10,35 +10,30 @@ const UserSchema = new mongoose.Schema({
id: { id: {
type: String, type: String,
required: true, required: true,
unique: true unique: true,
}, },
password: { password: {
type: String, type: String,
required: true, required: true,
select: false
}, },
confirm_password:{
type: String, number1: {
required: true,
select: false
},
phoneNumber: {
type: String, type: String,
required: true, required: true,
}, },
role: { number2: {
type: String, type: String,
required: true, required: true,
default: 'user',
enum: ['user', 'admin', 'root']
}, },
birth: { tel: {
type: String, type: String,
required: true, required: true,
}, },
sex: { role: {
type: String, type: String,
required: true, required: true,
default: 'user',
enum: ['user', 'admin', 'root']
} }
}, { }, {
timestamps: true timestamps: true
......
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