so I am writing an app and for a couple of days I struggle to proplerly authenticate and authorize user.
My express config:
const cookieLifetime = 1000 * 200;
app.use(
cors({
origin: "http://localhost:3000",
methods: ["GET,PUT,POST,DELETE,PATCH,OPTIONS"],
credentials: true,
allowedHeaders: `Content-Type, Authorization, X-Requested-With`,
})
);
app.use(
session({
name: `cookie`,
resave: false,
saveUninitialized: false,
store: store,
secret: `secretttttttt`,
cookie: {
secure: false,
maxAge: cookieLifetime,
httpOnly: false,
sameSite: false,
},
})
);
Login route
router.post(`/login`, async (req, res) => {
try {
const user = await User.findByCredentials(req.body.email, req.body.password);
if (!user) {
req.session.error = `Niepoprawny adres email lub hasło`;
res.status(404).send(req.session.error);
}
req.session.user = user;
res.status(200).send(req.session);
} catch (e) {
res.status(404).send();
}
});
As far everything is working correctly. I would like to add a couple of protected routes, so I am using auth
middleware in route, which looks
const isAuth = (req, res, next) => {
console.log(req.cookies);
if (req.cookies.cookie) {
next();
} else {
req.session.error = "Musisz być zalogowany, aby wykonać tą operacje";
res.status(400).send(req);
}
};
module.exports = isAuth;
In my front I would like to login user and then check if user is logged in to access routes, I think my idea of routing is decent but here is how it looks
const Login = () => {
const dispatch = useDispatch();
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [loading, setLoading] = useState(null);
const navigate = useNavigate();
const user = useSelector((state) => state);
const fetchData = () => {
dispatch(loginUser({ email, password }));
setLoading(true);
};
const handleFormSubmit = (e) => {
e.preventDefault();
fetchData();
};
useEffect(() => {
if (user.user !== null && loading === true) {
setLoading(false);
if(user.user.userRole === "reviewer"){
navigate("/reviewerView", { replace: true });
} else {
navigate("/appView", { replace: true });
}
}
}, [user]);
Now finally my final route, which I would like to check if user is logged in based on cookies.
export const PostList = () => {
const dispatch = useDispatch();
const [isLoading, setIsLoading] = useState(null);
const [selectedTopic, setSelectedTopic] = useState("");
const posts = useSelector((state) => state.post);
const cookie = Cookies.get("cookie");
useEffect(() => {
if ( cookie !== undefined && (posts.length === 0 || posts === undefined)) {
setIsLoading(true);
dispatch(getPosts());
}
if (posts.posts !== undefined) {
setIsLoading(false);
}
}, [posts, cookie]);
My question is – is my approach correct ? If not what and how can I change it to make it work and look properly ?