Asyncronous storage Issue react native - php

I am implementing login/signup in React Native uses Asynchronous storage. Here, when I login/signup successfully. And navigating to another page and getting the information from the Async storage stored in the previous session After login, same user_id using into this page, but not getting user_id using Async storage. Here the snippet.
async data() {
this.setState({loading:true});
let url = API.GAME;
cosnole.log(url);
const value = await AsyncStorage.getItem('user');
cosnole.log(url);
let user = JSON.parse(value);
let user_id = user.id;
cosnole.log(user_id);
let data = {
user_id:user_id,
};
cosnole.log(data);
The problem is it that when I use this method and console the function, I get an error in response saying ['user_id: undefined']. Sometime login with 'A' id and Async return previous login id 'B'.
i am posting user data after signup here the snippet
AsyncStorage.setItem("userData", "game").then(response=>{
AsyncStorage.setItem('user_id',this.props.navigation.state.params.user_id).then(async (res)=>{
await AsyncStorage.setItem('firstLogin',"true");
let url = API.getprofile;
let data = {
user_id: this.props.navigation.state.params.user_id,
};
try{
let response = await fetch(
url,
{
method: 'POST',
headers: {'Accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded'},
body: JSON.stringify(data)
}
);
let responseJson = await response.json();
if (responseJson.status === 1) {
this.state.user_data = responseJson.user;
AsyncStorage.setItem('user',JSON.stringify(responseJson.user)).then((result)=>{
this.Show_Custom_Alert(false);
this.props.navigation.navigate('app');
What should i do?
Thanks

Related

axios/ fetch failed but postman work with php api

I got stuck when calling php api with form-data type in my React app. When I test with Postman, it works correctly but failed in react.
Please let me know if I'm doing wrong here.
In Postman, call api like this:
URl_API: xxxx/yyyy.php.
Config in Body tab in key/value: form-data
k: "some string"
id: "some string"
With axios, I had an error:
My code:
const formData = new FormData()
formData.append('k', 'some string')
formData.append('id', 'some string')
const response = await axios.post('xxxx/yyyy.php', formData, {
headers: {
'Access-Control-Allow-Origin': '*',
},
})
xxxx/yyyy.php net::ERR_HTTP2_PROTOCOL_ERROR
I had already tried with fetch but no luck - call api success with status 200 but the response.text() is empty.
With fetch api:
const result = await fetch('xxxx/yyyy.php', {
method: 'POST',
mode: 'no-cors',
body: formData,
cache: 'no-cache',
})
.then(async (res) => {
return res.text()
})
.then((text) => console.log('It is empty here', text))
It look like a CORS also, but you will be able to sort it out
a simple solution in development is to use a local api server, and finally when the app is deployed to the server which is on the same domain as the api, you should get the response, as demonstrated below by making the calls using dev tools.
in short: if a api calls work with postman but not through the browser, its mostly due to cors restrictions, then it could be the response type
Verifying cors issue by making calls throught dev tools
let onSubmit = async () => {
try {
const url = "https://www.your-domain***.com/getUrlApp.php";
const formData = new FormData();
formData.append("k", "kk");
formData.append("id", "dd");
const data = new URLSearchParams(formData);
const response = await fetch(url, {
method: "POST", // *GET, POST, PUT, DELETE, etc.
mode: "no-cors", // no-cors, *cors, same-origin
body: data // body data type must match "Content-Type" header
});
//const res = response.json();
const buffer = await response.arrayBuffer();
const decoder = new TextDecoder("iso-8859-1");
const text = decoder.decode(buffer);
console.log("text", text);
return response;
} catch (error) {
console.log("error", error);
}
};
To verify the response
go https://www.your-domain***.com
open dev tools => console
past the function above and run it by typing onSubmit() in the console
you will see the response
Hope it helps you in some way

Encrypt with flutter and php, decrypt with php and flutter

I have a chat application created using flutter dart and php mysql as backend and also node js for socket.io
So what i want is if i send a message via flutter dart, i want to encrypt it and send to node js via socket.io which will send it to the other client's flutter app and decrypt it there for the user to see and the node.js will also send it to my php script via json format and stores it in my database via post request. Also I will soon create a website where those messages will be decryted and displayed on the user browser and when i send message using the browser i also want to encrypt it and store in the database so that both flutter and web user can see the decrypted format.
const https = require("https");
const http = require("http");
const qs = require("querystring");
function send_to_db(msg) {
console.log(msg);
var postData = qs.stringify(msg);
var options = {
hostname: "*****.com",
port: 443,
path: "/src/chats/post.php",
method: "POST",
rejectUnauthorized: true,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Content-Length": postData.length,
},
checkServerIdentity: function (host, cert) {
return undefined;
},
};
var buffer = "";
var req = https.request(options, (res) => {
res.on("data", function (chunk) {
buffer += chunk;
});
res.on("end", function () {
console.log(buffer);
});
});
req.on("error", (e) => {
console.error(e);
});
req.write(postData);
req.end();
return buffer;
}
Right now is am only encrypting and decrypting using php and am afraid of man in the middle attack since my data can be intercepted from flutter app to node.js before reaching my php side
Please what do I do to achieve this

TypeError: Network request failed using fetch ReactNative and Laravel response

I am posting data to Laravel and expect a success response, but it catches the exception TypeError: Network request failed. Using get methods and login post methods using Laravel passport works all fine.
Adding 'Content-Type': 'application/json' to headers creates Network request failed for the login methods.
Postman returns valid errors or success, so works totally as expected.
Debugging showed that the request has been sent to Laravel and routing is correct as Visual Studio Code debugger stops at a breakpoint at return response.
public function postMessages()
{
...
return response()->json(['success' => 'success'], 200);
}
Route::middleware('auth:api')->group(function () {
Route::post('messages', 'Api\ChatController#postMessages');
});
export const fetchApi = async (endPoint, method = 'get', body = {}) => {
const accessToken = authSelectors.get().tokens.access.value;
const accessType = authSelectors.get().tokens.access.type;
let headers = {
...(accessToken &&
{
Authorization: `${accessType} ${accessToken}`
}
)
};
let response;
if (method=='get' || Object.keys(body)==0 ) {
response = await fetch(`${apiConfig.url}${endPoint}`, {
method: method,
headers: headers
});
} else {
var formData = new FormData();
Object.keys(body).forEach(type => {
formData.append(type, body[type]);
});
response = await fetch(`${apiConfig.url}${endPoint}`, {
method: method,
headers: headers,
body: formData
});
console.log('fetch response: ' + JSON.stringify(response));
}
let responseJsonData = await response.json();
return responseJsonData;
}
export const postMessages = (eidug, type, name, messages) => fetchApi('/message', 'post', {
'eidug': eidug,
'type': type,
'name': name,
'messages': messages
});
I expect a response without any exception like Postman. What can be going wrong?
Have you enabled CORS in the backend? Once open inspect->network and then run fetch. Show if there are any errors.

Laravel with AngularJS Login

Im using Laravel 5 as an API and i have AngularJS running my frontend.
I have built the login portion of the backend that accepts the form data and responds with a json object.
My question is when i recieve the success object from the api to say that the login details are sucessfull. How do i use AngularJS to then login the user from the frontend.
AuthenticateUser.php
http://pastebin.com/PZqGCpz5
app.js
var app = angular.module('app', []);
app.controller('AppCtrl', function($scope, $http) {
$scope.login = {};
$scope.submitLoginForm = function () {
var email = $scope.login.email;
var password = $scope.login.password;
$http({
method : 'POST',
url : '/api/1.0/auth/login',
data : { email, password },
headers : { 'Content-Type': 'application/json' }
})
.success(function(data) {
console.log(data);
});
}
}
JSON Response
success: Object
message : authentication_successfull
code : 200
user_id : 1
What steps should i take from here to log the user into the frontend.
Thanks in advance
You can do this with the help of api_token approach.
First when you call a login api then create a unique token specific to user and save it database and send it in response as:
success: Object
message : authentication_successfull
code : 200
data : {api_token: some_random_key}
Then for subsequent request send that api_token in the request headers.
And server will automatically logins the user if you are using the auth:api middleware as:
Route::group(['middleware' => ['auth:api']], function()
{
// API routes here
});
For reference

How to save Facebook user data to MySql database with Angular and Ionic

I am working an an Ionic app where I implement native Facebook login (followed this tutorial -> https://ionicthemes.com/tutorials/about/native-facebook-login-with-ionic-framework). As you can see the Facebook data now gets stored in local storage. I need to save this data in my MySql database.
I got this to work without any issues. Now I want to store the Facebook user data to my MySql database.
Basically I am not sure where to place my http request to pass the data along to my database or how to even do it code wise.
I should mention that I have a backend already setup (which is coded with bootstrap, html, css, js php and mysql).
So the url for my users would be this: http://www.xxxxx.com/user.php
Part of my controller code:
app.controller('LoginCtrl', function($scope, $state, $q, UserService, $ionicLoading) {
// This is the success callback from the login method
var fbLoginSuccess = function(response) {
if (!response.authResponse){
fbLoginError("Cannot find the authResponse");
return;
}
var authResponse = response.authResponse;
getFacebookProfileInfo(authResponse)
.then(function(profileInfo) {
// For the purpose of this example I will store user data on local storage
UserService.setUser({
authResponse: authResponse,
userID: profileInfo.id,
name: profileInfo.name,
email: profileInfo.email,
picture : "http://graph.facebook.com/" + authResponse.userID + "/picture?type=large"
});
$ionicLoading.hide();
$state.go('app.dashboard');
}, function(fail){
// Fail get profile info
console.log('profile info fail', fail);
});
};
// This is the fail callback from the login method
var fbLoginError = function(error){
console.log('fbLoginError', error);
$ionicLoading.hide();
};
// This method is to get the user profile info from the facebook api
var getFacebookProfileInfo = function (authResponse) {
var info = $q.defer();
facebookConnectPlugin.api('/me?fields=email,name&access_token=' + authResponse.accessToken, null,
function (response) {
console.log('logging facebook response',response);
info.resolve(response);
},
function (response) {
console.log(response);
info.reject(response);
}
);
return info.promise;
};
//This method is executed when the user press the "Login with facebook" button
$scope.facebookSignIn = function() {
facebookConnectPlugin.getLoginStatus(function(success){
if(success.status === 'connected'){
// The user is logged in and has authenticated your app, and response.authResponse supplies
// the user's ID, a valid access token, a signed request, and the time the access token
// and signed request each expire
console.log('getLoginStatus', success.status);
// Check if we have our user saved
var user = UserService.getUser('facebook');
if(!user.userID){
getFacebookProfileInfo(success.authResponse)
.then(function(profileInfo) {
// For the purpose of this example I will store user data on local storage
UserService.setUser({
authResponse: success.authResponse,
userID: profileInfo.id,
name: profileInfo.name,
email: profileInfo.email,
picture : "http://graph.facebook.com/" + success.authResponse.userID + "/picture?type=large"
});
$state.go('app.dashboard');
}, function(fail){
// Fail get profile info
console.log('profile info fail', fail);
});
}else{
$state.go('app.dashboard');
}
} else {
// If (success.status === 'not_authorized') the user is logged in to Facebook,
// but has not authenticated your app
// Else the person is not logged into Facebook,
// so we're not sure if they are logged into this app or not.
console.log('getLoginStatus', success.status);
$ionicLoading.show({
template: 'Logging in...'
});
// Ask the permissions you need. You can learn more about
// FB permissions here: https://developers.facebook.com/docs/facebook-login/permissions/v2.4
facebookConnectPlugin.login(['email', 'public_profile'], fbLoginSuccess, fbLoginError);
}
});
};
})
My service.js code (local storage)
angular.module('Challenger.services', [])
.service('UserService', function() {
// For the purpose of this example I will store user data on ionic local storage but you should save it on a database
var setUser = function(user_data) {
window.localStorage.starter_facebook_user = JSON.stringify(user_data);
};
var getUser = function(){
return JSON.parse(window.localStorage.starter_facebook_user || '{}');
};
return {
getUser: getUser,
setUser: setUser
};
});
My recommendation is to simply use a JSON ajax PUT or POST from JavaScript. For example, assuming a backend host of example.com
Add a CSP to the Ionic HTML such as:
<meta http-equiv="Content-Security-Policy" content="default-src http://example.com; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'">
Add the domain to the whitelist in the Cordova config.xml:
<access origin="http://example.com" />
Then you can call PHP from JavaScript with ajax in your angular controller (I used jQuery here but you can use any JavaScript ajax library):
var data = {
authResponse: authResponse,
userID: profileInfo.id,
name: profileInfo.name,
email: profileInfo.email,
picture : "http://graph.facebook.com/" + authResponse.userID + "/picture?type=large"
};
$.post( "http://example.com/login.php", data, function(returnData, status) {
console.log('PHP returned HTTP status code', status);
});
Finally, on the PHP side — e.g. login.php — access the post data with $_POST['userId'], $_POST['email'], etc.
I guess that you have all your codes ready, but just not sure where is the best place to locate your codes. There is nice linker where has clear instruction about how to layout your php project structure: http://davidshariff.com/blog/php-project-structure/, hope this can give a kind of help.

Categories