I'm fairly new using this framework so please bear with me.
I tried following the docs (3.12.1) in Auth Provider and was able to authenticate user from my backend.
However, this code
logout: () => {
localStorage.removeItem("auth");
return Promise.resolve();
},
keeps on logging me out, prompting me to Please login to continue
Here is my code...
authProvider.js
const authProvider = {
logout: () => {
localStorage.removeItem("auth");
return Promise.resolve();
},
login: ({ username, password }) => {
const request = new Request("http://localhost:3000/api/auth", {
method: "POST",
body: JSON.stringify({ username, password }),
headers: new Headers({ "Content-Type": "application/json" }),
});
return fetch(request)
.then((response) => {
if (response.status < 200 || response.status >= 300) {
throw new Error(response.statusText);
}
return Promise.resolve();
})
.then((auth) => {
localStorage.setItem("auth", JSON.stringify(auth));
})
.catch(() => {
throw new Error("Network error");
});
},
checkError: ({ status }) => {
if (status === 401 || status === 403) {
localStorage.removeItem("username");
return Promise.reject();
}
return Promise.resolve();
},
checkAuth: () => {
localStorage.removeItem("username");
return localStorage.getItem("username")
? Promise.resolve()
: Promise.reject();
},
getPermissions: () => Promise.resolve(),
};
export default authProvider;
Response I get from the server
{
"success": true,
"message": "Successfully Logged In!",
"userData": {
"user_id": "601d25ca48305c2ef1e6a42c",
"firstName": "test",
"lastName": "test",
"username": "test@mail.com",
"token": "eyJhbGciOiJIUzI1NiJ9.NjAxZDI1Y2E0ODMwNWMyZWYxZTZhNDJj.WvYB9-H2kVTtCvRB4YumJe17EIIb0Kiz2t8h1g-IcwY"
}
}
Well, as far as I see - your checkAuth function will always reject the Promise, which automatically redirects to logout.
Why are you setting the auth inside localStorage and then on checkAuth you are searching for username (although you alway remove it at first)?
You should sync these two functions and should be good to go.