Post data to Server PostgreSQL using Flutter - postgresql

What is the best practice to post data to a server, currently my database is a PostgreSql.
I would be posting to a REST Api and I want to be safe, to post I was going to use a token to verify that they are from the app but then if someone decompiles the app they will see the verification token and could then post to the API
String token = esR3bJM9bPLJoLgTesR3bJM9bPLJoLgT;
String apiUserLikes = current_server_address + "/api/user-likes/?token=$token";
final response = await http.post(
Uri.parse(apiUserLikes?token=$token),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(<String, String>{
'userID': '1234567969855478',
'UserDisplayName': 'John Jones',
'liked': 'true',
'dateLiked': '2022/12/05 00:00:00',
'eventLiked': 'Music concert at The stadium',
}),
);
What is the best way to protect users details and still post to the server
Thanks

You could never verify that the user is from the app because he can send the same request with just the command line. Even with authentication, it is still impossible to confirm. The only way to make it safe is to validate the data sent and add restriction against abuse like how many times per minute an IP/user could send data or how much could it send/download.

Instead of using static token you can use OAuth2 compliant security mechanism where token expires and new refresh token is generated/issued,
You can use firebase Auth or something like to make your App Compliant with OAuth.
For firebase Auth you can check the following link:
https://firebase.google.com/docs/auth/

Related

Flutter Supabase - custom JWT

I was using Firebase SMS auth, generate a JWT, and use the Firebase auth token as the user token in SupaBase:
Supabase.instance.client.auth.setAuth(theCustomJWTtoken);
In the 1.x version of the supabase_flutter package setAuth has been removed, and the documentation is not helping me figure out how I can continue to use custom JWTs in Flutter.
Any ideas (preferably with code)?
final supabase = SupabaseClient(supabaseUrl, supabaseKey, headers: {
'Authorization': 'Bearer $access_token',
});
This worked. Was posted on GitHub here:

Is it PCI compliant to create PaymentIntent directly from my Flutter app?

I have tried different ways to handle payment via no webhook flow, but the only solution is to call stripe API directly from my dart code as follows:
var response = await http.post(
Uri.parse('https://api.stripe.com/v1/payment_intents'),
body: {
'amount': _calculateAmount(amount),
'currency': currency,
'payment_method_types[]': 'card',
'description': description,
'receipt_email': email,
},
headers: {
'Authorization': 'Bearer ${AppConfig.instance.stripeSecretKey}',
'Content-Type': 'application/x-www-form-urlencoded'
},
);
is my code still PCI compliant and properly secured to use in production?
Your code is still PCI compliant, but not secure. Secret key must be stored securely in your web or mobile app’s server-side code (such as in an environment variable or credential management system). Calling from Dart means you are exposing your credential to the whole world. It's explained in Stripe Doc

flutter making authenticated api requests

I am trying to do something along these lines to make an authenticated api request:
Future<http.Response> fetchAlbum() {
return http.get(
'https://jsonplaceholder.typicode.com/albums/1',
// Send authorization headers to the backend.
headers: {HttpHeaders.authorizationHeader: "Basic your_api_token_here"},
);
}
I get my api tokens by calling
FirebaseUser user = FirebaseAuth.instance.signInWithEmailAndPassword(email: _email, password: _password).
My questions are:
Don't these tokens expire after a short period of time? How do I make it so my user doesn't have to constantly log in? I don't understand this at all.
Should I save my user variable in a global provider state and access it this way?
I've been watching tons of tutorials on this and I don't get it.

How to authenticate on Bluemix using SSO and REST?

I'm using rest to authenticate users to Bluemix using an API key. I would also like to implement username and password authentication.
def auth(self):
self.log.debug('Authenticating to CloudFoundry')
url = self.info['authorization_endpoint'] + '/oauth/token'
headers = {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
'Accept': 'application/x-www-form-urlencoded;charset=utf-8',
'Authorization': 'Basic Y2Y6'
}
if self.api_auth:
data = 'grant_type=password&username=apikey&password={}'.format(self.api_key)
elif self.userpass_auth:
data = 'grant_type=password&username={}&password={}'.format(self.username, self.password)
else:
raise ValueError()
# send request ...
However, when I attempt to make the request using username and password, I receive the response:
{"error_description":"BMXLS0202E: You are using a federated user ID,
please use one time code to login with option --sso.","error":"unauthorized"}
So I can send my users to the SSO web page to get a token, but what REST api do I need to make when they have the SSO token? Or, do I use the same rest api as I am doing above, but instead provide a different parameter?
Why do you want to support username and password (I feel like I'm missing a piece of the puzzle here)?
I'd recommend using API tokens as a general good practice - some of the federated logins require a web-based token step which isn't great when working with integrations.

How can I reuse an existing API (mongo + passport-local) with my react-native project?

I have a existing API (node + mongo + passport-local) that I have been using for a while. I have a Users model and Posts model. Using postman, I can register, login, and create/edit/delete posts.
The Users model contains userid, username, displayname, and of course password that passport automatically salts/hashes.
The Posts model has postid, userid, title, text, and creationdate.
I want to use this existing set up in my react-native app. So, if I have this API running on localhost:9000 or something, and I want to register users on it as well as any new posts made by a logged in user, is that possible?
I was hoping to use redux to manage my user state. The user object will initialize as null, so if it is null, show the login page. Ignoring registration for now, so if the user puts in a username/password and hits submit, the userLogin action will fire that makes a POST to localhost:9000/login with the username/pass and I get the response back which gives me the username and display name. User object is updated, and since it exists the user will be routed to the main app page.
I've been trying to learn about user authentication for react-native apps but the things I've found so far have been extremely confusing. I tried using parse but could not get it to work after spending 2 hours on it and honestly I don't even understand it. I just want to be able to use my local API and test locally.
Thanks
You can use fetch to do 'GET' and 'POST' requests. Username and password go into the body object. For example:
fetch('http://localhost:9000/login, {
method: 'POST',
crossOrigin: true,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: email,
password: pw
})
}).then((r) => {r.json()})
.then((result) => {... do something with the result})
Since fetch returns a promise, you get the result in the 'then' statement.
Based on the response you can update the state in your stores to 'logged in' our 'logged out'.