-
카테고리
-
세부 분야
풀스택
-
해결 여부
미해결
로그인 401 Error (routes에서 user false, 'Missing credentials')
24.01.06 16:17 작성 24.01.06 16:22 수정 조회수 161
0
안녕하세요 선생님
상황)
쿠키/세션 전체 로그인 흐름 강좌를 따라해보았는데 로그인을 했을 때 401 에러가 발생하는 상황입니다.
시도해본 것)
아래 파일들의 로그인과 관련된 코드에 로그를 찍어보았고 이런 결과가 출력 되었습니다.
1)LoginForm => onSubmitForm함수에서 email,password찍으면 이메일,비밀번호 출력됨
2)reducers/user => loginRequestAction함수에서 data찍으면 이메일만 출력되고 loginAction함수에서는 출력안됨
3)sagas/user => logIn함수에서 action.data에 이메일만 출력되고 result는 출력안됨
4)user/routes => err는 null, user는 false, info는 { message: 'Missing credentials' }라고 출력됨
5)passport/index, passport/local => 출력안됨
질문1) reducer와 sagas에서는 원래 비밀번호가 출력이 안되는게 맞나요?
질문2) 만약에 reducer와 sagas에서 원래 비밀번호가 안나오는게 맞다면 어떤 부분에 문제가 있어서 reducer와 saga에서 data 나오는데, routes에서는 users가 false로 나오고 Missing credentials가 나오는건가요?
질문3)이 문제를 어떻게 해결하면 좋을까요,,?
작성한 코드) 글자수 제한이 있어 로그인 부분만 올립니닷,,!
LoginForm
import React, { useCallback, useEffect } from 'react';
import {Form, Input, Button} from 'antd';
import Link from 'next/link';
import styled from 'styled-components';
import {useDispatch, useSelector} from 'react-redux';
import useInput from '../hooks/useInput';
import {loginRequestAction} from '../reducers/user';
const LoginForm = () => {
const dispatch = useDispatch();
const {logInLoading, logInError} = useSelector((state) => state.user);
const [email, onChangeEmail] = useInput('');
const [password, onChangePassword] = useInput('');
useEffect(() => {
if (logInError) {
alert(logInError);
}
}, [logInError]);
const onSubmitForm = useCallback(() => {
console.log('LoginForm에서 email, password', email, password); //email, password luckyhaejin1@naver.com 1234
dispatch(loginRequestAction(email, password));
},[email, password]);
return (
<FormWrapper onFinish={onSubmitForm}> {/* 생략 */}
<Button type="primary" htmlType="submit" loading={logInLoading}>로그인</Button>
</FormWrapper>
);
}
reducers/user
import {produce} from 'immer';
export const initialState = {
logInLoading: false, //login시도중
logInDone: false,
logInError: null,
//생략
loginData:{}
}
export const LOG_IN_REQUEST = 'LOG_IN_REQUEST';
export const LOG_IN_SUCCESS = 'LOG_IN_SUCCESS';
export const LOG_IN_FAILURE = 'LOG_IN_FAILURE';
export const loginAction = (data) => {
console.log('reducers loginAction에서 data', data);//로그x
return (dispatch) => {
setTimeout(() => {
dispatch(loginRequestAction());
}, 2000);
dispatch(loginRequestAction());
}
}
export const loginRequestAction = (data) => {
console.log('reducers loginRequestAction에서 data', data); //luckyhaejin1@naver.com
return {
type: LOG_IN_REQUEST,
data
}
}
const reducer = (state = initialState, action) => produce(state, (draft) => {
switch(action.type){
case LOG_IN_REQUEST:
draft.logInLoading = true;
draft.logInError = null;
draft.logInDone = false;
break;
case LOG_IN_SUCCESS:
draft.logInLoading = false;
draft.logInDone = true;
draft.me = action.data;
break;
case LOG_IN_FAILURE:
draft.logInLoading = false;
draft.logInError = action.error;
break;
//생략
}
});
export default reducer;
sagas/user
import axios from 'axios';
import { all, call, delay, fork, put, takeLatest } from 'redux-saga/effects';
import {
LOG_IN_FAILURE,
LOG_IN_REQUEST, LOG_IN_SUCCESS,
} from '../reducers/user';
function logInAPI(data){
return axios.post('/user/login', data);
}
function* logIn(action) {
try {
console.log('sagas에서 action.data', action.data);//luckyhaejin1@naver.com
const result = yield call(logInAPI, action.data);
console.log('sagas에서 logIn함수에서 result', result);//로그x
yield put({
type: LOG_IN_SUCCESS,
data: result.data,
});
} catch(err) {
console.error(err);
yield put({
type: LOG_IN_FAILURE,
data: err.response.data,
});
}
}
function* watchLogIn() {
yield takeLatest(LOG_IN_REQUEST, logIn);
}
export default function* userSaga() {
yield all ([
fork(watchLogIn)
])
}
routes/user
const express = require('express');
const bcrypt = require('bcrypt');
const {User} = require('../models');
const router = express.Router();
const passport = require('passport');
router.post('/login',(req, res, next)=> {
console.log('routes 진입');
passport.authenticate('local',(err, user, info) => {
if(err) {
console.error(err);
return next(err);
}
if(info) {
console.log('routes err', err);//null
console.log('routes user', user);//false
console.log('routes info', info);//{ message: 'Missing credentials' }
return res.status(401).send(info.reason);
}
return req.login(user,async(loginErr)=> {
if(loginErr) {
console.log('routes loginErr', loginErr);
console.error(loginErr);
return next(loginErr);
}
return res.status(200).json(user);
});
})(req, res, next);
}); //POST /user/login
module.exports = router;
passport/index
const passport = require('passport');
const local = require('./local');
const { User } = require('../models');
module.exports = () => {
passport.serializeUser((user,done) => {
console.log('serializeUser의 user.id', user.id);//로그x
done(null,user.id);//첫번째 인자 에러, 두번째 인자 성공(쿠키와 묶어줄 user아이디만 저장)
});
passport.deserializeUser(async(id, done) => {
try {
const user = await User.findOne({where:{id}})
console.log('deserializeUser의 user', user);//로그x
done(null,user);
} catch(error) {
console.error(error);
done(error);
}
});
local();
};
passport/local
const passport = require('passport');
const {Strategy:LocalStrategy} = require('passport-local');
const bcrypt = require('bcrypt');
const {User} = require('../models');
const express = require('express');
const router = express.Router();
router.post('/login', passport.authenticate('local'));
module.exports = () => {
passport.use(new LocalStrategy({
usernameField: 'email',
passwordField: 'password',
}, async(email, password, done) => {
console.log('Passport LocalStrategy - Start');//로그x
try {
const user = await User.findOne({
where:{email}
});
if(!user) {
console.log('Passport LocalStrategy - User not found');//로그x
return done(null, false, {reasone: '존재하지 않는 이메일입니다!'})
}
const result = await bcrypt.compare(password, user.password);
if(result) {
console.log('Passport LocalStrategy - Login success');//로그x
return done(null, user);//성공에 사용자 정보 넘겨줌
}
console.log('Passport LocalStrategy - Incorrect password');//로그x
return done(null, false, {reason:'비밀번호가 틀렸습니다.'});
} catch(error) {
console.error('Passport LocalStrategy - Error:', error);//로그x
return done(error);
}
}));
}
사용중인 OS) macOS Apple M1 Pro
설치된 버전) back/Package.json
"dependencies": {
"passport": "^0.7.0",
"passport-local": "^1.0.0",
"sequelize": "^6.35.2",
"sequelize-cli": "^6.6.2"
},
답변을 작성해보세요.
답변 2