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';
import { Link, Redirect } from 'react-router-dom';
import Nav1 from '../Components/MainNav';
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 form =e.currentTarget;
if(form.checkValidity() === false){ //checkValidity 는 입력 요소에 유효한 데이터가 포함되어 있는지 확인
e.preventDefault();
e.stopPropagation();
const [validated, setValidated] = useState(false);
const [user, setUser] = useState(INIT_USER)
const [error, setError] = useState('')
const [success, setSuccess] = useState(false)
async function handleSubmit(event) {
event.preventDefault()
const form = event.currentTarget;
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
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 (
<div>
<Nav1 />
......@@ -24,15 +59,22 @@ function Login(){
<Row className="justify-content-center">
<Col md={5} xs={10} className="border" style={{ background: '#F7F3F3' }}>
<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.Row>
<Col sm={4} xs={6} as={Form.Label} for="id"> 아이디</Col>
<Col sm={8} xs={12} as={Form.Control}
required
type="text"
id="id"
name="id"
placeholder="ID"
value={user.id}
onChange={handleChange}
style={{ width: '160px' }}>
</Col>
<Form.Control.Feedback className="text-center" type="invalid"> 아이디를 입력하세요.</Form.Control.Feedback>
......@@ -44,8 +86,10 @@ function Login(){
<Col sm={4} xs={6} as={Form.Label} for="password">비밀번호</Col>
<Col sm={8} xs={12} as={Form.Control}
type="password"
id="password"
name="password"
value={user.password}
placeholder="Password"
onChange={handleChange}
style={{ width: '160px' }}
required />
<Form.Control.Feedback className="text-center" type="invalid">
......@@ -63,6 +107,7 @@ function Login(){
</Container>
</div>
)
}
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 Nav1 from '../Components/MainNav';
import Nav2 from '../Components/SubNav';
......@@ -18,12 +18,13 @@ function Signup() {
const [user, setUser] = useState(true)
const [error, setError] = useState('')
const [validated, setValidated] = useState(false);
function handleChange(event) {
const { name, value } = event.target
setUser({ ...user, [name]: value })
}
const [validated, setValidated] = useState(false);
async function handleSubmit(event) {
event.preventDefault()
......@@ -43,7 +44,25 @@ function Signup() {
} catch (error) {
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 (
<div>
......@@ -124,7 +143,8 @@ function Signup() {
style={{ width: '160px' }}
value={user.password}
required
onChange={handleChange} />
onChange={handleChange}
/>
<Form.Control.Feedback className="text-center" type="invalid">
비밀번호를 입력하세요.
</Form.Control.Feedback>
......@@ -140,7 +160,8 @@ function Signup() {
style={{ width: '160px' }}
value={user.password2}
required
onChange={handleChange} />
onChange={handleChange}
/>
<Form.Control.Feedback type="invalid"> 비밀번호를 한번 입력하세요.
</Form.Control.Feedback>
</Form.Row>
......@@ -159,7 +180,9 @@ function Signup() {
</Form.Row>
</Form.Group>
<Button
style={{ background: '#91877F', borderColor: '#91877F' }} type="submit" block>
style={{ background: '#91877F', borderColor: '#91877F' }} type="submit" block
onClick={checkPassword}
>
Sign Up
</Button>
</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';
import path from 'path'
import kakaopayRoutes from './routes/kakaopay.routes.js'
import config from './config.js'
import authRouter from './routes/auth.routes.js'
import cors from 'cors'
connectDb()
......@@ -22,6 +23,7 @@ app.use(express.static(path.join(process.cwd(), 'dist')))
// app.use('/', indexRouter);
app.use('/', kakaopayRoutes)
app.use('/api/users',userRouter)
app.use('/api/auth/login',authRouter)
app.use('/api/products', productRouter)
app.listen(config.port, () => {
......
......@@ -3,7 +3,8 @@ const config = {
port: process.env.PORT || 3001,
jwtSecret: process.env.JWT_SECRET || 'My_Secret_Key',
mongoDbUri: process.env.MONGEDB_URI || 'mongodb://localhost/shopping-mall',
kakaoAdminKey: 'b2dda7685c5b2990684d813e362cff07'
kakaoAdminKey: 'b2dda7685c5b2990684d813e362cff07',
cookieMaxAge: 60 * 60 * 24 * 7 * 1000
}
// 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 bcrypt from 'bcryptjs'
const signup = async (req, res) => {
console.log(req.body)
console.log('req.body.name=', req.body.name)
const { name, number1, number2, id, password, password2, tel } = req.body
const { name, number1, number2, id, password, tel } = req.body
try {
if(!isLength(password,{min:8, max:15})){
return res.status(422).send('비밀번호는 8-15자리로 입력해주세요.')
......@@ -14,6 +14,7 @@ const signup = async (req, res) => {
return res.status(422).send(`${id}가 이미 사용중입니다.`)
}
const hash=await bcrypt.hash(password,10)
const newUser = await new User ({
......@@ -22,8 +23,7 @@ const signup = async (req, res) => {
number2,
id,
password:hash,
password2:hash,
tel
tel,
}).save()
console.log(newUser)
res.json(newUser)
......@@ -35,4 +35,4 @@ const signup = async (req, res) => {
}
export default signup
\ No newline at end of file
export default { signup }
\ 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 @@
"author": "",
"license": "ISC",
"dependencies": {
"bcryptjs": "^2.4.3",
"cors": "^2.8.5",
"express": "^4.17.1",
"jsonwebtoken": "^8.5.1",
"mongoose": "^5.11.9",
"multer": "^1.4.2",
"node-fetch": "^2.6.1",
"nodemon": "^2.0.6",
"validator": "^13.5.2",
"multer": "^1.4.2"
"validator": "^13.5.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'
const { String, Number, Array } = mongoose.Schema.Types
const { String} = mongoose.Schema.Types
const ProductSchema = new mongoose.Schema({
pro_name: {
......
import mongoose from 'mongoose'
import mongoose from "mongoose";
const { String } = mongoose.Schema.Types
......@@ -10,35 +10,30 @@ const UserSchema = new mongoose.Schema({
id: {
type: String,
required: true,
unique: true
unique: true,
},
password: {
type: String,
required: true,
select: false
},
confirm_password:{
type: String,
required: true,
select: false
},
phoneNumber: {
number1: {
type: String,
required: true,
},
role: {
number2: {
type: String,
required: true,
default: 'user',
enum: ['user', 'admin', 'root']
},
birth: {
tel: {
type: String,
required: true,
},
sex: {
role: {
type: String,
required: true,
default: 'user',
enum: ['user', 'admin', 'root']
}
}, {
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