flutter http invalid header name - http

I got a problem with the header.
Invalid header field name, with 128
One important thing FYI, when I use the JSON MOCK SERVER, it works very well, after switching DOCKER environment I got the error. I would like to add other details. I also test my real back-end code which is works on the docker environment, I test on the browser with fetch API, and also angular application works well. I think that there is not related to my back-end or such kind of CORS issues.
Future<void> login(String email, String password) async {
final String url = '$baseUrl/login';
try {
final http.Response response = await http.post(
url,
headers: <String, String>{
HttpHeaders.contentTypeHeader: 'application/json; charset=UTF-8',
},
body: jsonEncode(<String, String>{
'email': email,
'password': password,
'device_name': 'apple',
}),
);
if (response.statusCode != 200) {
throw HttpException('An error occured ${response.statusCode}');
}
if (response.statusCode == 422) {
throw UnprocessableEntity('form values not okay');
}
final Login user = Login.fromJson(json.decode(response.body));
_token = user.data.token;
_email = email;
final SharedPreferences sharedPreferences =
await SharedPreferences.getInstance();
final userData = json.encode({
'token': _token,
'email': _email,
});
sharedPreferences.setString('userData', userData);
notifyListeners();
} catch (exception) {
throw exception;
}
}

The network has been hijacked. Maybe you should consider HTTPS

Related

Flutter WooCommerce Customer registeration failed using Dio and jwt?

I am buidling flutter woocommerce store app for customers. I want to create/register a new customer using Dio() and I am using WordPress Plugin JWT Authentication for WP REST API for authentication. Here if i want to access URL for Customers Its showing following response. URL= "https://example.com/wp-json/wc/v3/customers"
{"code":"rest_no_route","message":"No route was found matching the URL and request method.","data":{"status":404}}
CUSTOMER MODEL FILE IS...
class CustomerModel {
String email;
String firstName;
String lastName;
String password;
CustomerModel(
{required this.email,
required this.firstName,
required this.lastName,
required this.password});
Map<String, dynamic> toJson() {
Map<String, dynamic> map = {};
map.addAll({
'email': email,
'first_name': firstName,
'last_name': lastName,
'password': password,
'username': email
});
return map;
}
}
API MODEL FILE IS...
Future<bool> createCustomer(CustomerModel model) async {
var authToken =
base64.encode(utf8.encode(Config.key + ':' + Config.sceret));
print(authToken);
bool ret = false;
try {
print("${Config.url+ Config.customerURL}");
var response = await Dio().post(Config.url + Config.customerURL,
data: model.toJson(),
options: new Options(headers: {
HttpHeaders.authorizationHeader: 'Basic $authToken',
HttpHeaders.contentTypeHeader: 'application/json'
}));
print(response.statusCode);
if (response.statusCode == 201) {
ret = true;
}
} on DioError catch (e) {
if (e.response?.statusCode == 404) {
ret = false;
} else {
ret = false;
}
}
return ret;
}
404 means that url that you are requesting is not exist on the server.
Double-check the actual URL you are requesting and compare with expected one.
404 Not Found
The requested resource could not be found but may be available in the future. Subsequent requests by the client are permissible.

Cant send message with oneSignal, Error: String is not a subtype of type List<String>

I am trying to send a text from my device using oneSignal using the token Id, My tokenId shows correctly in the firebase console However as I try to send it I get an error type 'String' is not a subtype of type 'List<String>' Please help me fix it
class _NewMessageState extends State<NewMessage> {
Future<Response> sendNotification(
List<String> tokenIdList, String contents, String heading) async {
return await post(
Uri.parse('https://onesignal.com/api/v1/notifications'),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(<String, dynamic>{
"app_id":
"385efff8-************-0fe852ac796c", //kAppId is the App Id that one get from the OneSignal When the application is registered.
"include_player_ids":
tokenIdList, //tokenIdList Is the List of All the Token Id to to Whom notification must be sent.
// android_accent_color reprsent the color of the heading text in the notifiction
"android_accent_color": "FF9976D2",
"small_icon": "ic_stat_onesignal_default",
"large_icon":
"https://www.filepicker.io/api/file/zPloHSmnQsix82nlj9Aj?filename=name.jpg",
"headings": {"en": heading},
"contents": {"en": contents},
}),
);
}
var _enterMessage = '';
//controller for textfield to clear it
final _controller = new TextEditingController();
void _sendMessage() async {
//send message
FocusScope.of(context).unfocus();
final user = FirebaseAuth.instance
.currentUser; //gets the current logged in user gives data like userId
final userData = await FirebaseFirestore.instance
.collection('users')
.doc(user.uid)
.get(); //get username
//create new message
FirebaseFirestore.instance.collection('chat').add(
//no authentication token required
{
'text': _enterMessage,
'createdAt':
Timestamp.now(), //TimeStamp is from cloud firestore package\
'userId': user
.uid, //to seperate chat left and right , differentiate between sender and receiver
'username': userData[
'username'], //the message now fetched will already have usernmae
'userImage': userData['image_url'], //access to url
'tokenId': userData['tokenId'],
}, //createdAT to sort the messages in order
);
_controller.clear(); //clear text field
sendNotification(userData["tokenId"], _enterMessage,
"Testing a message");
}
}
The error is on sendNotification(userData["tokenId"], _enterMessage, The data with the tokenId is added correctly in 'chat' collection of firebase. I just can't figure out to use onesignal sendNotification
tokenIdList is list of strings are id as number?
For a simple fix just removed theon List from on List<String>

How to sign up and in with OAuth credentials in firebase and flutter?

I was reading in the firebase Auth Rest Api and found this OAuth Credentials that contains a lot of information about a user that signs in including if the email is verified, So I tried to do it in my flutter app but looks like I am missing sth called Request URI I am new to flutter and firebase so I need your help.
My code:
static Future signin(String email, String password) async {
try {
http.Response response = await http.post(
'https://identitytoolkit.googleapis.com/v1/accounts:signInWithIdp?key=AIzaSyD3KOx9KSfK1lhyWRCt4_-dXLkKDNq-0hU',
body: {
'email': email,
'password': password,
'requestUri': ?? 'Sth of Type String',
},
);
if (response.statusCode == 200) {
print(response.statusCode);
print(json.decode(response.body));
} else {
print(response.statusCode);
}
String jsonsDataString = response.body.toString();
var _data = jsonDecode(jsonsDataString);
print(_data.toString());
print({email, password});
if (response.body.contains('EMAIL_EXISTS')) {
print('email exists');
} else if (response.body.contains('WEAK_PASSWORD')) {
print('weak password');
}
} catch (e) {
print(e);
}
}
Your are using the API for signing in with via oAuth and the requestUri ist the redirect URL of the auth flow.
Check this link: https://www.oauth.com/oauth2-servers/redirect-uris/
What you could do is use the sign-in with email api instead.
Check https://firebase.google.com/docs/reference/rest/auth and search sign in with email / passwort.

Flutter : Edit profile returns 401 'Unauthenticated' but works in POSTMAN

i was trying to edit my user's profile with flutter and laravel based on this tutorial . My register and login works fine. However, when i try to edit it always return this error.
Here are some of my codes;
api.dart
class CallApi {
final String _url = 'http://10.0.2.2:8000/api/';
var token ;
postData(data, apiUrl) async {
var fullUrl = _url + apiUrl + await _getToken();
print(fullUrl);
return await http.post(
fullUrl,
body: jsonEncode(data),
headers: _setHeaders());
}
editData(data, apiUrl) async {
var fullUrl = _url + apiUrl + await _getToken();
return await http.post(
fullUrl,
body: jsonEncode(data),
headers: _setTokenHeaders())
.then((response) {
print('Response status : ${response.statusCode}');
print('Response body : ${response.body}');
});
}
getData(apiUrl) async {
var fullUrl = _url + apiUrl + await _getToken();
return await http.get(fullUrl, headers: _setHeaders());
}
_setHeaders() => {
'Content-type': 'application/json',
'Accept': 'application/json',
};
_getToken() async {
SharedPreferences localStorage = await SharedPreferences.getInstance();
var token = localStorage.getString('token');
return '?token=$token';
}
_setTokenHeaders() =>
{
'Content-type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer $_getToken()',
};
}
Handle update function
void _handleUpdate() async {
setState(() {
_isLoading = true;
});
var data = {
'residency': locationController.text,
'spouse': spouseController.text,
'occupation': occupationController.text,
};
var res = await CallApi().postData(data, 'profile');
// i've tried both postData and editData which returns the same error
var body = json.decode(res.body);
print(body);
/*if (body['status'] == true) {
SharedPreferences localStorage = await SharedPreferences.getInstance();
localStorage.setString('user_details', json.encode(body['token']));
Navigator.of(context).pushNamed(Profile.tag);
}*/
}
Logcat
I/flutter ( 2390): {message: Unauthenticated.}
The api works properly through postman and i have checked the url and parameters which i am entering in the post request and they are the same as that of postman but still i keep getting the error.
Whats working on POSTMAN
Register
Login
Logout
Update
On flutter App
Register
Login
You should only return the token only. No need to return string query.
_getToken() async {
...
return token;
};
Also, remove the _getToken() from your fullUrl variable. You need to send the token by headers, not by query parameters.
EDITED
Your postData() function should be using _setTokenHeaders() in the headers instead.

Flutter - async function returns null

I've been working on this off and on for a couple of days now, and even after searching, and digging, haven't figured it out.
Here are the two relevant pieces of code:
Future<FirebaseUser> signUp(String email, String password, String username) async {
FirebaseUser user = await _firebaseAuth.createUserWithEmailAndPassword(
email: email, password: password).then((newUser) {
var obj = {
"active": true,
"public": true,
"email": email,
"username":username
};
_profileRef.child(newUser.uid).set(obj).then((_) {
print("inside");
//print("new userId: ${newUser}");
//return newUser;
});
});
//print("outside");
return user;
}
And:
Future<void> register() async {
final formState = _formKey.currentState;
if(formState.validate()) {
formState.save();
try {
//print("email: " + _email + ", pwd: " + _password);
//FirebaseUser user = await FirebaseAuth.instance.signInWithEmailAndPassword(email: _email,password: _password);
//String uid = await widget.auth.signIn(_email, _password);
FirebaseUser user = await widget.auth.signUp(_email, _password, _username);
print("uid: " + user.uid);
Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => HomePage(auth: widget.auth, userId: user.uid, onSignedOut: widget.onSignedIn,)));
//Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => HomePage(auth: widget.auth, userId: uid, onSignedOut: widget.onSignedIn,)));
} catch(e) {
print(e);
}
}
}
The signUp() function works properly, and correctly creates the user in Firebase, along with the userProfile entry in the Firebase realtime database. However, for whatever reason, I'm never able to get the actual FirebaseUser object back in the register() function. It always returns an error like the below:
Connected Path: satisfied (Path is satisfied), interface: en0
Duration: 1.315s, DNS #0.001s took 0.004s, TCP #0.007s took 0.053s, TLS took 0.158s
bytes in/out: 5745/975, packets in/out: 9/9, rtt: 0.051s, retransmitted packets: 0, out-of-order packets: 0
[C3.1 8282B933-6D0B-4103-937C-173268FD0304 192.168.1.7:54700<->172.217.14.106:443]
Connected Path: satisfied (Path is satisfied), interface: en0
Duration: 0.441s, DNS #0.000s took 0.003s, TCP #0.005s took 0.054s, TLS took 0.152s
bytes in/out: 5040/1812, packets in/out: 9/9, rtt: 0.052s, retransmitted packets: 0, out-of-order packets: 0
flutter: NoSuchMethodError: The getter 'uid' was called on null.
Receiver: null
Tried calling: uid
flutter: inside
It's generally confusing to combine the use of await with then. Refactor your signUp method to remove the then.
Future<FirebaseUser> signUp(String email, String password, String username) async {
FirebaseUser user = await _firebaseAuth.createUserWithEmailAndPassword(
email: email, password: password);
var obj = {
"active": true,
"public": true,
"email": email,
"username": username,
};
await _profileRef.child(user.uid).set(obj);
return user;
}
The problem is that chaining .then kind of "overrides" the previous promise's return type.
This function returns a Future<FirebaseUser> by itself:
_firebaseAuth.createUserWithEmailAndPassword(...);
However you have a .then chain that returns nothing which is why no value is assigned to the final result of the Future and it remains null:
.then((newUser) {
var obj = {
"active": true,
"public": true,
"email": email,
"username":username
};
_profileRef.child(newUser.uid).set(obj).then((_) {
print("inside");
};
// Need to return newUser here.
};
You can either add a return newUser;:
_profileRef.child(newUser.uid).set(obj).then((_) {
print("inside");
};
return newUser;
or follow Richard's answer which gets rid of .then altogether and use await only instead which make your code look cleaner and easier to read especially when there is async chaining.

Resources