• 카테고리

    질문 & 답변
  • 세부 분야

    풀스택

  • 해결 여부

    미해결

로그인 질문(로그인하지 않은 사용자만 접근이 가능합니다)

21.12.14 19:15 작성 조회수 173

0

 

위와 같이 로그인을 하지 않은 상태입니다. 그런데 로그인을 하면 저렇게 401 에러가 뜹니다. 뭐가 잘못됬는지 감이안와서 헤매고 있는데 조언좀 주세요 ㅠ

401 에러 이외엔 에러 메세지가 따로 없습니다.

```javascript

// routes/middlewares.js

 exports.isLoggedIn = (req, res, next) => {

if (req.isAuthenticated()) {
next(); // 비어있으면 다음 미들웨어로 간다
} else {
res.status(401).send('로그인이 필요합니다.');
}
};

exports.isNotLoggedIn = (req, res, next) => {
if (!req.isAuthenticated()) {
next(); // 비어있으면 다음 미들웨어로 간다
} else {
res.status(401).send('로그인하지 않은 사용자만 접근이 가능합니다.');
}
};

```

```javascript

routes/user.js

router.post('/login', isNotLoggedIn, (req, res, next) => {
passport.authenticate('local', (err, user, info) => {
if (err) {
console.error(err);
next(err);
}
if (info) {
return res.status(401).send(info.reason); // client로 응답을 보내줌, 401: 허가되지 않음, 403: 금지
}
return req.login(user, async (loginErr) => {
if (loginErr) {
console.error(loginErr);
return next(loginErr);
}
const fullUserWithoutPassword = await User.findOne({
where: { id: user.id },
attributes: {
exclude: ['password'], // 원하는 정보만 가져오거나 가져오지 않겠다 / 현재: pw 빼고 다 가져오겠다
},
include: [
{
model: Post,
},
{
model: User,
as: 'Followers',
},
{
model: User,
as: 'Followings',
},
], // 가져올 정보중 뺄 것들
});
return res.status(200).json(fullUserWithoutPassword);
});
})(req, res, next);
}); // 로그인 전략 실행

```

```javascript

// front/components/AppLayout.js

<LoggedFixed>{me ? <UserProfile /> : <LoginForm />}</LoggedFixed>

```

 

답변 1

답변을 작성해보세요.

1

쿠키가 있는걸로 봐서는 이미 로그인된 상태인데 프론트에서 자신이 로그인되었다는걸 인식 못하고 있는 것 같습니다. getServerSideProps쪽 문제 같습니다.

감사합니다