Search code examples
restapireact-nativetoken

How to get data just access_token at react native rest api after login and show at cases


So, I want to display the access token obtained from the user when logging in from Cases.js ... But I have tried several ways to display it, but still not just the access_token ... But carried away with others ...

Maybe someone can help to solve this problem .. thank you

The thing that I have tried is to retrieve the value of the existing token and access token, but still the appearance of all the data such as "access_token", "bearer", "scope", "refresh_token" ... not only access_token ...

This is Form.js

import React, { Component } from 'react';
import { Text, View, StyleSheet, TextInput, TouchableOpacity, AsyncStorage, Animated, ImageBackground} from 'react-native';
import { Actions } from 'react-native-router-flux';

const ACCESS_TOKEN = 'access_token';

export default class Form extends Component {

    constructor(){
      super()

      this.state ={
        darikiri                : new Animated.Value(0),
        darikanan               : new Animated.Value(0),
        daribawah               : new Animated.Value(0),
        grant_type              : "password",
        scope                   : "",
        client_id               : "",
        client_secret           : "",
        username                : "",
        password                : "",
        error                   : "",
      }
    }

    async storeToken(accessToken){
      try{
        await AsyncStorage.setItem(ACCESS_TOKEN, accessToken);
        this.getToken();
      }catch (error){
        console.log("something where wrong")
      }
    }

    async getToken(){
      try{
        let token =  await AsyncStorage.getItem(ACCESS_TOKEN);
        console.log("token is : "+ token)
      }catch (error){
        console.log("something where wrong")
      }
    }

    async removeToken(){
      try {
        let token = await AsyncStorage.removeItem(ACCESS_TOKEN);
        this.getToken();
      } catch(error){
        console.log("Something went wrong")
      }
    }

    _start = () => {
      return Animated.parallel([
        Animated.timing(this.state.darikiri, {
          toValue: 1,
          duration: 800,
          useNativeDriver: true
        }),
        Animated.timing(this.state.darikanan, {
          toValue: 1,
          duration: 800,
          useNativeDriver: true
        }),
        Animated.timing(this.state.daribawah, {
          toValue: 1,
          duration: 800,
          useNativeDriver: true
        })
      ]).start();
    };

    async onLoginPressed(){
      try {
        let response = await fetch('https://bpm.asihputera.or.id/asihputera/oauth2/token', {
          method: 'POST',
          headers: {
            'Content-Type'        : 'application/json',
            'Accept-Encoding'     : 'gzip, deflate',
            'Authorization'       : 'Bearer cde4e4bc600afcb604fb2ba078c60a16e29dac04',
            'User-Agent'          : 'PostmanRuntime/7.15.2',
            'Accept'              : '*/*',
            'Cache-Control'       : 'no-cache',
            'Postman-Token'       : 'ad9e715b-a2af-4f3f-86dd-11a7b6ec6037,f00ce420-e144-47ec-be83-756ec1fbc5d2',
            'Host'                : 'bpm.asihputera.or.id',
            'Cookie'              : 'PM-TabPrimary=101010010; singleSignOn=0',
            'Content-Length'      : '139',
            'Connection'          : 'keep-alive',
            'cache-control'       : 'no-cache',
          },
          body: JSON.stringify({
            'grant_type'          : "password",
            'scope'               : '*',
            'client_id'           : 'QKQYKIBJUXFRMGITBPKXVBWOVMFYPWWF',
            'client_secret'       : '2922119675d440616c9a613026663027',
            'username'            : this.state.username,
            'password'            : this.state.password,
          }),
        });

        let res = await response.text();
        if (response.status >= 200 && response.status <=300) {
          this.setState({error:""});
          let accessToken = res;
          this.storeToken(accessToken);
          let token =  await AsyncStorage.getItem(ACCESS_TOKEN);
          console.log("res token: "+accessToken);
          Actions.Cases({"userName" :this.state.username ,"Password":  this.state.password, "Token" : accessToken.access_token})
        } else {
          let error = res;
          throw error;
        }
      } catch(error){
        this.removeToken();
        this.setState({error: error});
        console.log("error" + error);
      }

    }

    render(){
        return(
            <View onLayout={this._start} style={styles.container}>
              <Animated.View
                style={{
                  transform: [
                    {
                      translateX: this.state.darikiri.interpolate({
                        inputRange: [0, 1],
                        outputRange: [-900, 0]
                      })
                    }
                  ],
                }}
                >
                <TextInput style={styles.inputBox} 
                    editable={true}
                    onChangeText = {(username)=> this.setState({username})}
                    underlineColorAndroid='rgba(0,0,0,0)' 
                    placeholder="Username" 
                    ref='username'
                    returnKeyType='next'  
                    value={this.state.username}
                    placeholderTextColor="#ffffff"
                    selectionColor="#fff"/>
                </Animated.View>
                <Animated.View
                  style={{
                    transform: [
                      {
                        translateX: this.state.darikanan.interpolate({
                          inputRange: [0, 1],
                          outputRange: [900, 0]
                        })
                      }
                    ],
                  }}
                  >
                <TextInput style={styles.inputBox} 
                    editable={true}
                    onChangeText={(password) => this.setState({password})}
                    underlineColorAndroid='rgba(0,0,0,0)'
                    placeholder='Password'
                    ref='password'
                    returnKeyType='next'
                    secureTextEntry={true}
                    value={this.state.password}
                    placeholderTextColor="#ffffff"
                    selectionColor="#fff"/>
                </Animated.View>
                <Animated.View
                style={{
                    transform: [
                    {
                        translateY: this.state.daribawah.interpolate({
                        inputRange: [0, 1],
                        outputRange: [900, 0]
                        })
                    }
                    ],
                }}
                >
                <TouchableOpacity style={styles.button} onPress={this.onLoginPressed.bind(this)}>
                    <Text style={styles.buttonText}> Log In </Text>
                </TouchableOpacity>
                </Animated.View>
                <Text>
                  {this.state.error} 
                </Text>
            </View> 
            )
    }

}

const styles = StyleSheet.create({
    container :{
        flexGrow:1,
        justifyContent:'center',
        alignItems:'center',
    },

    inputBox: {
        width: 300,
        backgroundColor:'#C0C0C0',
        borderRadius: 25,
        paddingHorizontal: 16,
        fontSize :14,
        color: '#ffffff',
        marginVertical: 13
    },

    buttonText: {
        fontSize : 16,
        fontWeight : '500',
        color: '#ffffff',
        textAlign:'center'
    },

    button: {
        width:100,
        backgroundColor: '#C0C0C0',
        borderRadius: 40,
        marginVertical: 30,
        paddingVertical: 13
    }
});

This is Cases.js

import React, {Component} from 'react';
import {Alert, Image, Text, TouchableOpacity, View, StyleSheet, ScrollView, AsyncStorage, Animated} from 'react-native';
import {Actions} from 'react-native-router-flux';
import {Fonts} from '../utils/Fonts';
import Wallpaper from '../components/Wallpaper';


const ACCESS_TOKEN = 'access_token';

export default class Cases extends Component {
  async storeToken(accessToken){
    try{
      await AsyncStorage.setItem(ACCESS_TOKEN, accessToken);
      this.getToken();
    }catch (error){
      console.log("something where wrong")
    }
  }

  async getToken(){
    try{
      let token =  await AsyncStorage.getItem(ACCESS_TOKEN);
      console.log("token is : "+ token)
    }catch (error){
      console.log("something where wrong")
    }
  }

  async removeToken(){
    try {
      let token = await AsyncStorage.removeItem(ACCESS_TOKEN);
      this.getToken();
    } catch(error){
      console.log("Something went wrong")
    }
  }

  constructor(props){
    super(props)

    this.state ={
      accessToken   : this.props.Token,
      user          : this.props.userName,
      role          : "",
      ready         : false,
      ygdarikiri    : new Animated.Value(0),
      ygdarikanan   : new Animated.Value(0),
    }
  }

  userLogout() {
    Actions.login();
  }

  /*async getRole(){
    try {
      let response = await fetch('https://bpm.asihputera.or.id/api/1.0/users/', {
        method: 'GET',
        headers: {
          'Content-Type'        : 'application/json',
          'Accept-Encoding'     : 'gzip, deflate',
          'Authorization'       : 'Bearer '+ this.state.accessToken,

        },
        body: JSON.stringify({
          'grant_type'          : "password",
          'scope'               : '*',
          'client_id'           : 'QKQYKIBJUXFRMGITBPKXVBWOVMFYPWWF',
          'client_secret'       : '2922119675d440616c9a613026663027',
          'username'            : this.state.username,
          'password'            : this.state.password,
        }),
      });

      let res = await response.text();
      if (response.status >= 200 && response.status <=300) {
        this.setState({error:""});
        let accessToken = res;
        this.storeToken(accessToken);
        this.getToken();
        console.log("res token: "+accessToken);
        Actions.Cases({"userName" :this.state.username ,"Password":  this.state.password})
      } else {
        let error = res;
        throw error;
      }
    } catch(error){
      this.removeToken();
      this.setState({error: error});
      console.log("error" + error);
    }

  }
  */

  _start = () => {
    return Animated.parallel([
      Animated.timing(this.state.ygdarikiri, {
        toValue: 1,
        duration: 800,
        useNativeDriver: true
      }),
      Animated.timing(this.state.ygdarikanan, {
        toValue: 1,
        duration: 800,
        useNativeDriver: true
      })
    ]).start();
  };

  render() {

    let {ygdarikanan, ygdarikiri} = this.state;
    return (
      <View style={styles.tampilan} onLayout={this._start}>
       <View style ={{flexDirection:'row'}}>
        <Text style={styles.textasih}>
            ASIH PUTERA
        </Text>
        <TouchableOpacity style={styles.button} onPress={this.userLogout}>
            <Text style={styles.buttonText}> Logout </Text>
        </TouchableOpacity>
        </View>
        <View style={styles.garis} />
        <Text style={styles.textwelcome}>Username    : {this.state.user}</Text>
        <Text style={styles.textwelcome}>Access_Token              : {this.state.Token}</Text>
        <View style={styles.garis} />
        <ScrollView>
        <View style={{flexDirection: 'row'}}>
        <Animated.View
          style={{
            transform: [
              {
                translateX: ygdarikiri.interpolate({
                  inputRange: [0, 1],
                  outputRange: [-900, 0]
                })
              }
            ],
            width: 180,
            height: 180,
            backgroundColor:'#bff5ff',
          }}
          >
          <TouchableOpacity style={styles.touchCases}>
              <Text style={styles.btnMenu}> CASES </Text>
          </TouchableOpacity>
          </Animated.View>
          <Animated.View
          style={{
            transform: [
              {
                translateX: ygdarikanan.interpolate({
                  inputRange: [0, 1],
                  outputRange: [900, 0]
                })
              }
            ],
            width: 180,
            height: 180,
          }}
          >
          <TouchableOpacity style={styles.touchInbox}>
              <Text style={styles.btnMenu}> INBOX </Text>
          </TouchableOpacity>
          </Animated.View>
        </View>
        <View style={{flex: 1, flexDirection: 'row'}}>
        <Animated.View
          style={{
            transform: [
              {
                translateX: ygdarikiri.interpolate({
                  inputRange: [0, 1],
                  outputRange: [-1800, 0]
                })
              }
            ],
            width: 180,
            height: 180,
            backgroundColor:'#bff5ff',
          }}
          >
          <TouchableOpacity style={styles.touchOutbox}>
              <Text style={styles.btnMenu}> OUTBOX </Text>
          </TouchableOpacity>
          </Animated.View>
          <Animated.View
          style={{
            transform: [
              {
                translateX: ygdarikanan.interpolate({
                  inputRange: [0, 1],
                  outputRange: [1800, 0]
                })
              }
            ],
            width: 180,
            height: 180,
            backgroundColor:'#bff5ff',
          }}
          >
          <TouchableOpacity style={styles.touchParticipated}>
              <Text style={styles.btnMenu}> PARTICIPATED </Text>
          </TouchableOpacity>
          </Animated.View>
        </View>
        <View style={{flex: 1, flexDirection: 'row'}}>
        <Animated.View
          style={{
            transform: [
              {
                translateX: ygdarikiri.interpolate({
                  inputRange: [0, 1],
                  outputRange: [-2700, 0]
                })
              }
            ],
            width: 180,
            height: 180,
            backgroundColor:'#bff5ff',
          }}
          >
          <TouchableOpacity style={styles.touchUnassigned}>
              <Text style={styles.btnMenu}> UNASSIGNED </Text>
          </TouchableOpacity>
          </Animated.View>
          <Animated.View
          style={{
            transform: [
              {
                translateX: ygdarikanan.interpolate({
                  inputRange: [0, 1],
                  outputRange: [2700, 0]
                })
              }
            ],
            width: 180,
            height: 180,
            backgroundColor:'#bff5ff',
          }}
          >
          <TouchableOpacity style={styles.touchPaused}>
              <Text style={styles.btnMenu}> PAUSED </Text>
          </TouchableOpacity>
          </Animated.View>
        </View>
        </ScrollView>
        <Text style={styles.textcpyr}>{'\u00A9'} ASIH PUTERA</Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
    container :{
        flexGrow:1,
        justifyContent:'center',
        alignItems:'center',
    },

    btnMenu:{
      textAlign: 'center',
      paddingTop: 70,
      fontFamily: Fonts.LexendExa,
      fontSize : 20,
      fontWeight: "bold",

    },

    touchCases:{
      width: 180,
      height: 180,
      backgroundColor:'#bff5ff',
    },

    touchInbox:{
      width: 180,
      height: 180,
      backgroundColor:'#6bffc2',
    },

    touchOutbox:{
      width: 180,
      height: 180,
      backgroundColor:'#83c3ff',
    },

    touchParticipated:{
      width: 180,
      height: 180,
      backgroundColor:'#70ff8a',
    },

    touchUnassigned:{
      width: 180,
      height: 180,
      backgroundColor:'#ffdeaa',
    },

    touchPaused:{
      width: 180,
      height: 180,
      backgroundColor:'#dd8aff',
    },

    inputBox: {
        width: 300,
        backgroundColor:'#C0C0C0',
        borderRadius: 25,
        paddingHorizontal: 16,
        fontSize :14,
        color: '#ffffff',
        marginVertical: 13
    },

    textwelcome:{
      marginHorizontal: 15,
      fontFamily: Fonts.LexendExa,
      fontSize: 15,
    },

    textcpyr:{
      paddingBottom:15,
      textAlign: "center",
      fontFamily: Fonts.LexendExa,
      fontSize: 15
    },

    buttonText: {
      fontSize : 16,
      fontWeight : '500',
      color: '#FFFFFF',
      textAlign:'center'
  },

  button: {
      width:100,
      backgroundColor: '#C0C0C0',
      borderRadius: 40,
      marginVertical: 5,
      marginHorizontal: 100,
      paddingVertical: 13,
  },
    textasih:{
      marginVertical:20,
      marginHorizontal: 15,
      fontFamily: Fonts.LexendExa,
      fontSize: 15
    },
    tampilan :{
      backgroundColor: '#cfe6f4',
      flex:1
    },
    garis:{
      width: 360, 
      height: 2, 
      backgroundColor: 'gray',
      marginVertical: 1
    },
});

And then, this is a Login.js

import React, { Component } from 'react';
import { Text, View, StyleSheet, StatusBar, TouchableOpacity,Animated,ScrollView } from 'react-native';

import Logo from '../components/Logo';
import Form from '../components/Form';

import {Actions} from 'react-native-router-flux';
import Wallpaper from '../components/Wallpaper';

export default class Login extends Component {

    render() {
        return(

            <View style={styles.container}>
                <Wallpaper>
                    <Logo navigation = {this.props.navigation}/>
                    <Form navigation = {this.props.navigation} type ="Login"/>
                </Wallpaper>
            </View>
        )
    }
}

const styles = StyleSheet.create({
    container: {
      backgroundColor : '#FFFFE0',
      flex: 1,
      alignItems: 'center',
      justifyContent: 'center'
    },

    signupTextCont: {
        flexGrow: 1,
        alignItems: 'center',
        justifyContent: 'flex-end',
        paddingVertical: 16,
        flexDirection: 'row'
    },

    signupText:{
        color: 'rgba(255,255,255, 0.7)',
        fontSize: 16,
        paddingVertical: 30,
        marginVertical: 30
    },

    signupButton: {
        color: '#ffffff',
        fontSize: 16,
        fontWeight:'500'
    }
  });

This is the example the text of all value accessToken :

res token :
{"access_token":"//value of access_token","expires_in":"86400","token_type":"bearer","scope":"*","refresh_token":"//value of refresh_token"}

token is :
{"access_token":"//value of access_token","expires_in":"86400","token_type":"bearer","scope":"*","refresh_token":"//value of refresh_token"}

I hope i get a solution at here :D thank you


Solution

  • You can get the JSON result of your REST request and then access the 'access_token' member, like this:

    try {
      let response = await fetch('https://bpm.asihputera.or.id/api/1.0/users/', {
        method: 'GET',
        headers: {
          'Content-Type'        : 'application/json',
          'Accept-Encoding'     : 'gzip, deflate',
          'Authorization'       : 'Bearer '+ this.state.accessToken,
    
        },
        body: JSON.stringify({
          'grant_type'          : "password",
          'scope'               : '*',
          'client_id'           : 'QKQYKIBJUXFRMGITBPKXVBWOVMFYPWWF',
          'client_secret'       : '2922119675d440616c9a613026663027',
          'username'            : this.state.username,
          'password'            : this.state.password,
        }),
      });
    
      let res = await response.json(); // this line
      if (response.status >= 200 && response.status <=300) {
        this.setState({error:""});
        let accessToken = res;
        this.storeToken(accessToken.access_token); //and this line
        this.getToken();
        console.log("res token: "+accessToken);
        Actions.Cases({"userName" :this.state.username ,"Password":  this.state.password})
      } else {
        let error = res;
        throw error;
      }
    } catch(error){
      this.removeToken();
      this.setState({error: error});
      console.log("error" + error);
    }