2017-04-24 22 views
1

RESTユーザーログインをReact Native with Wordpressにコーディングする方法に関する便利なコードスニペットやドキュメントを見つけるのに困っています。React Nativeを使用してWordpressでユーザーにログインする方法

これを達成するのに役立つ何か、最も簡単な方法はありますか?

+0

こんにちはユルゲン・ガンズ同じ質問ここで

あなたはlogoutメソッドを実装する方法をです。これを解決しましたか? –

+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> 
    ) 
} 

は、その後、フォームに提出した資格情報が正しい場合は、データは、資格情報が正しいと間違った場合は、エラーをスローした場合、我々はチェックワードプレスのAPIサーバーにPOSTされます - 私たちはただの組み合わせであるトークンを生成します文字列と数字の組み合わせ(あなたの選択)。このトークンはwp_usermetaテーブルに格納されます。これにより、ユーザーがモバイルアプリにアクセスするたびにチェックを行うことができます。今、我々が持っているように、

<?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'; 
      } 
     } 
    } 
} 

お気に入りのFTPプログラムを経由してサーバーにログインして、ワードプレスのルートディレクトリ、「authentication.php」と呼ばれるPHPファイルを作成し、次のコードを追加しますトークンを受け取ったら、応答としてモバイルアプリに戻します。私たちのモバイルアプリケーションは、AsyncStorageを介してモバイルデバイスストレージにトークン(およびその他の必要なデータ)を受信して​​格納できるようになります。このように、モバイルアプリケーションを開くたびにアプリケーションはストレージをチェックします現在ログインしているユーザー(Persistent Login)があります。

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/

関連する問題