如何使用 React Native 使用 Wordpress 用户登录
How to User Login With Wordpress using React Native
我很难找到有关如何使用 React Native 将 REST 用户登录编码到 Wordpress 的任何有用的代码片段或文档。
任何可以帮助我实现这一目标的最简单方法?
在 React Native 组件的 render() 方法中,创建一个包含用户名和密码输入字段的表单。
this.state = {
validating: false
}
render() {
return (
<Container>
<Content>
<Form>
<Item floatingLabel>
<Label>Email</Label>
<Input onChangeText={(text) => this.setState({email:text})} />
</Item>
<Item floatingLabel last>
<Label>Password</Label>
<Input secureTextEntry onChangeText={(text) => this.setState({password:text})} />
</Item>
<Button block success style={{ marginTop: 50 }} onPress={() => {
if( this.state.email && this.state.password ){
this.validate();
}
}} >
<Text>Authenticate</Text>
</Button>
</Form>
</Content>
</Container>
)
}
然后在表单提交时,数据被发布到 WordPress API 服务器,我们在服务器上检查凭据是否正确,如果不正确则抛出错误,如果凭据正确 - 我们生成一个令牌,它只是字符串和数字的组合(您的选择)。然后,此令牌将存储在 wp_usermeta table 中,这样您就可以在每次用户访问您的移动应用程序时进行检查。
通过你最喜欢的FTP程序登录到你的服务器,然后到WordPress的根目录,创建一个名为“authentication.php”的PHP文件,然后添加以下代码:
<?php
require_once('wp-load.php');
$response = array(
'data' => array(),
'msg' => 'Invalid email or password',
'status' => false
);
/* Sanitize all received posts */
foreach($_POST as $k => $value){
$_POST[$k] = sanitize_text_field($value);
}
/**
* Login Method
*
*/
if( isset( $_POST['type'] ) && $_POST['type'] == 'login' ){
/* Get user data */
$user = get_user_by( 'email', $_POST['email'] );
if ( $user ){
$password_check = wp_check_password( $_POST['password'], $user->user_pass, $user->ID );
if ( $password_check ){
/* Generate a unique auth token */
$token = MY_RANDOM_CODE_GENERATOR( 30 );
/* Store / Update auth token in the database */
if( update_user_meta( $user->ID, 'auth_token', $token ) ){
/* Return generated token and user ID*/
$response['status'] = true;
$response['data'] = array(
'auth_token' => $token,
'user_id' => $user->ID,
'user_login' => $user->user_login
);
$response['msg'] = 'Successfully Authenticated';
}
}
}
}
现在我们有了一个令牌,我们将它作为响应传回我们的移动应用程序。然后我们的移动应用程序应该能够通过 AsyncStorage 接收令牌(以及您想要的任何其他数据)并将其存储到我们的移动设备存储中,这样,每次用户打开您的移动应用程序时,我们的应用程序将只检查存储是否正确有一个当前登录的用户(持久登录)。
validate(){
this.setState({ validating: true });
let formData = new FormData();
formData.append('type', 'login');
formData.append('email', this.state.email);
formData.append('password', this.state.password);
return fetch('http://example.com/authentication.php', {
method: 'POST',
body: formData
})
.then((response) => response.json())
.then((responseJson) => {
let data = responseJson.data;
if (this.saveToStorage(data)){
this.setState({
validating: false
});
/* Redirect to accounts page */
Actions.pageAccount();
} else {
console.log('Failed to store auth');
}
})
.catch((error) => {
console.error(error);
});
}
saveToStorage() 方法:
async saveToStorage(userData){
if (userData) {
await AsyncStorage.setItem('user', JSON.stringify({
isLoggedIn: true,
authToken: userData.auth_token,
id: userData.user_id,
name: userData.user_login
})
);
return true;
}
return false;
}
然后我们可以提供一个注销按钮,基本上清除存储并通知服务器清除与当前登录用户关联的令牌。
以下是您将如何实现注销方法:
async logout(){
await AsyncStorage.removeItem('user');
// Add a method that will delete user_meta token of the user from the server.
// await deleteUserMetaToken(PARAM_USER_ID);
/* Redirect to the login page */
Actions.pageLogin();
}
全文:http://carlofontanos.com/user-login-with-wordpress-using-react-native/
我很难找到有关如何使用 React Native 将 REST 用户登录编码到 Wordpress 的任何有用的代码片段或文档。
任何可以帮助我实现这一目标的最简单方法?
在 React Native 组件的 render() 方法中,创建一个包含用户名和密码输入字段的表单。
this.state = {
validating: false
}
render() {
return (
<Container>
<Content>
<Form>
<Item floatingLabel>
<Label>Email</Label>
<Input onChangeText={(text) => this.setState({email:text})} />
</Item>
<Item floatingLabel last>
<Label>Password</Label>
<Input secureTextEntry onChangeText={(text) => this.setState({password:text})} />
</Item>
<Button block success style={{ marginTop: 50 }} onPress={() => {
if( this.state.email && this.state.password ){
this.validate();
}
}} >
<Text>Authenticate</Text>
</Button>
</Form>
</Content>
</Container>
)
}
然后在表单提交时,数据被发布到 WordPress API 服务器,我们在服务器上检查凭据是否正确,如果不正确则抛出错误,如果凭据正确 - 我们生成一个令牌,它只是字符串和数字的组合(您的选择)。然后,此令牌将存储在 wp_usermeta table 中,这样您就可以在每次用户访问您的移动应用程序时进行检查。
通过你最喜欢的FTP程序登录到你的服务器,然后到WordPress的根目录,创建一个名为“authentication.php”的PHP文件,然后添加以下代码:
<?php
require_once('wp-load.php');
$response = array(
'data' => array(),
'msg' => 'Invalid email or password',
'status' => false
);
/* Sanitize all received posts */
foreach($_POST as $k => $value){
$_POST[$k] = sanitize_text_field($value);
}
/**
* Login Method
*
*/
if( isset( $_POST['type'] ) && $_POST['type'] == 'login' ){
/* Get user data */
$user = get_user_by( 'email', $_POST['email'] );
if ( $user ){
$password_check = wp_check_password( $_POST['password'], $user->user_pass, $user->ID );
if ( $password_check ){
/* Generate a unique auth token */
$token = MY_RANDOM_CODE_GENERATOR( 30 );
/* Store / Update auth token in the database */
if( update_user_meta( $user->ID, 'auth_token', $token ) ){
/* Return generated token and user ID*/
$response['status'] = true;
$response['data'] = array(
'auth_token' => $token,
'user_id' => $user->ID,
'user_login' => $user->user_login
);
$response['msg'] = 'Successfully Authenticated';
}
}
}
}
现在我们有了一个令牌,我们将它作为响应传回我们的移动应用程序。然后我们的移动应用程序应该能够通过 AsyncStorage 接收令牌(以及您想要的任何其他数据)并将其存储到我们的移动设备存储中,这样,每次用户打开您的移动应用程序时,我们的应用程序将只检查存储是否正确有一个当前登录的用户(持久登录)。
validate(){
this.setState({ validating: true });
let formData = new FormData();
formData.append('type', 'login');
formData.append('email', this.state.email);
formData.append('password', this.state.password);
return fetch('http://example.com/authentication.php', {
method: 'POST',
body: formData
})
.then((response) => response.json())
.then((responseJson) => {
let data = responseJson.data;
if (this.saveToStorage(data)){
this.setState({
validating: false
});
/* Redirect to accounts page */
Actions.pageAccount();
} else {
console.log('Failed to store auth');
}
})
.catch((error) => {
console.error(error);
});
}
saveToStorage() 方法:
async saveToStorage(userData){
if (userData) {
await AsyncStorage.setItem('user', JSON.stringify({
isLoggedIn: true,
authToken: userData.auth_token,
id: userData.user_id,
name: userData.user_login
})
);
return true;
}
return false;
}
然后我们可以提供一个注销按钮,基本上清除存储并通知服务器清除与当前登录用户关联的令牌。
以下是您将如何实现注销方法:
async logout(){
await AsyncStorage.removeItem('user');
// Add a method that will delete user_meta token of the user from the server.
// await deleteUserMetaToken(PARAM_USER_ID);
/* Redirect to the login page */
Actions.pageLogin();
}
全文:http://carlofontanos.com/user-login-with-wordpress-using-react-native/