React native: How to validate username and password while submitting - validation

I have validate username and password,if username and password is wrong ,then i want through error like 'Invalid username/password'.if any one know,pls let me know.
async submit() {
//Validating username and password
const { username, password } = this.state;
if(username == ''){
this.setState({error:'Username is required'});
} else if(password == ''){
this.setState({error:'Password is required'});
} else {
this.setState({error: null})
let collection={};
collection.username=this.state.username;
collection.password=this.state.password;
// console.warn(collection);
var url = 'my url';
try {
let response = await fetch(url,
{
method: 'POST', // or 'PUT'
body: JSON.stringify(collection), // data can be `string` or {object}!
headers: new Headers({
'Content-Type': 'application/json'
})
});
let res = await response.text();
// console.warn(res);
if (response.status >= 200 && response.status < 300) {
//Handle success
let accessToken = res;
console.log(accessToken);
//On success we will store the access_token in the AsyncStorage
this.storeToken(accessToken);
// console.warn(accessToken);
//After storing value,it will navigate to home
this.props.navigation.navigate('Home');
} else {
//Handle error
console.log('Success:',response);
let error = res;
throw error;
}
} catch(error) {
console.log("error " + error);
}
}
}
response after giving invalid username/password:
0 {…}
field :password
message :Incorrect username or password.

I have written code like this based on status to validated username/password is correct/wrong.so here am posting code if it is useful for anyone in future.below code is,
if (response.status >= 200 && response.status < 300) {
//Handle success
let accessToken = res;
//On success we will store the access_token in the AsyncStorage
this.storeToken(accessToken);
console.warn(accessToken);
//After storing value,it will navigate to home
this.props.navigation.navigate('Home');
} else {
console.log('Success:',response);
this.setState({error:'Invalid username/password'});
let error = res;
throw error;
}

Related

Can't get data when 400 error. in Flutter

I'm trying to implement login with the Dio package in my app. When I send the correct email and password I get a 200 status code and user data. But when I send the email or password incorrect backend sends 400 error code and data like this {"message": "User Not Exist","data": [],"status": false} the problem is I'm unable to get the data when I have 400 error because in dio catchError method I can get just error and stacktrace.
Future login(String username, String password) async {
try {
String url = "$baseUrl/admin/user/login";
print(url);
var res = await dio.post(
url,
data: {"email": username, "password": password},
);
if (res.statusCode == 400) {
print(res.data); <----- This dont print anything.
return false;
} else {
print(res.data);
return true;
}
// await Future.delayed(Duration(seconds: 4));
} catch (e, s) {<----- here I have just error and stacktrace not the data
print("stacktrace $s");
print("error $e");
}
}
I solved this issue using on DioError catch instead of the catch method.
Future login(String username, String password) async {
try {
String url = "$baseUrl/admin/user/login";
print(url);
var res = await dio.post(
url,
data: {"email": username, "password": password},
);
if (res.statusCode == 400) {
print(res.data); <----- This dont print anything.
return false;
} else {
print(res.data);
return true;
}
// await Future.delayed(Duration(seconds: 4));
} on DioError catch (e) {
print(e.response.data);<-----------here I can get the data
return e.response.data;
}
}
Take try..catch out and use this form:
dio.post(...).then((response) {...}).catch(...)
Then you can use response as you wish.
You can read this article

react-native fetch with authorization header sometime return 401

I'm facing some issue whereby I sometime will get status code 401 (Unauthorised) from my phone. I'm trying to access to an API from my computer localhost (192.168.0.7).
I've a screen, when I click on a button it will navigate to a page and it will request data through API. And when I go back and navigate to same page again, it sometime will return me code 401.
So if I repeat the same step (navigate and go back) let's say 10 times. I'm getting Unauthorised like 5-7 times.
Below are my code
export function getMyCarpool(param,token) {
return dispatch => {
var requestUrl = _api + 'GetMyProduct?' + param;
fetch(requestUrl, {
method: "get",
headers: new Headers({
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Bearer ' + token
})
})
.then((request) => {
console.log(request);
if(request.status == 200)
return request.json();
else if(request.status == 401) {
//dispatch(logout());
throw new Error('Unauthorized access.');
}
else
throw new Error('Failed to request, please try again.');
})
.then((response) => {
var message = response.message;
if(response.success == 'true')
dispatch({ message, type: GET_MY_PRODUCT_SUCCESS });
else
dispatch({ message, type: GET_MY_PRODUCT_FAILED });
})
.catch(error => {
var message = error.message;
dispatch({ message, type: GET_MY_PRODUCT_FAILED });
});
}
I've check the token in my phone and also trying to make many request using postman. So I don't think it's server side problem.
I'm using Laravel and using laravel passport for API authentication. I not sure why this happen if I continue to access many time, any help is greatly appreciated.
UPDATE :: I'm trying to capture whether the http request has the token from this link, and I don't get the problem anymore.
It's a healthy mechanism for token expire. Maybe you have your token (access_token) for 5 minutes, then the token expired, you should use refresh_token to regain another new token (access_token).
For code explanation:
async function fetchService(url) {
const reqSetting = {
headers: {
Accept: 'application/json',
Authorization: `Bearer ${Auth.access_token}`,
},
};
const prevRequest = { url, reqSetting };
const resp = await fetch(url, reqSetting);
if (!resp.ok) {
const error = new Error(resp.statusText || 'Request Failed!');
if (resp.status === 401 || resp.status === 400) {
const responseClone = resp.clone();
const errorInfo = await resp.json();
if (errorInfo.error == 'invalid_token') {
// console.log('Token Expired', errorInfo);
try {
await refreshToken();
const response = await fetchService(prevRequest.url);
return response;
} catch (err) {
// handle why not refresh a new token
}
}
return responseClone;
}
error.errorUrl = url;
error.code = resp.status;
throw error;
}
return resp;
}
Where the refresh token function is :
async function refreshToken() {
const url = 'https://example.com/oauth/token';
const data = {
grant_type: 'refresh_token',
refresh_token: Auth.refresh_token,
};
try {
const res = await fetch(url, data);
const data = res.json();
Auth.access_token = data.access_token;
Auth.refresh_token = data.refresh_token;
return true;
} catch (error) {
throw error;
}
}
This fetchService will automatic regain a new token if old expired and then handle old request.
PS.
If you have multiple requests same time, the fetchService will need a little optimization. You'd better choose another regain token strategy like saga.

XMLHttpRequest 401 (Unauthorized)

I am trying to Create Post in user interface.
When I logged in as Admin and insert
createPost.setRequestHeader("X-WP-Nonce", magicalData.nonce);
to the below code, Create Post success. But I don't want to use nonce, I want use user and password, but I got this error: 401 (Unauthorized). I tried to replace btoa to Decode64 but it not work. Do I miss anything?
var createPost = new XMLHttpRequest();
createPost.open("POST", magicalData.siteURL + "/wp-json/wp/v2/posts", true);
createPost.withCredentials = true;
createPost.setRequestHeader("Authorization", "Basic " + btoa("username:password"));
createPost.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
createPost.send(JSON.stringify(ourPostData));
createPost.onreadystatechange = function() {
if (createPost.readyState == 4) {
if (createPost.status == 201) {
document.querySelector('.admin-quick-add [name="title"]').value = '';
document.querySelector('.admin-quick-add [name="content"]').value = '';
} else {
alert("Error - try again.");
}
}
}

Retrieving of Restful web service values in android for Titanium

We are using the same restful web service code from serviceutility.js for both android and ios. But the service is getting hit and values are retrieved only in ios. The same code is not working in android and we are getting the following error:
[ERROR] : TiExceptionHandler: (main) [2,821093] - In alloy/controllers/home.js:25,32
[ERROR] : TiExceptionHandler: (main) [0,821093] - Message: Uncaught TypeError: Cannot read property 'status' of null
[ERROR] : TiExceptionHandler: (main) [0,821093] - Source: if ("1" == response.status) alert(response.message); else if ("0"
[ERROR] : V8Exception: Exception occurred at alloy/controllers/home.js:25: Uncaught TypeError: Cannot read property 'status' of null.
Titanium SDK is 5.1.2 GA
exports.login = function(user, cb) {
var response = null;
if (Ti.Network.online) {
var xhr = Ti.Network.createHTTPClient({
timeout : 10000,
validatesSecureCertificate : false
});
xhr.onload = function() {// Onload
var responseTxt = this.responseText == '' ? '{}' : this.responseText;
try {
response = JSON.parse(responseTxt);
cb(response, 'SUCCESS');
} catch(e) {
cb(response, 'ERROR');
}
};
xhr.onerror = function(e) {
if (xhr.status === 0) {
cb(response, 'TIMEDOUT');
} else {
cb(response, 'ERROR');
}
};
url = "https://";
var postData = {
employeeId : user.employeeId,
password : user.password
};
xhr.open('POST', url);
xhr.setTimeout(10000);
xhr.setRequestHeader('employeeId', user.employeeId);
xhr.setRequestHeader('password', user.password);
xhr.send();} else {
cb(response, 'NO_NETWORK');
}};
The below code is for index.js file where the actual retrieval of values happen.
if (Ti.Network.online) {
loginUtil.login(user, function(response, status) {
Ti.API.info("status----" + status);
if (response.status == "0") {
Ti.API.info("status== " + response.status);
Ti.App.role = response.role;
Alloy.createController('home', {employeeId:$.userTextField.value,password:$.passwordTextField.value,from:"index"}).getView().open();
} else if (response.status == '1') {
alert(response.message);
} else {
alert("Please enter the correct credentials");
}
});
}
Please help us on this.
Looks like you are ONLY returning a string value instead of the entire response object. Then in your controller you attempt to access the .status property of the response object.
//this line returns the string responseTxt
response = JSON.parse(responseTxt);
Try returning the entire response object instead.
response = JSON.parse(this);
Then in your index.js controller use/ display the status property
alert(response.status);
Your index.js expected response to be an object, but that is only the case where you call callback like this:
response = JSON.parse(responseTxt);
cb(response, 'SUCCESS');
All other places where you call callback the response variable is null, since that is what you initialise it with on the second line.
Your callback returns two parameters, response & status, the second param is never used.
From reading the login function code, you only get to access the response object if status == "SUCCESS"
if(status === "SUCCESS"){
if (response.status == "0") {
Ti.API.info("status== " + response.status);
Ti.App.role = response.role;
Alloy.createController('home', {employeeId:$.userTextField.value,password:$.passwordTextField.value,from:"index"}).getView().open();
} else if (response.status == '1') {
alert(response.message);
} else {
alert("Please enter the correct credentials");
}
}
else {
alert("whoops, please try again !"); // a more generic message.
}

Return user id along with Ajax Success response

I have Ajax login submit that works just fine. Now i need to send the $user_id back to the login page on success. But cant figure out how.
Below is what i have.
This is the php page
<?
if (!securePage($_SERVER['PHP_SELF'])){die();}
//Prevent the user visiting the logged in page if he/she is already logged in
if(isUserLoggedIn()) { header("Location: account.php"); die(); }
//Forms posted
if(!empty($_POST))
{
$errors = array();
$username = sanitize(trim($_POST["user"]));
$password = trim($_POST["password"]);
//Perform some validation
//Feel free to edit / change as required
if($username == "")
{
$response['success'] = false;
}
if($password == "")
{
$response['success'] = false;
}
if(count($errors) == 0)
{
//A security note here, never tell the user which credential was incorrect
if(!usernameExists($username))
{
$response['success'] = false;
}
else
{
$userdetails = fetchUserDetails($username);
//See if the user's account is activated
if($userdetails["active"]==0)
{
$response['success'] = false;
}
else
{
//Hash the password and use the salt from the database to compare the password.
$entered_pass = generateHash($password,$userdetails["password"]);
if($entered_pass != $userdetails["password"])
{
//Again, we know the password is at fault here, but lets not give away the combination incase of someone bruteforcing
$response['success'] = false;
}
else
{
//Passwords match! we're good to go'
$response['success'] = true;
}
}
}
}
}
//$user_id = $loggedInUser->user_id;
echo json_encode($response);
?>
Here is the ajax that calls the php page. And also where i need to retrieve the ID from php page.
<script type="text/javascript">
//login ajax to send over user and pass LS
function handleLogin() {
var form = $("#loginForm");
//disable the button so we can't resubmit while we wait
$("#submitButton",form).attr("disabled","disabled");
var e = $("#user", form).val();
var p = $("#password", form).val();
console.log("click");
if(e != "" && p != "") {
var str = form.serialize();
//McDOn(str);
$.ajax({
type: 'POST',
url: 'http://vsag.actualizevps.com/loginmobile.php',
crossDomain: true,
data: {user: e, password :p},
dataType: 'json',
async: false,
success: function (response){
//alert ("response");
if (response.success) {
//alert("you're logged in");
window.localStorage["user"] = e;
//window.localStorage["password"] = md5(p);
//window.localStorage["UID"] = data.uid;
window.location = "create.html";
}
else {
alert("Your login failed");
//window.location("main.html");
location.reload();
}
},
error: function(error){
//alert(response.success);
alert('Could not connect to the database' + error);
window.location = "main.html";
}
});
}
else {
//if the email and password is empty
alert("You must enter user and password");
}
return false;
}
</script>
the $response value is just true or false at the moment, you could return an array:
$response = array("Success" => true, "UserId" => $user_id);
and on you AJAX response, the response variable
response.UserId
will contain the user id

Resources