2017-04-24 52 views
1

我有麻煩找到任何有用的代碼片段或關於如何使用React Native編寫REST用戶登錄到Wordpress的文檔。如何用戶使用React Native以Wordpress登錄

任何事情,這可以幫助我實現這一點,最簡單的方法?

+0

喜于爾根的gunz同樣的問題。你解決了這個問題嗎? –

+0

我會很快做出一個教程。 – Carl

回答

1

在您的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表中,這樣,每次用戶訪問您的移動應用程序時都可以執行檢查。通過你喜歡的FTP程序

登錄到服務器,然後WordPress的根目錄下,創建一個名爲PHP文件「authentication.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/

相關問題