Commit d8de2d3f authored by 이재연's avatar 이재연
Browse files

No commit message

No commit message
parent ccc8f484
import React from 'react';
import { Navbar, Nav } from 'react-bootstrap';
import { handleLogout, isAuthenticated } from '../utils/auth';
import { handleLogout, isAuthenticated, isAuthenticatedAdmin } from '../utils/auth';
function MainNav() {
const user = isAuthenticated()
const admin = isAuthenticatedAdmin()
return (
<Navbar sticky="top" style={{ background: "#CDC5C2" }}>
......@@ -13,7 +14,7 @@ function MainNav() {
{' '}KU#
</Navbar.Brand>
<Nav>
{user ? <> <Nav.Link className="text-light" onClick={() => handleLogout()}>Logout</Nav.Link>
{user,admin ? <> <Nav.Link className="text-light" onClick={() => handleLogout()}>Logout</Nav.Link>
<Nav.Link className="text-light" href="/account"> Mypage </Nav.Link>
</>
: (
......@@ -25,9 +26,13 @@ function MainNav() {
<Nav.Link href="/shoppingcart">
<img alt="카트" src="/icon/cart.svg" width="30" height="30" />
</Nav.Link>
<Nav.Link href="/admin">
{admin ? <Nav.Link href="/admin">
<img alt="관리자" src="/icon/option.svg" width="30" height="30" />
</Nav.Link>
</Nav.Link> :(
<>
</>
)}
</Nav>
</Navbar>
)
......
......@@ -97,7 +97,7 @@ function Account() {
<Col md={5} className="d-flex align-content-center justify-content-center">
<Button variant="outline-light" onClick={handleShow}>
{account.avatarUrl ? (
<Image src={account.avatarUrl && `/image/${account.avatarUrl}`} className="img-thumbnail"
<Image src={account.avatarUrl && `/images/${account.avatarUrl}`} className="img-thumbnail"
roundedCircle style={{ objectFit: "cover", width: "10rem", height: "10rem" }} />
) : (
<Image src="/icon/person.svg" className="img-thumbnail"
......
......@@ -3,7 +3,7 @@ import { Link, Redirect } from 'react-router-dom';
import { Form, Col, Container, Button, Row, Alert } from 'react-bootstrap';
import axios from 'axios'
import catchErrors from '../utils/catchErrors'
import { handleLogin } from '../utils/auth'
import { handleLogin, handleLoginAdmin } from '../utils/auth'
const INIT_USER = {
......@@ -11,16 +11,23 @@ const INIT_USER = {
password: ''
}
const INIT_ADMIN = {
id: '',
password: ''
}
function Login() {
const [validated, setValidated] = useState(false);
const [user, setUser] = useState(INIT_USER)
const [error, setError] = useState('')
const [success, setSuccess] = useState(false)
const [admin, setAdmin] = useState(INIT_ADMIN)
function handleChange(event) {
const { name, value } = event.target
setUser({ ...user, [name]: value })
setAdmin({ ...admin, [name]: value })
}
......@@ -34,9 +41,13 @@ function Login() {
setValidated(true);
try {
setError('')
const response=await axios.post('/api/auth/login', user)
if (user) {
const response = await axios.post('/api/auth/login', user)
handleLogin(response.data)
setSuccess(true)
}else{
return false
}
} catch (error) {
catchErrors(error, setError)
}
......@@ -44,7 +55,7 @@ function Login() {
if (success) {
alert('로그인 되었습니다.')
window.location.href='/'
window.location.href = '/'
}
......
......@@ -114,7 +114,7 @@ function Product({ match, location }) {
</style>
<Row className="justify-content-center mt-5 mx-0">
<Col sm={11} md={4}>
<img src={product.main_img} style={{ objectFit: "contain", width: "100%" }} />
<img src={`/images/${product.main_img}`} style={{ objectFit: "contain", width: "100%" }} />
</Col>
<Col sm={11} md={4} className="align-middle mt-4">
<h3 className="mb-4">{product.name}</h3>
......
......@@ -12,13 +12,15 @@ function ProductsList({ match }) {
const [mainCategory, setMainCategory] = useState(match.params.main.toUpperCase())
const [subcategory, setSubcategory] = useState([])
const [productlist, setProductlist] = useState([])
const [bestlist, setBestlist] = useState([])
const [newlist, setNewlist] = useState([])
const [sub, setSub] = useState([])
const [error, setError] = useState('')
// const user=isAuthenticated()
useEffect(() => {
getSubsCategories()
// getSubsCategories()
getProductlist()
}, [mainCategory])
......@@ -44,15 +46,15 @@ function ProductsList({ match }) {
// e.preventDefault()
// }
async function getSubsCategories() {
try {
const response = await axios.get(`/api/categories/sub/${mainCategory}`)
console.log("sub", response.data)
setSubcategory(response.data)
} catch (error) {
catchError(error, setError)
}
}
// async function getSubsCategories() {
// try {
// const response = await axios.get(`/api/categories/sub/${mainCategory}`)
// console.log("sub", response.data)
// setSubcategory(response.data)
// } catch (error) {
// catchError(error, setError)
// }
// }
async function getProductlist() {
try {
......@@ -79,6 +81,7 @@ function ProductsList({ match }) {
}
}
return (
<div>
{console.log("main=",mainCategory)}
......@@ -114,8 +117,8 @@ function ProductsList({ match }) {
<Dropdown>
<Dropdown.Toggle className="mx-2">정렬</Dropdown.Toggle>
<Dropdown.Menu>
<Dropdown.Item>인기상품</Dropdown.Item>
<Dropdown.Item>신상품</Dropdown.Item>
<Dropdown.Item >인기상품</Dropdown.Item>
<Dropdown.Item >신상품</Dropdown.Item>
<Dropdown.Item>낮은가격</Dropdown.Item>
<Dropdown.Item>높은가격</Dropdown.Item>
</Dropdown.Menu>
......
import axios from "axios"
export function handleLogin({userId,role,name}){
export function handleLogin({userId,adminId,role,name}){
localStorage.setItem('id',userId)
localStorage.setItem('role',role)
localStorage.setItem('name',name)
localStorage.setItem('adminId',adminId)
}
export async function handleLogout(){
localStorage.removeItem('id')
localStorage.removeItem('role')
localStorage.removeItem('name')
localStorage.removeItem('adminId')
localStorage.removeItem('adminrole')
localStorage.removeItem('adminname')
await axios.get('/api/auth/logout')
window.location.href = '/'
}
export function isAuthenticatedAdmin(){
const adminId= localStorage.getItem('adminId')
if(adminId){
return adminId
} else {
return false
}
}
export function isAuthenticated(){
const userId= localStorage.getItem('id')
if(userId){
......
......@@ -5,15 +5,16 @@ import config from '../config.js'
const login = async (req, res) => {
const { id, password } = req.body
console.log(id, password)
console.log(req.body)
try {
const user = await User.findOne({ id }).select('password role name')
const user = await User.findOne({role:"user",id:id}).select('password name')
console.log('u=', user)
if (!user) {
return res.status(404).send(`${id}가 존재하지 않습니다.`)
return res.status(404).send(`${user.id}가 존재하지 않습니다.`)
}
const passwordMatch = await bcrypt.compare(password, user.password)
if (passwordMatch) {
const token = jwt.sign({ userId: user._id }, config.jwtSecret, {
expiresIn: '3d'
......@@ -34,9 +35,47 @@ const login = async (req, res) => {
}
}
const admin = (req, res) => {
try {
res.json(admin)
} catch (error) {
res.status(500).send('다시 시도하세요.')
}
}
const adminId = async (req, res, next, admin) => {
try {
const admin = await User.findOne({ role: "admin" }).select('id password role name')
console.log('a=',admin)
if (!admin) {
res.status(404).send(`${id}가 존재하지 않습니다.`)
}
const adminpasswordMatch = await bcrypt.compare(password, admin.password)
if (adminpasswordMatch) {
const token = jwt.sign({ adminId: admin.id }, config.jwtSecret, {
expiresIn: '3d'
})
res.cookie('token', token, {
maxAge: config.cookieMaxAge,
httpOnly: true,
secure: config.env === 'production'
})
res.json({ adminId: admin.id, role: admin.role, name: admin.name })
}else {
res.status(401).send('비밀번호가 일치하지 않습니다.')
}
req.admin = admin
next()
} catch (error) {
res.status(500).send('로그인 실패. 다시 시도하세요.')
}
}
const logout = (req, res) => {
res.clearCookie('token')
res.send('로그아웃 되었습니다.')
}
export default { login, logout }
\ No newline at end of file
export default { login, logout, admin, adminId }
\ No newline at end of file
......@@ -11,16 +11,15 @@ const getCategory = async (req, res) => {
}
}
const getSubCategory=(req,res)=>{
// const getSubCategory=(req,res)=>{
}
// }
const getsubId=(req,res,next,sub)=>{
const subcategory = await category.find({"Dress"})
console.log('sub=',sub)
// const getsubId=(req,res,next,sub)=>{
// console.log('sub=',sub)
next()
}
// next()
// }
export default { getCategory , getsubId, getSubCategory}
\ No newline at end of file
export default { getCategory }
\ No newline at end of file
......@@ -6,10 +6,10 @@ const upload = multer({ dest: 'uploads/' })
const imageUpload = upload.fields([
{ name: 'main_image' },
{ name: 'detail_image' }
])
])
const regist = async (req, res) => {
console.log("req.body=",req.body)
console.log("req.body=", req.body)
try {
const { pro_name, price, stock, main_category, sub_category, description, colors, sizes } = req.body
const main_img = req.files['main_image'][0]
......@@ -33,15 +33,28 @@ const getToHome = async (res, req) => {
try {
const bestProduct = await Product.find({}).sort({ purchase: 1 }).limit(6)
const newProduct = await Product.find({}).sort({ createdAt: -1 }).limit(6)
console.log("best=",bestProduct)
console.log("new=",newProduct)
console.log("best=", bestProduct)
console.log("new=", newProduct)
res.json(bestProduct, newProduct)
} catch {
res.status(500).send('상품을 불러오지 못했습니다.')
}
}
const getlist=(req,res)=>{
const Sortlist = async (res, req) => {
try {
const newlist = await Product.find({}).sort({ createdAt: -1 })
const bestlist = await Product.find({}).sort({ purchase: 1 })
console.log('bestsort',bestlist)
console.log('newlist',newlist)
res.json(newlist, bestlist)
} catch {
res.status(500).send('상품을 불러오지 못했습니다.')
}
}
const getlist = (req, res) => {
try {
res.json(req.productslist)
} catch (error) {
......@@ -52,7 +65,7 @@ const getlist=(req,res)=>{
const categoryId = async (req, res, next, category) => {
try {
const productslist = await Product.find({main_category: category})
const productslist = await Product.find({ main_category: category })
if (!productslist) {
res.status(404).send('상품을 찾을 수 없습니다.')
}
......@@ -63,16 +76,16 @@ const categoryId = async (req, res, next, category) => {
}
}
const subgetlist=(req,res)=>{
try{
const subgetlist = (req, res) => {
try {
res.json(req.subproductslist)
}catch(error){
} catch (error) {
res.status(500).send('상품을 불러오지 못했습니다.')
}
}
const subcategoryId = async (req, res, next, subcategory) => {
try {
const subproductslist = await Product.find({sub_category:subcategory})
const subproductslist = await Product.find({ sub_category: subcategory })
if (!subproductslist) {
res.status(404).send('상품을 찾을 수 없습니다.')
}
......@@ -83,4 +96,4 @@ const subcategoryId = async (req, res, next, subcategory) => {
}
}
export default { imageUpload, regist, categoryId, getlist, subcategoryId, subgetlist }
export default { imageUpload, regist, categoryId, getlist, subcategoryId, subgetlist, getToHome , Sortlist}
......@@ -9,4 +9,9 @@ router.route('/login')
router.route('/logout')
.get(authCtrl.logout)
router.route('/admin/:admin')
.post(authCtrl.admin)
router.param('admin',authCtrl.adminId)
export default router
\ No newline at end of file
......@@ -6,9 +6,9 @@ const router = express.Router()
router.route('/main')
.get(categoryCtrl.getCategory)
router.route('/sub/:sub')
.get(categoryCtrl.getSubCategory)
// router.route('/sub/:sub')
// .get(categoryCtrl.getSubCategory)
router.param('sub',categoryCtrl.getsubId)
// router.param('sub',categoryCtrl.getsubId)
export default router
\ No newline at end of file
......@@ -4,6 +4,9 @@ import productCtrl from '../controllers/product.controller.js';
const router = express.Router()
router.route('/sort')
.get(productCtrl.Sortlist)
router.route('/regist')
.post(productCtrl.imageUpload, productCtrl.regist)
......
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