What value should be passed with AsyncStorage? - php

I am currently a beginner of react native and I want to know if I wanted to login and store user data using AsyncStorage, what key and value should be passed?
AsyncStorage.setItem('key', 'value');
UserLogin = () =>{
const { username } = this.state ;
fetch('https://www.example.com/React/user-login.php', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
username: username,
})
}).then((response) => response.json())
.then((responseJson) => {
// If server response message same as Data Matched
if(responseJson === 'Data Matched')
{
login(username, password).then(authenticationToken => {
AsyncStorage.setItem('token', authenticationToken)
})
//Then open Profile activity and send user email to profile activity.
this.props.navigation.navigate('ProfileScreen', { username:username });
}
else{
Alert.alert(responseJson);
}
}).catch((error) => {
console.error(error);
});
}
If I were to say if logged in, then AsyncStorage.setItem('key', 'value');, then that could work if I want to store say the user's username so that I can display it on their profile page?

AsyncStorage parameters are both strings, so you can store serialised json data or just a plain string.
// Some code that logs someone in and gets an authentication token which then is stored
login(username, password).then(authenticationToken => {
AsyncStorage.setItem('token', authenticationToken)
})
// then somewhere else in your code
AsyncStorage.getItem('token').then(authenticationToken => {
console.log(‘the token’, authenticationToken)
})

Related

how to use php sessions and svelte together

I'm using php for my application backend. I created a authentication system with two loginUser.php and loginCheck.php
In loginUser.php when username and password is correct:
session_start();
session_regenerate_id();
$_SESSION['bookstore_username'] = $_POST['username'];
session_write_close();
$response = array('status' => true, 'message' => 'user successfully authorized.', 'data' => $row);
echo json_encode($response);
Then in loginCheck.php
session_start();
if (isset($_SESSION["bookstore_username"]) && $_SESSION["bookstore_username"] == $_POST['username']) {
$response = array('status' => true, 'message' => "user is logged in.");
echo json_encode($response);
} else {
$response = array('status' => false, 'message' => "user is not logged in.");
echo json_encode($response);
}
When i testing it in Postman Application everything is fine and response showed me user logged in but in svelte app after doing a user login when i check login stat response is always false and session is null.
const checkUserIsLoggedIn = async (): Promise<void> => {
const url = ORIGIN + "Backend/api/user/loginCheck.php";
let data = new FormData();
data.append("username", userInformationStore?.get().username);
const res = await fetch(url, {
method: "POST",
body: data,
});
let response = await res.json();
console.log(response);
};
Assuming the session relies on a cookie, the only explanation I see for the Session being null is that the session cookie is not being passed back to your back-end. By default, fetch only allows same-origin cookies. Try adding the following option to your fetch operation to allow cookies to be passed in cross-origin requests:
const res = await fetch(url, {
method: "POST",
body: data,
credentials: "include",
});
See this paragraph in the Fetch API documentation for details.

Passport/axios not post username password

I am trying to POST username, password of auth to Laravel/Passport but it always return null
axios.post('http://localhost:8000/api/login', {
withCredentials: true,
auth: {
email: 'agent#test.com',
password: 'qwerty!##$%^'
}
})
.then(res => {
console.log(res);
})
PassportController.php
public function login(){
if(Auth::attempt(['email' => request('email'), 'password' => request('password')])){
$user = Auth::user();
$success['token'] = $user->createToken('MyApp')-> accessToken;
return response()->json(['success' => $success], $this-> successStatus);
}
else{
return response()->json(['email'=>request('email')], 401);
// I return email to see value
// return response()->json(['error'=>'Unauthorised'], 401);
}
}
api.php
Route::post('login', 'PassportController#login');
I checked everything many times, feel everything is ok, but for some reason data not send to passport.
conosle log:
POST http://localhost:8000/api/login 401 (Unauthorized)
{email: null}
email: null
Laravel is probably accessing the POST data's values with request. The axios.post method's second parameter is the object sent as POST data, so you probably meant to just pass the email and password as top-level keys:
axios
.post(
"http://localhost:8000/api/login",
{
email: "agent#test.com",
password: "qwerty!##$%^"
},
{ withCredentials: true }
)
.then(res => {
console.log(res);
});
I suspect that you may be mixing up authentication in general with HTTP ("Basic") Authentication. The auth key is part of the config object that you can pass as a third parameter to axios.post, which would control just that. I do not think this is what you are after, but just adding it here for completeness. Note that basic auth accepts an username and a password:
axios
.post("http://localhost:8000/api/login", {}, {
withCredentials: true,
auth: {
username: "agent#test.com",
password: "qwerty!##$%^"
}
})
.then(res => {
console.log(res);
});
Finally I solved my issue, the problem is no need to send credentials and auth via axios because from back-end laravel accept post data not auth data, so I passed email and password via form-data not auth:
axios.post("http://localhost:8000/api/login", {
email: "agent#test.com",
password: "qwerty!##$%^"
})
.then(res => {
console.log(res);
});
Now I got token in back-end.

PHP Webhost Operation Checking

I wanted perform checking if the PHP Webhost is complete whenever perform a update function, if everything doing fine then send an notification and let the Application know the Operation is Doing fine.
Basically I wanted to know if the query in PHP work and use my application to notify the user.
is there any way or method to do so?
I using this method to fetch data from PHP in my React Native App
RecipeUpdation = () =>{
const { ID } = this.state ;
const { Name } = this.state ;
const { Type } = this.state ;
const { Ingredient } = this.state ;
const { Step } = this.state ;
return fetch('https://www.update.php', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
RecipeID : ID,
RecipeName : Name,
RecipeType : Type,
RecipeIngredient: Ingredient,
RecipeStep: Step
})
}).then((response) => response.json())
.then((responseJson) => {
}).catch((error) => {
console.error(error);
});
}
Basically we can verify if the Operation in PHP is successful or not by Checking the Query Execution Status. A very Basic way to do the checking is using If Else to see if the Query Function return True(Success) or False(Fail). You can also always return some Message through JsonResponds.
Here some example Code for PHP checking and Return Some Message:
// Using If Else to Check if operation Success or Not
if(mysqli_query($connection,$Your_Query)){
$MSG = 'Success' ;
// Convert message into Json format first
$json = json_encode($MSG);
// This is where it return the message to Application.
echo $json ;
}
else{
$MSG = 'Failed' ;
$json = json_encode($MSG);
echo $json ;
}
In your Application Code you already have the implementation to retrieve the JsonResponds(the Message) which have been echo in the PHP Code, I would suggest use a simple method which is Alert to pop out the message in your React Native Application to notify the User the Operation Status.
}).then((response) => response.json())
.then((responseJson) => {
// this responseJson Already have the echo Message from PHP
// just Display the Status with Alert Function
Alert.alert(responseJson);
}).catch((error) => {
console.error(error);
});
Hope this would help.

Error handling in ionic2/ Angular2

Trying to integrate APIs built in Laravel 5.4 with ionic 2 and struggling handle the error
What I want to do:
Authenticate the login using Laravel Password service ( OAuth2 ).
Once authenticated, it would return the access token.
Access Token is passed in the header in a GET API call to receive the
user details.
I am able to #1 and #2 but got stuck at #3.
Here is my code of login.ts
public login() {
this.showLoading();
this.auth.login(this.loginCredentials).subscribe(allowed => {
if (allowed) {
setTimeout(() => {
this.loading.dismiss();
this.nav.setRoot(HelloIonicPage)
});
} else {
this.showError("Access Denied");
}
},
error => {
this.showError(error);
});
}
auth is a service provider, that has login method.
//Function to get access token
public login(credentials) {
if (credentials.email === null || credentials.password === null) {
return Observable.throw("Please insert credentials");
} else {
return Observable.create(observer => {
var link = 'http://localhost/XXX/public/oauth/token';
var vars = {
password: "XXX",
username: "XXXXXX",
grant_type: 'password',
client_id: "XXXXX",
client_secret: 'XXXXXX',
scope: ''
}
this.http.post(link, vars)
.map(res => res.json())
.subscribe(
data => { let user = this.getUserFromAccessToken(data);
console.log(user);
observer.next(user);
},
err => { observer.error(err.json()); }
() => {
console.log('Completed..');
}
);
});
}
}
//Function to get user from the accessToken
private getUserFromAccessToken(oAuthData) {
let headers = new Headers({ 'Content-Type': 'application/json','Accept': 'application/json','Authorization': 'Bearer ' + oAuthData.access_token });
let options = new RequestOptions({ headers: headers });
let link = 'http://localhost/XXXX/public/api/v1/user';
return this.http.get(link, options)
.map(res => res.json())
.subscribe(
data => this.currentUser = data.user,
err => this.error = err
);
}
currentUser and error are defined as properties of the AuthService class.
How should I ensure that an error is thrown either in case the access token is not returned or user is not returned from the access token.

how to use JSON data Coming from PHP file in Angular2?

export class LoginComponent
{
getdata : string;
public data;
username : any ;
password : any ;
constructor(private http: Http){}
login() {
var headers= new Headers({'Content-Type' : 'application/x-www-form-urlencoded '});
var body = JSON.stringify({
user : this.username,
pwd : this.password,
})
this.http.post('.../pos_system/Widgets/Login.php',body, {
headers:headers; })
.map(res => res.json())
.map(res => {
if(res.success)
{
this.msg="Login Complete";
}
else{
this.msg1="username and password is wrong";
}
})
.subscribe(
data =>this.getdata = JSON.stringify(data),
err => console.error(err),
() => console.log('done'));
}
}
This is my Angular2 part here i m getting JSON data from php file in res.Now I want to use this response in my angualr2 part.I want to use display username of the user which is in json data.so how to do that in angular2?
it's simple just make this change,
for Example
this.msg=res.username;
this will display username in message.
note: you need to do this in php file.
$data=array();
$df=json_decode(file_get_contents("php://input"));
$nam=$df->user;
$pws=$df->pwd;
$select=mysql_query("SELECT * FROM userData WHERE username='$nam' AND password='$pws'")or mysql_error();
$sql=mysql_num_rows($select);
if($sql>0)
{
while($row=mysql_fetch_array($select))
{
$data['success']=true;
$user=$row['username'];
$data['username']=$user;
}
}
echo json_encode($data);

Categories