Firebase signInWithCustomToken in React Native - javascript

I use email and password for login at first login and I have a token with getToken() function, after I add localStoreage with AsyncStoreage.setItem("ACCESS_TOKEN",token). I want to refresh to app signup with token and I use signInWithCustomToken(token) but I have an error. its 'auth/invalid-custom-token' (The token you provided is not valid.). I can't login.
DataStore.js
onLogin: function (Data) {
ApiRequest.login(Data)
.then((authData) => {
authData.getToken().then((token)=>{
AccessToken.set(token)
.then(() => Actions.login.completed(authData));
})
.catch((err) => Actions.login.failed(err))
})
.catch((err) => Actions.login.failed(err))
}
ApiRequest.Js
login(data) {
// first.login data = (email.password) && after.login data=(token)
return new Promise((next, error) => {
if (data && data.email && data.password) {
this.firebase.auth().signInWithEmailAndPassword(data.email,data.password)
.then((uData) => {;
next(uData)
})
.catch((err)=> error(err));
} else {
console.log("TOKEN:");
console.log(data);
this.firebase.auth().signInWithCustomToken(data)
.then((authData)=>next(authData))
.catch((err)=>{console.log("Error #232",err)})
}
});
}
AccessToken.Js
get(){
return new Promise((next,error) => {
if(this._accessToken) {
console.log("LastToken");
return next(this._accessToken);
}
AsyncStorage.getItem("ACCESS_TOKEN")
.then((token)=>{
if(token){
next(JSON.parse(token));
}else{
error()
}
})
.catch((err)=>error(err));
});
}
set(token){
this._accessToken=token;
return AsyncStorage.setItem("ACCESS_TOKEN",JSON.stringify(token));
}
Authenticate Listener
actions.auth.listen(function () {
AccessToken.get()
.then((token) => actions.login(token))
.catch((err) => actions.logout());
})
Token
eyJhb...Ckz95w

Related

remember me checkbox in login that using token in react js

I want to add a Clickable “Remember Me” checkbox in my login page that tells the browser to save a cookie so that if you close out the window for the site without signing out, the next time you go back, you will be signed back in automatically.that can save username and password
export const getUser = () => {
const userStr = sessionStorage.getItem("user");
if (userStr) return JSON.parse(userStr);
else return null;
};
export const getToken = () => {
return sessionStorage.getItem("token") || null;
};
export const setUserSession = (token, user) => {
sessionStorage.setItem("token", token);
sessionStorage.setItem("user", JSON.stringify(user));
};
export const removeUserSession = () => {
sessionStorage.removeItem("token");
sessionStorage.removeItem("user");
};
export const handleSuccessfulLogin = async (token, rememberMe) => {
localStorage.setItem("token", token);
localStorage.setItem("rememberme", rememberMe);
};
export const handleLogout = () => {
localStorage.clear();
};
This is my login that work with api
const handelLogin = () => {
setError(null);
setLoading(true);
axios
.post("https://www.mecallapi.com/api/login", {
username: username,
password: password,
})
.then((response) => {
setLoading(false);
setUserSession(response.data.token, response.data.user);
navigate("/Dashboard");
})
.catch((error) => {
setLoading(false);
if (error.response.status === 401 || error.response.status === 400) {
setError(error.response.data.message);
} else {
setError("somthing went wrong ,please try again");
}
});
};
This is my remember me checkbox
<div className="login-bottom">
<Checkbox {...label} />
</div>

SwitchMap not triggering second API call

The below angular code switchMap is not working, I'm not sure what error I made. Under the switchMap second API call not triggering '/upload/file'
zip(
this.service.submitForm(formValue),
this.service.upload(fData)
).subscribe(
([submitForm, upload]) => {
if (submitForm === 'success' && upload === 'Ok') {
//Redirect confirmation page
}
},
(err) => {
console.log(err, 'ERORORO');
}
)
//Service code
upload(formData): Observable <any> {
return this.sessionService.keepAlive().pipe(
switchMap(data => {
let token = data.jwtToken;
console.log(token, 'TOKEN SESSION');
// getting output as Bearer xyz
// with formData as req
const request_config = {
headers: {
"Authorization": token
}
};
console.log("REQUEST CONFIG", request_config); // getting output
return this.http.post < any > (
'/upload/file',
formData,
request_config
).pipe( // this is not working
map((res) => {
console.log(res, 'RESPONSE');
return res.status;
}),
catchError((error: HttpErrorResponse) => {
throw error;
})
)
})
)
}

Cannot read property 'navigate' of undefined in a .then() => { }

Why can't I navigate to the screen "App" in the following code. I get the error:
Cannot read property 'navigate' of undefined
async signIn() {
const { username, password } = this.state
await Auth.signIn(username, password)
.then(user => {
this.setState({ user })
this.props.navigation.navigate("App");
Alert.alert('Signed In Successful!')
})
.catch(err => {
console.log('Error when signing in: ', err)
Alert.alert('Error when signing in: ', err)
})
}
}
You are mixing promises and await. You either await for the sign in, or remove the async/await and treat it like a promise. Also, it could be that you haven't binded the function so "this" points to undefined.
Either:
async signIn = () => {
const { username, password } = this.state
let user = await Auth.signIn(username, password);
this.setState({ user })
this.props.navigation.navigate("App");
Alert.alert('Signed In Successful!')
}
}
Or
signIn = () => {
const { username, password } = this.state
Auth.signIn(username, password)
.then(user => {
this.setState({ user })
this.props.navigation.navigate("App");
Alert.alert('Signed In Successful!')
})
.catch(err => {
console.log('Error when signing in: ', err)
Alert.alert('Error when signing in: ', err)
})
}
}

Axios interceptor refresh token for multiple requests

I'll throw the http request because I'm calling the refresh token when it returns 401. After the refresh token response, I need to throw the previous request
SAMPLE
Logın -> — 1 hours later— —> call product —> 401 —> call refresh token —> call product
I try this link a link and look this link a link but doesn't work.
Catch the 401 error
setInterceptors = () => {
axios.interceptors.response.use(
response => {
return response;
},
err => {
return new Promise((resolve, reject) => {
if (err.response.status === 401 && err.config && !err.config.__isRetryRequest) {
const originalRequest = err.config;
this.emit('onAutoLogin', originalRequest);
}
// throw err;
});
}
);
};
Call my action
jwtService.on('onAutoLogin', originalRequest => {
jwtService
.signInWithToken()
.then(res => {
if (res.access_token) {
originalRequest.headers['Authorization'] = 'Bearer ' + res.access_token;
Axios.request(originalRequest).then(response => {
store.dispatch({
type: ** MY PROBLEM İS HERE **
payload: response.data
});
});
}
})
.catch(err => {
jwtService.setSession(null);
});
using this link I was able to solve the problem without triggering the redux store.
let isRefreshing = false;
let failedQueue = [];
const processQueue = (error, token = null) => {
failedQueue.forEach(prom => {
if (error) {
prom.reject(error);
} else {
prom.resolve(token);
}
});
failedQueue = [];
};
axios.interceptors.response.use(
response => {
return response;
},
err => {
const originalRequest = err.config;
if (err.response.status === 401 && !originalRequest._retry) {
if (isRefreshing) {
return new Promise(function(resolve, reject) {
failedQueue.push({ resolve, reject });
})
.then(token => {
originalRequest.headers['Authorization'] = 'Bearer ' + token;
return axios(originalRequest);
})
.catch(err => {
return Promise.reject(err);
});
}
originalRequest._retry = true;
isRefreshing = true;
return new Promise(function(resolve, reject) {
axios
.post('/fooUrl/refreshToken', {
refreshToken: "fooToken"})
.then(({ data }) => {
axios.defaults.headers.common['Authorization'] = 'Bearer ' + data.fooToken;
originalRequest.headers['Authorization'] = 'Bearer ' + data.fooToken;
processQueue(null, data.fooToken);
resolve(axios(originalRequest));
})
.catch(err => {
processQueue(err, null);
store.dispatch(showMessage({ message: 'Expired Token' }));
reject(err);
})
.then(() => {
isRefreshing = false;
});
});
}
return Promise.reject(err);
}
);

How catch error from async action with redux?

I have fetch, it throws error:
fetchAuthorization(username, password) {
return fetch(`https://api.github.com/user`, {
method: 'GET',
headers: {
"Accept": 'application/json',
"Content-Type": 'application/json',
"Authorization": "Basic " + btoa(`${username}:${password}`)
},
})
.then(res => {
if(res.status !== 200) {
throw Error("Bad validation");
}
return res.json();
});
},
then this async action (redux):
export const onSignInAction = (username, password) => {
return dispatch => {
return api.fetchAuthorization(username, password)
.then( res => {
dispatch(signInAction(username, password, res));
})
.catch(err => console.log(err));
}
}
next:
handleSignIn = (username, password) => {
const { onSignInAction } = this.props;
onSignInAction(username, password);
}
And now I want catch Error from my fetch :
handleSignIn = () => {
const { onSignIn } = this.props;
const { errorMessage, open } = this.state;
const username = this.usernameField.getValue();
const password = this.passwordField.getValue();
try {
onSignIn(username, password);
}
catch (Error) {
this.setState({
errorMessage: 'Incorrect username or password'
});
}
}
How to catch it correctly? My code doesn't do this stuff. Thanks!
You can throw error from .catch(), substitute Promise.prototype.catch() for try..catch
var onSignInAction = () => {
return Promise.reject(new Error("Bad validation")).catch(e => {
console.log("catch 1", e.message);
throw e
});
}
onSignInAction()
.catch(err => {
console.log("catch 2:", {
errorMessage: 'Incorrect username or password'
}, err.message);
});

Categories