package com.example.bdkipoc; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.view.WindowManager; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.google.android.material.button.MaterialButton; import org.json.JSONObject; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class LoginActivity extends AppCompatActivity { private static final String TAG = "LoginActivity"; private static final String PREFS_NAME = "LoginPrefs"; private static final String KEY_TOKEN = "token"; private static final String KEY_USER_DATA = "user_data"; private static final String KEY_IS_LOGGED_IN = "is_logged_in"; private EditText etIdentifier, etPassword; private MaterialButton btnLogin; private ProgressBar progressBar; private ExecutorService executor; private String currentPassword; @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); if (hasFocus) { getWindow().getDecorView().setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY); } } @Override protected void onCreate(Bundle savedInstanceState) { // Enable hardware acceleration getWindow().setFlags( WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED, WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED ); super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); // Check if user is already logged in if (isUserLoggedIn()) { navigateToMainActivity(); return; } initializeViews(); setupListeners(); executor = Executors.newSingleThreadExecutor(); } private void initializeViews() { etIdentifier = findViewById(R.id.et_identifier); etPassword = findViewById(R.id.et_password); btnLogin = findViewById(R.id.btn_login); progressBar = findViewById(R.id.progress_bar); } private void setupListeners() { btnLogin.setOnClickListener(v -> { String identifier = etIdentifier.getText().toString().trim(); String password = etPassword.getText().toString().trim(); if (validateInput(identifier, password)) { performLogin(identifier, password); } }); } private boolean validateInput(String identifier, String password) { if (TextUtils.isEmpty(identifier)) { etIdentifier.setError("Email/Username tidak boleh kosong"); etIdentifier.requestFocus(); return false; } if (TextUtils.isEmpty(password)) { etPassword.setError("Password tidak boleh kosong"); etPassword.requestFocus(); return false; } if (password.length() < 6) { etPassword.setError("Password minimal 6 karakter"); etPassword.requestFocus(); return false; } return true; } private void performLogin(String identifier, String password) { setLoadingState(true); currentPassword = password; executor.execute(() -> { try { // Create JSON payload JSONObject jsonPayload = new JSONObject(); jsonPayload.put("identifier", identifier); jsonPayload.put("password", password); // Setup HTTP connection using BuildConfig URL url = new URL(BuildConfig.BACKEND_BASE_URL + "/users/auth"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("accept", "*/*"); connection.setDoOutput(true); connection.setConnectTimeout(10000); connection.setReadTimeout(10000); // Send request try (OutputStream os = connection.getOutputStream()) { byte[] input = jsonPayload.toString().getBytes("utf-8"); os.write(input, 0, input.length); } // Get response int responseCode = connection.getResponseCode(); Log.d(TAG, "Response Code: " + responseCode); BufferedReader reader; if (responseCode >= 200 && responseCode < 300) { reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); } else { reader = new BufferedReader(new InputStreamReader(connection.getErrorStream())); } StringBuilder response = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); connection.disconnect(); Log.d(TAG, "Response: " + response.toString()); // Parse response on main thread runOnUiThread(() -> handleLoginResponse(responseCode, response.toString())); } catch (Exception e) { Log.e(TAG, "Login error: " + e.getMessage(), e); runOnUiThread(() -> { setLoadingState(false); Toast.makeText(this, "Koneksi gagal: " + e.getMessage(), Toast.LENGTH_LONG).show(); }); } }); } private void handleLoginResponse(int responseCode, String responseBody) { setLoadingState(false); try { JSONObject jsonResponse = new JSONObject(responseBody); if (responseCode >= 200 && responseCode < 300) { // Login successful String message = jsonResponse.optString("message", ""); int status = jsonResponse.optInt("status", 0); if (status == 200) { JSONObject result = jsonResponse.getJSONObject("result"); String token = result.getString("token"); JSONObject userData = result.getJSONObject("user"); // Log user data to console logUserData(userData); // Save login data SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE); SharedPreferences.Editor editor = prefs.edit(); editor.putString(KEY_TOKEN, token); editor.putString(KEY_USER_DATA, userData.toString()); editor.putBoolean(KEY_IS_LOGGED_IN, true); editor.putString("current_password", currentPassword); editor.apply(); Toast.makeText(this, "Login berhasil! " + message, Toast.LENGTH_SHORT).show(); // Navigate to MainActivity navigateToMainActivity(); } else { Toast.makeText(this, "Login gagal: " + message, Toast.LENGTH_LONG).show(); } } else { // Login failed String errorMessage = jsonResponse.optString("message", "Login gagal"); Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show(); Log.e(TAG, "Login failed: " + errorMessage); } } catch (Exception e) { Log.e(TAG, "Error parsing response: " + e.getMessage(), e); Toast.makeText(this, "Error parsing response", Toast.LENGTH_LONG).show(); } } // Method to log user data to console private void logUserData(JSONObject userData) { try { StringBuilder userInfo = new StringBuilder(); userInfo.append("\n=== USER LOGIN DETAILS ==="); userInfo.append("\nID: ").append(userData.optString("id", "N/A")); userInfo.append("\nName: ").append(userData.optString("name", "N/A")); userInfo.append("\nEmail: ").append(userData.optString("email", "N/A")); userInfo.append("\nRole: ").append(userData.optString("role", "N/A")); userInfo.append("\nPhone: ").append(userData.optString("phone", "N/A")); userInfo.append("\nPosition: ").append(userData.optString("position", "N/A")); userInfo.append("\nMID: ").append(userData.optString("mid", "N/A")); userInfo.append("\nTID: ").append(userData.optString("tid", "N/A")); userInfo.append("\nLast Login: ").append(userData.optString("last_login", "N/A")); userInfo.append("\n=========================="); Log.i(TAG, userInfo.toString()); } catch (Exception e) { Log.e(TAG, "Error logging user data: " + e.getMessage()); } } private void setLoadingState(boolean isLoading) { btnLogin.setEnabled(!isLoading); etIdentifier.setEnabled(!isLoading); etPassword.setEnabled(!isLoading); progressBar.setVisibility(isLoading ? View.VISIBLE : View.GONE); if (isLoading) { btnLogin.setText("Memproses..."); } else { btnLogin.setText("MASUK"); } } private boolean isUserLoggedIn() { SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE); return prefs.getBoolean(KEY_IS_LOGGED_IN, false); } private void navigateToMainActivity() { Intent intent = new Intent(LoginActivity.this, MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); finish(); } // Public static methods untuk mengakses data login dari activity lain public static String getToken(android.content.Context context) { SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, MODE_PRIVATE); return prefs.getString(KEY_TOKEN, ""); } public static String getUserData(android.content.Context context) { SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, MODE_PRIVATE); return prefs.getString(KEY_USER_DATA, ""); } public static JSONObject getUserDataAsJson(android.content.Context context) { try { String userData = getUserData(context); if (!TextUtils.isEmpty(userData)) { return new JSONObject(userData); } } catch (Exception e) { Log.e("LoginActivity", "Error parsing user data: " + e.getMessage()); } return null; } public static void logout(android.content.Context context) { SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, MODE_PRIVATE); SharedPreferences.Editor editor = prefs.edit(); editor.clear(); editor.apply(); // Navigate back to login Intent intent = new Intent(context, LoginActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); context.startActivity(intent); } public static boolean isLoggedIn(android.content.Context context) { SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, MODE_PRIVATE); return prefs.getBoolean(KEY_IS_LOGGED_IN, false); } @Override protected void onDestroy() { super.onDestroy(); if (executor != null && !executor.isShutdown()) { executor.shutdown(); } } }