I'm making an app where different users can add their own plants/flowers.
The flowerlist contains the users flowers and loads these items upon mounting.
class flowerList extends Component {
componentDidMount() {
this.props.getFlowers();
}
To send the correct GET request to the backend I need to have the currently logged in user's ID.
This is what the called action creator looks like:
export const getFlowers = () => (dispatch, getState) => {
dispatch(setFlowersLoading());
axios
.get(`/api/users/${getState().auth.user.id}/flowers`)
.then((res) =>
dispatch({
type : GET_FLOWERS,
payload : res.data
})
)
.catch((err) => dispatch(returnErrors(err.response.data, err.response.status)));
};
However, this doesn't work very well. It only works when coming directly from signing in. If I refresh the page, the app crashes with the error message "TypeError: Cannot read property 'id' of null". When writing the POST requests in a similar fashion it doesn't work well either, so I guess there must be a better way to access the state. I'd really appreciate any help in getting this to work.
When you login, you should set local storage to keep the users info something like these:
const setAuthorizationHeader = token => {
const Token = `Bearer ${token}`;
localStorage.setItem("Token", Token);
axios.defaults.headers.common["Authorization"] = Token;
};
you can add it to your user login action, after then(), when the login is successful, here is an example, I assume you handle the token in the backend, so after successful login, it sends the token with a respond(res.data):
export const loginUser = (userData) => dispatch => {
axios
.post("http://localhost:5000/api/users/login", userData)
.then(res => {
setAuthorizationHeader(res.data.token);
})
.catch(err => {
dispatch({
type: SET_ERRORS,
payload: err.response
});
});
};
Afterwards, put these to your app.js:
const token = localStorage.Token;
if (token) {
const decodedToken = jwtDecode(token);
if (decodedToken.exp * 1000 < Date.now()) {
store.dispatch(logoutUser());
window.location.href = "/login";
} else {
store.dispatch({ type: SET_AUTHENTICATED_USER });
axios.defaults.headers.common["Authorization"] = token;
store.dispatch(getUserData(decodedToken));
}
}
Here I used jwtDecode because I am using JWT to crypt my users' info and store it to the localStorage, these codes provide to look for Token in localStorage after refreshing the page. If the user logged in, there is the token and so the app will not crash
Related
I am using react native for an ios app and firebase for authentication. Every time I leave the app and come back, it asks for a login. I want to persist the firebase login but don't really know where to put it.
I know I need to put this in:
firebase.auth().setPersistence(firebase.auth.Auth.Persistence.LOCAL)
I have the following signIn function that runs when the login button is pressed on the signInScreen:
const signIn = async () => {
setLoading(true);
try {
await firebase.signIn(email, password);
const uid = firebase.getCurrentUser().uid;
const userInfo = await firebase.getUserInfo(uid);
const emailArr = userInfo.email.split("#");
setUser({
username: emailArr[0],
email: userInfo.email,
uid,
isLoggedIn: true,
});
} catch (error) {
alert(error.message);
} finally {
isMounted.current && setLoading(false);
}
};
I have the following signIn stuff in my firebaseContext:
const Firebase = {
getCurrentUser: () => {
return firebase.auth().currentUser;
},
signIn: async (email, password) => {
return firebase.auth().signInWithEmailAndPassword(email, password);
},
getUserInfo: async (uid) => {
try {
const user = await db.collection("users").doc(uid).get();
if (user.exists) {
return user.data();
}
} catch (error) {
console.log("Error #getUserInfo", error);
}
},
logOut: async () => {
return firebase
.auth()
.signOut()
.then(() => {
return true;
})
.catch((error) => {
console.log("Error #logout", error);
});
},
};
Where do I put the persist code I listed above from the docs?
Thanks!
When do you check if someon is signed in or not?
From the code shown it looks like you check it manuelly by calling currentUser. You have to consider that the persistance of auth state is asynchronous. That means if you call currentUser on auth before the localy saved auth state is loaded you would get there null and thing that the user is not signed in.
To get the auth state Firebase recommend to use the onAuthStateChanges event listener. With that you can listen to auth state changes no matter if you logged in or the persistet auth state is loaded.
The usage is very simple:
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
} else {
// No user is signed in.
}
});
That is the reson I asked where you check if someon is signed in or not. If I could see that code I could help you adopt it to use that event listener.
I'm using https://github.com/anthonyjgrove/react-google-login for auth in my React app. Everything's working except when I close all my tabs and return to my site (within seconds, not even that long), I have to sign in again... How can I persist the login for some amount of time?
Here's my current setup:
<GoogleLogin
clientId={process.env.REACT_APP_GOOGLE_OAUTH_CLIENT_ID}
buttonText='Continue with Google'
onSuccess={handleGoogleOAuthResponse}
onFailure={handleError}
isSignedIn={true}
prompt='consent'
accessType='offline'
redirectUri={process.env.REACT_APP_FRONT_END_BASE_URL}
/>
const handleGoogleOAuthResponse = ({ accessToken, profileObj }) => {
postRequest('rest-auth/google/', null, { 'access_token': accessToken }) // backend in Django
.then(({ access_token, refresh_token, user }) => {
setAccessToken(access_token); // these are just local states
setRefreshToken(refresh_token);
setProfile(profileObj);
setError(null);
})
.catch(error => {
setError(error);
});
};
const handleError = (error, details) => {
setError(`${error}: ${details}`);
}
The issue is using just the ephemeral state, which gets lost on page reload (and even every time component unmounts) as it is in-memory only. One quick solution would be to also store your token in a localStorage:
.then(({ access_token, refresh_token, user }) => {
setAccessToken(access_token); // these are just local states
setRefreshToken(refresh_token);
setProfile(profileObj);
setError(null);
// in addition to existing code above, add this part to persist the tokens
localStorage.setItem('accessTokenKey', access_token);
localStorage.setItem('refreshTokenKey', refresh_token);
})
With tokens stored, we need to load them as well upon next start of the app, which can be done like this:
useEffect(() => {
const access_token = localStorage.getItem('accessTokenKey');
const refresh_token = localStorage.setItem('refreshTokenKey');
setAccessToken(access_token);
setRefreshToken(refresh_token);
}, []);
or used as initial state in the useState hooks:
const [refreshToken, setRefreshToken] = useState(localStorage.getItem('refreshTokenKey'));
const [accessToken, setAccessToken] = useState(localStorage.getItem('accessTokenKey'));
I try to get a list from the backend in Reactjs component with JWT token but I get an error message {"status":"Token is Invalid"}, please guide me.
My backend API is working fine and my token is saved in the localstore after login.
my frontend used API code
import {API} from "../config";
/**
* to get about pages
* get a single about page
* update a about page
* delete about page
*/
export const getAboutContent = (token) =>{
return fetch(`${API}/about/?token=${token}`, {
method: "GET",
})
.then(response =>{
return response.json();
})
.catch(err =>{
console.log(err);
});
};
about/index.js
const [allAboutContent, setAllAboutContent] = useState([]);
const loadAllAboutContent = () => {
getAboutContent().then(data => {
if(data.error){
console.log(data.error)
} else{
setAllAboutContent(data.data)
}
});
};
useEffect(() =>{
loadAllAboutContent();
}, [])
Please help.
You are invoking getAboutContent in about/index.js file without JWT and hence it not defined. Just update your code to read JWT from localStorage like below
const loadAllAboutContent = () => {
// Read token from local storage
const token = localStorage.getItem('jwt');
// Pass to getAboutContent
getAboutContent(token).then(data => {
if(data.error){
console.log(data.error)
} else{
setAllAboutContent(data.data)
}
});
};
Also, I see you have stored your token as {token: ''}. Maybe, you can directly save it. Otherwise you have to read it like this JSON.parse(localStorage.getItem('jwt')).token
I created authorization in javascript. Then if success login I redirect to React project with url parameter http://localhost:3000/?phoneNum=%2B77072050399
Then in React I get userId by using the passed url parameter => phoneNumber using axios.
I realized it in App.js. Code below:
let url = window.location.href;
let params = (new URL(url)).searchParams;
const userPhoneNum = encodeURIComponent(params.get('phoneNum'));
const [userToken, setUserToken] = useState(null);
const getUserToken = async() => {
try {
const data = await axios
.get(`https://stormy-escarpment-89406.herokuapp.com/users/getToken?phone_number=${userPhoneNum}`)
.then(response => {
setUserToken(response.data);
})
.catch(function(error) {
console.log('No such user! Error in getting token!');
});
} catch (e) {
console.log(e);
}
}
useEffect(() => {
getUserToken();
console.log(userToken);
}, userToken);
So, when I go to next page localhost:3000/places, it is requesting for userToken again with parameter null, because there is no param phoneNum.
How to make it to request only one time and save the userId after it is taken in main page. So, then only when I click LogOut button reset the variable where userID is saved.
If you want to do that without using any third party libraries you can use browser's in built storage api
So, when you receive the token, you can store that in the local storage of the browser using localstorage.setItem and later when you wan to see if the token is there or not just read from there using localStorage.getItem
const getUserToken = async() => {
try {
const data = await axios
.get(`https://stormy-escarpment-89406.herokuapp.com/users/getToken?phone_number=${userPhoneNum}`)
.then(response => {
setUserToken(response.data);
Storage.setItem('token',JSON.stringify(response.data))
})
.catch(function(error) {
console.log('No such user! Error in getting token!');
});
} catch (e) {
console.log(e);
}
}
For Logout you can simply remove the token using localStorage.removeItem
You can easily achieve this by using the react-cookie library
npm i react-cookie
Can be easily implemented in your code by
cookies.set('key', value, { path: '/' });
cookies.get('key')
After getting the userNumber form the param
const userPhoneNum = encodeURIComponent(params.get('phoneNum'));
cookies.set('userphoneNum', userPhoneNum);
View the documentation for more information
https://www.npmjs.com/package/react-cookie
I'm learning how to test a frontend webapp without any connection to the API.
My problem is: I have to test an POST HTTP Request but always get an error : TypeError: loginUser(...).then is not a function.
I know my expect is not correct. I must change the data for a JWT token, and also don't know yet hot to do it.
It's a simple user authentication. Http post sending an email and password, getting back a JWT (json web token). I have to write a test to make sure I've send the correct information and get a JWT as response.
Thanks for your help
Here is my code:
//login.test.js
const expect = require('chai').expect;
const loginUser = require('../src/actions/authActions').loginUser;
const res = require('./response/loginResponse');
const nock = require('nock');
const userData = {
email: 'test#test.com',
password: '123456'
};
describe('Post loginUser', () => {
beforeEach(() => {
nock('http://localhost:3000')
.post('/api/users/login', userData )
.reply(200, res);
});
it('Post email/pwd to get a token', () => {
return loginUser(userData)
.then(res => {
//expect an object back
expect(typeof res).to.equal('object');
//Test result of name, company and location for the response
expect(res.email).to.equal('test#test.com')
expect(res.name).to.equal('Tralala!!!')
});
});
});
//authActions.js
import axios from "axios";
import setAuthToken from "../utils/setAuthToken";
import jwt_decode from "jwt-decode";
import {
GET_ERRORS,
SET_CURRENT_USER,
USER_LOADING
} from "./types";
// Login - get user token
export const loginUser = userData => dispatch => {
axios
.post("/api/users/login", userData)
.then(res => {
// Save to localStorage
// Set token to localStorage
const { token } = res.data;
localStorage.setItem("jwtToken", token);
// Set token to Auth header
setAuthToken(token);
// Decode token to get user data
const decoded = jwt_decode(token);
// Set current user
dispatch(setCurrentUser(decoded));
})
.catch(err =>
dispatch({
type: GET_ERRORS,
payload: err.response.data
})
);
// loginResponse.js
module.exports = { email: 'test#test.com',
password: '123456',
name: "Tralala!!!"
};
Actual result:
1) Post loginUser
Post email/pwd to get a token:
TypeError: loginUser(...).then is not a function
at Context.then (test/login.test.js:37:12)
The way you called loginUser method is not correct. This method returns another function. So, instead of loginUser(userData), you must also specify the dispatch parameter e.g. loginUser(userData)(dispatch).then().
I changed the method to specify return before axios statement
export const loginUser = userData => dispatch => {
return axios // adding return
.post("/api/users/login", userData)
.then(res => {
...
})
.catch(err =>
dispatch({
type: GET_ERRORS,
payload: err.response.data
})
);
};
for test, I may involve Sinon to spy the dispatch
it("Post email/pwd to get a token", () => {
const dispatchSpy = sinon.spy();
return loginUser(userData)(dispatchSpy).then(res => {
//expect an object back
expect(typeof res).to.equal("object");
//Test result of name, company and location for the response
expect(res.email).to.equal("test#test.com");
expect(res.name).to.equal("Tralala!!!");
});
});
Hope it helps