I'm stuck in an error, my endpoint works with thymeleaf and javascript but not and reactJs.

I tried for hours convert this solution below to reactJS

My init testing in thymeleaf and function javascript it working fine

<script src="/js/sms-login.js"></script>
<script src="https://sdk.accountkit.com/en_US/sdk.js"></script>
</head>
<body>
    <h1>Login with Phone Number</h1>
    <h2 th:if="${param.logout}">You have been logged out</h2>
    <div>
        <select id="country_code">
            <option value="+49">+49 Germany</option>
        </select>
        <input id="phone_number" type="text" placeholder="Phone Number" />
        <br/><br/>
        <button class="fb" onclick="smsLogin()">Verify and Login</button>
    </div>

    <form id="login_success" action="/login/redirect_success" th:object="${accKitReq}" method="POST">
        <input id="csrf" type="hidden" name="csrf" th:field="*{csrf}"/>
        <input id="code" type="hidden" name="code" th:field="*{code}"/>
        <input type="submit" value="Send" />
    </form>
</body>
</html>

My Javascript function

function loginCallback(response) {
    if (response.status === "PARTIALLY_AUTHENTICATED") {
        // Send code to server to exchange for access token
        document.getElementById("code").value = response.code;
        document.getElementById("csrf").value = response.state;
//        document.getElementById("login_success").submit();
        console.log(""Auth ok")
    } else if (response.status === "NOT_AUTHENTICATED") {
        // handle authentication failure
        console.log("NOT_AUTHENTICATED")
    } else if (response.status === "BAD_PARAMS") {
        // handle bad parameters
        console.log("BAD_PARAMS")
    }
    console.log(loginCallback)
}

function smsLogin() {
    var countryCode = document.getElementById("country_code").value;
    var phoneNumber = document.getElementById("phone_number").value;
    AccountKit.login(
        'PHONE',
        {countryCode: countryCode, phoneNumber: phoneNumber}, // will use default values if not specified
        loginCallback
    );
}

This is my endpoint connecting account kit with my backend java spring boot

@GetMapping("/login")
    public String login(ModelMap m) {
        m.addAttribute("accKitReq", new AccountKitPostRequest());
        return null;
    }

    @PostMapping("/login/redirect_success")
    public String loginSuccess(@ModelAttribute AccountKitPostRequest accKitReq) {
        String uri = TOKEN_EXCHANGE_BASE_URL + "?grant_type=authorization_code&code=" +
                        accKitReq.getCode() + "&access_token=AA|" + FB_APP_ID + "|" + AK_APP_SECRET;
        Object obj = restTemplate.getForObject(uri, Object.class);

        @SuppressWarnings("unchecked")
        Map<String, Object> info = (HashMap<String,Object>) obj;
        String user_id = (String) info.get("id");
        String user_access_token = (String) info.get("access_token");

        String me_endpoint_uri = ME_ENDPOINT_BASE_URL + "?access_token=" + user_access_token;
        Object me = restTemplate.getForObject(me_endpoint_uri,Object.class);

        //Set Phone User Object
        @SuppressWarnings("unchecked")
        Map<String, Object> map = (HashMap<String,Object>) me;
        @SuppressWarnings("unchecked")
        Map<String, Object> phone = (HashMap<String,Object>) map.get("phone");
        String number = (String) phone.get("number");

This is my code in ReactJs is not working when I try to submit the form I get error 500 is not sending...

import React, { Component } from 'react';
import AccountKit from 'react-facebook-account-kit';
import { smsLoginRedirect, GetSmsLogin } from '../../util/APIUtils';

function loginCallback(response) {
    if (response.status === "PARTIALLY_AUTHENTICATED") {
        document.getElementById("code").value = response.code;
        document.getElementById("csrf").value = response.state;
        // document.getElementById("login_success").submit();
        console.log("PARTIALLY_AUTHENTICATED")

    } else if (response.status === "NOT_AUTHENTICATED") {
        // handle authentication failure
        console.log("NOT_AUTHENTICATED")
    } else if (response.status === "BAD_PARAMS") {
        // handle bad parameters
        console.log("BAD_PARAMS")
    }
    console.log(response)
  }
export default class FbAccountKit extends Component{

    constructor() {
        super();
        this.state = {
                csrf: '',
                code: ''
            }
        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }
    handleChange (event) {
        this.setState( [event.target.name] : event.target.value )
      }

//My endpoint /login/
    componentDidMount() {
        GetSmsLogin() //endpoinst /login
         .then(({ accKitReq }) => {
           const data = accKitReq
             console.log(data);
           })
      }
//handdle submit with my endpoint /login/redirect_success
    handleSubmit(event) {
        event.preventDefault();
        const data = { 
            code: this.state.code.value,
            csrf: this.state.csrf.value 
        }
        console.log(data)

        smsLoginRedirect(data) //endpoint /login/redirect_success
        .then(response => {
            notification.success({
                description: "Thank you! You're logged in",
            }); 
            console.log(response)

    }

    render() {
        return (
            <div>
                        <AccountKit /> //my private details to init account kit


//I'm receiving from my account ki the code and csrf in my form ok
                    <Form  id="login_success" onSubmit={this.handleSubmit}  >
                        <Input  id="code" type="" name="code"  onChange={event => this.handleChange(event)}/>
                        <Input  id="csrf" type="" name="csrf"  onChange={event => this.handleChange(event)}/>

                        <Button 
                                htmlType="submit" 
                                className="create-poll-form-button">Submit</Button>
                    </Form>

            </div>


        );
    }
}

I am thinking it is about using @ModelAttribute in my endpoint sending object=${accKitReq} while testing thymeleaf, but using ReactJS javascript is not working at all. Any ideas why where is mine mistake? thanks.

1 Answers

0
Leandro J On

I just found out by myself I added 'Content-Type': 'application/x-www-form-urlencoded' to my Post and it worked now.