Thursday, January 6, 2022

[SOLVED] Make android login form using Curl

Issue

I need help to make login using Curl, I just tried make it but it always failed. do I need php file or no ? if yes, can you give me an example how to use it.

here is my url to make login using nik_baru and password

http://hrd.tvip.co.id/rest_server/api/login/index

And here is my code

package com.example.eis2;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

    EditText editTextnik_baru;
    EditText editTextpassword;
    Button buttonlogin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        editTextnik_baru = (EditText) findViewById(R.id.editTextnik_baru);
        editTextpassword = (EditText) findViewById(R.id.editTextpassword);
        buttonlogin = (Button) findViewById(R.id.buttonlogin);

        buttonlogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(!editTextnik_baru.getText().equals("")){
                    sendLogin();

                } else {
                    editTextnik_baru.setError("Please insert NIK");
                    editTextpassword.setError("Please insert password");
                }
            }
        });
    }
    private void sendLogin() {
        String url = "http://hrd.tvip.co.id/rest_server/api/login/index";
        url += editTextnik_baru.getText();
        final String nik_baru = editTextnik_baru.getText().toString().trim();

        StringRequest loginRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONArray array = new JSONArray("data");
                            JSONObject json = array.getJSONObject(0);
                            String status = json.getString("nik_baru");
                            System.out.println("data "+ status);
//                            JSONObject json = getJSONObject("data");
                            if(status.equals(nik_baru)){
                                Log.d("tvip", "success");
                                Intent intent = new Intent(MainActivity.this, menu.class);
                                startActivity(intent);
                                finish();
                            }else{
                                Toast.makeText(getApplicationContext(), "Username & Password Salah", Toast.LENGTH_LONG).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(getApplicationContext(),"Error", Toast.LENGTH_LONG).show();
                    }
                }
        ){
            @Override
            protected Map<String, String> getParams(){
                HashMap<String, String> params = new HashMap<>();
                params.put("nik_baru", editTextnik_baru.getText().toString());
                params.put("password", editTextpassword.getText().toString());
                return params;
            }
        };
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(loginRequest);
    }
}

and this is it's xml code

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#00d0ff"
    tools:context=".MainActivity">

    <ImageView
        android:id="@+id/logoeis"
        android:layout_width="148dp"
        android:layout_height="140dp"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="90dp"
        app:srcCompat="@drawable/logoeis" />
    <ImageView
        android:id="@+id/logoasa"
        android:layout_width="38dp"
        android:layout_height="43dp"
        android:layout_below="@+id/logoeis"
        android:layout_marginLeft="300dp"
        android:layout_marginTop="-200dp"
        app:srcCompat="@drawable/logoasa" />
    <ImageView
        android:id="@+id/logotvip"
        android:layout_width="38dp"
        android:layout_height="43dp"
        android:layout_below="@+id/logoeis"
        android:layout_marginLeft="250dp"
        android:layout_marginTop="-200dp"
        app:srcCompat="@drawable/logotvip" />
    <EditText
        android:id="@+id/editTextnik_baru"
        android:layout_width="241dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        android:layout_below="@+id/logoeis"
        android:layout_centerHorizontal="true"
        android:hint="NIK Baru"
        android:inputType="text"
        android:textColor="#000000"
        android:selectAllOnFocus="true"/>
    <EditText
        android:id="@+id/editTextpassword"
        android:layout_width="241dp"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editTextnik_baru"
        android:layout_centerHorizontal="true"
        android:hint="Password"
        android:textColor="#000000"
        android:inputType="textPassword"
        android:selectAllOnFocus="true"/>
    <Button
        android:id="@+id/buttonlogin"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editTextpassword"
        android:layout_centerHorizontal="true"
        android:text="Login"
        android:layout_marginTop="15dp" />
    <TextView
        android:id="@+id/eis"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Employee Information System"
        android:textSize="23dp"
        android:layout_marginTop="12dp"
        android:textColor="#000000"
        android:layout_below="@+id/buttonlogin"
        android:layout_centerHorizontal="true"/>
    <TextView
        android:id="@+id/version"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Version 1.0"
        android:textSize="23dp"
        android:layout_marginTop="12dp"
        android:textColor="#000000"
        android:layout_below="@+id/eis"
        android:layout_centerHorizontal="true"/>
</RelativeLayout>

Can you guys solve this problem ?


Solution

This is just an example... the exact coding for your particular login system may be different.

The server login file PHP would be similar to this:

if (isset($_POST['username']) && $_POST['username'] != '') {
    $loginPassword = $_POST['password'];
    $username = $_POST['username'];
    $sql = "SELECT `id`, `username`, `email`, `password`, `key` FROM `TABLE_NAME` WHERE `username`=:username";
    $LoginRS_query = $conn->prepare($sql);
    $LoginRS_query->bindValue(':username', $username, PDO::PARAM_STR);
    $LoginRS_query->execute();
    $LoginRS = $LoginRS_query->fetch(PDO::FETCH_ASSOC);
    $totalRows = $LoginRS_query->rowCount();
    
    if($totalRows > 0) {
        $db_key = $LoginRS['key'];
        $peppered = hash_hmac("sha256", $loginPassword, $db_key);
        $db_pwd = $LoginRS['password'];
        if(password_verify($peppered, $db_pwd)) {
            $loginFoundUser = 'true';
        } else {
            $loginFoundUser = 'false';
        }
    }
    
    if($loginFoundUser == 'true') {
        $loginID =  $LoginRS['id'];
        $loginUserName = $LoginRS['username'];
        
        $LoginRS_query->closeCursor();
        
        echo "success";
        
        $response = array('id' => $loginID, 'username' => $loginUserName);
        echo json_encode($response);
    } else {
        $LoginRS_query->closeCursor();
        echo "no user found";
    }
} else {
    echo "access failed";
}

Then in your activity file inside sendLogin() ...

public void onResponse(String response) {
    if (response.contains("success")) {
        String res = response.substring(response.indexOf("{"));
        try {
            JSONObject jsonObject = new JSONObject(res);
            final String loginID = jsonObject.getString("id");
            final String loginUser = jsonObject.getString("username");
            
            Intent intent = new Intent(MainActivity.this, menu.class);
            intent.putExtra("id", loginID); // added this line
            intent.putExtra("username", loginUser); // added this line
            startActivity(intent);
            finish();
        } catch (JSONException e) {
            e.printStackTrace();
            Toast.makeText(getApplicationContext(), "Login Error " + e, Toast.LENGTH_LONG).show();
        }
    }else{
        Toast.makeText(getApplicationContext(), "Username & Password Salah", Toast.LENGTH_LONG).show();
    }

The intent.putExtra is only needed if you will need your username or ID elsewhere to perform other tasks



Answered By - Kuya