# Android Kotlin App Development Guide ## School Staff OTP & Device-Binding Authentication Client This guide provides the complete, production-ready implementation for building the native Android application in **Kotlin** for the **School Staff OTP Authentication System**. --- ## 1. Architecture & Security Specifications * **Target Android Version:** Android 8.0+ (API 26+) up to Android 14+ (API 34). * **Zero Dangerous Permissions:** Does **not** request `READ_PHONE_STATE`, IMEI, MAC address, or SIM serial number. * **Device ID Architecture:** A persistent, cryptographically secure identifier generated on initial launch and anchored in hardware-backed storage using **`EncryptedSharedPreferences`** (backed by Android Keystore). * **OTP Delivery Channel:** Delivered directly to the staff member's WhatsApp via Fast2SMS WhatsApp API (Template ID: `3529`). * **Communication Protocol:** JSON REST API over HTTPS (or HTTP `10.0.2.2` during local emulator development). * **Token Management:** Bearer token stored securely in `EncryptedSharedPreferences` with automatic attachment via an OkHttp `Interceptor`. --- ## 2. Project Setup & Dependencies In your Android Studio project, configure the following dependencies in `app/build.gradle.kts` (or `build.gradle`): ```kotlin plugins { alias(libs.plugins.android.application) alias(libs.plugins.kotlin.android) } android { namespace = "com.school.staffauth" compileSdk = 34 defaultConfig { applicationId = "com.school.staffauth" minSdk = 26 targetSdk = 34 versionCode = 1 versionName = "1.0.0" testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" } buildFeatures { viewBinding = true } compileOptions { sourceCompatibility = JavaVersion.VERSION_17 targetCompatibility = JavaVersion.VERSION_17 } kotlinOptions { jvmTarget = "17" } } dependencies { // AndroidX & Material implementation("androidx.core:core-ktx:1.13.1") implementation("androidx.appcompat:appcompat:1.7.0") implementation("com.google.android.material:material:1.12.0") implementation("androidx.constraintlayout:constraintlayout:2.1.4") implementation("androidx.lifecycle:lifecycle-viewmodel-ktx:2.8.6") implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.8.6") implementation("androidx.activity:activity-ktx:1.9.2") // Security & Cryptography (EncryptedSharedPreferences & Android Keystore) implementation("androidx.security:security-crypto:1.1.0-alpha06") // Networking: Retrofit & OkHttp implementation("com.squareup.retrofit2:retrofit:2.11.0") implementation("com.squareup.retrofit2:converter-gson:2.11.0") implementation("com.squareup.okhttp3:okhttp:4.12.0") implementation("com.squareup.okhttp3:logging-interceptor:4.12.0") // Coroutines implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.8.1") } ``` --- ## 3. Network Configuration & Permissions ### `AndroidManifest.xml` Add the Internet permission and configure the network security configuration: ```xml ``` ### `res/xml/network_security_config.xml` Allows cleartext HTTP traffic to local development hosts (`10.0.2.2` for standard Android Emulator and local LAN subnets). In production, only HTTPS is permitted: ```xml teachers.ssss.org.in 10.0.2.2 192.168.1.0 ``` --- ## 4. Hardware-Backed Device ID Manager As specified in the core security requirements, the app must generate and securely persist a stable device identifier without requesting sensitive permissions. Create `data/security/DeviceIdManager.kt`: ```kotlin package com.school.staffauth.data.security import android.content.Context import android.content.SharedPreferences import androidx.security.crypto.EncryptedSharedPreferences import androidx.security.crypto.MasterKey import java.util.UUID class DeviceIdManager(context: Context) { private val sharedPreferences: SharedPreferences init { // Build a hardware-backed MasterKey using the Android Keystore val masterKey = MasterKey.Builder(context) .setKeyScheme(MasterKey.KeyScheme.AES256_GCM) .build() // Create EncryptedSharedPreferences backed by the MasterKey sharedPreferences = EncryptedSharedPreferences.create( context, PREFS_FILE_NAME, masterKey, EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV, EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM ) } /** * Retrieves the persistent hardware-anchored device ID. * Generates a cryptographically strong UUID on first app launch. */ fun getOrCreateDeviceId(): String { var deviceId = sharedPreferences.getString(KEY_DEVICE_ID, null) if (deviceId.isNullOrBlank()) { deviceId = "ANDROID_" + UUID.randomUUID().toString().replace("-", "").uppercase() sharedPreferences.edit().putString(KEY_DEVICE_ID, deviceId).apply() } return deviceId } companion object { private const val PREFS_FILE_NAME = "secure_device_prefs" private const val KEY_DEVICE_ID = "app_device_identifier" } } ``` --- ## 5. Session Token Manager Create `data/security/SessionManager.kt` to securely store the raw 64-character bearer token returned by `/api/auth/verify-otp.php`: ```kotlin package com.school.staffauth.data.security import android.content.Context import android.content.SharedPreferences import androidx.security.crypto.EncryptedSharedPreferences import androidx.security.crypto.MasterKey class SessionManager(context: Context) { private val prefs: SharedPreferences init { val masterKey = MasterKey.Builder(context) .setKeyScheme(MasterKey.KeyScheme.AES256_GCM) .build() prefs = EncryptedSharedPreferences.create( context, "secure_session_prefs", masterKey, EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV, EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM ) } fun saveSessionToken(token: String) { prefs.edit().putString(KEY_TOKEN, token).apply() } fun getSessionToken(): String? { return prefs.getString(KEY_TOKEN, null) } fun clearSession() { prefs.edit().remove(KEY_TOKEN).apply() } fun isLoggedIn(): Boolean { return !getSessionToken().isNullOrBlank() } companion object { private const val KEY_TOKEN = "session_token" } } ``` --- ## 6. Network Data Models Create `data/model/AuthModels.kt`: ```kotlin package com.school.staffauth.data.model import com.google.gson.annotations.SerializedName // POST /api/auth/request-otp.php Payload data class RequestOtpPayload( @SerializedName("mobile") val mobile: String, @SerializedName("device_id") val deviceId: String ) // POST /api/auth/verify-otp.php Payload data class VerifyOtpPayload( @SerializedName("mobile") val mobile: String, @SerializedName("otp") val otp: String, @SerializedName("device_id") val deviceId: String ) // Common API Response wrapper data class ApiResponse( @SerializedName("success") val success: Boolean, @SerializedName("code") val code: String?, @SerializedName("message") val message: String?, @SerializedName("token") val token: String?, @SerializedName("user") val user: UserProfile?, @SerializedName("session") val session: SessionDetails? ) data class UserProfile( @SerializedName("id") val id: Long, @SerializedName("name") val name: String, @SerializedName("mobile") val mobile: String, @SerializedName("role") val role: String, @SerializedName("status") val status: String?, @SerializedName("device_registered") val deviceRegistered: Boolean?, @SerializedName("device_bound_at") val deviceBoundAt: String? ) data class SessionDetails( @SerializedName("expires_at") val expiresAt: String? ) ``` --- ## 7. Retrofit API Service & HTTP Client ### `data/api/AuthApiService.kt` ```kotlin package com.school.staffauth.data.api import com.school.staffauth.data.model.ApiResponse import com.school.staffauth.data.model.RequestOtpPayload import com.school.staffauth.data.model.UserProfile import com.school.staffauth.data.model.VerifyOtpPayload import retrofit2.Response import retrofit2.http.Body import retrofit2.http.GET import retrofit2.http.POST interface AuthApiService { @POST("api/auth/request-otp.php") suspend fun requestOtp( @Body payload: RequestOtpPayload ): Response> @POST("api/auth/verify-otp.php") suspend fun verifyOtp( @Body payload: VerifyOtpPayload ): Response> @POST("api/auth/logout.php") suspend fun logout(): Response> @GET("api/auth/me.php") suspend fun getProfile(): Response> } ``` ### `data/api/ApiClient.kt` ```kotlin package com.school.staffauth.data.api import com.school.staffauth.data.security.SessionManager import okhttp3.Interceptor import okhttp3.OkHttpClient import okhttp3.Response import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import java.util.concurrent.TimeUnit class AuthInterceptor(private val sessionManager: SessionManager) : Interceptor { override fun intercept(chain: Interceptor.Chain): Response { val original = chain.request() val builder = original.newBuilder() // Attach Authorization header if session token is available sessionManager.getSessionToken()?.let { token -> builder.header("Authorization", "Bearer $token") } builder.header("Accept", "application/json") return chain.proceed(builder.build()) } } object ApiClient { // Production Server Base URL private const val BASE_URL = "https://teachers.ssss.org.in/" fun create(sessionManager: SessionManager): AuthApiService { val logging = HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY } val okHttpClient = OkHttpClient.Builder() .addInterceptor(AuthInterceptor(sessionManager)) .addInterceptor(logging) .connectTimeout(15, TimeUnit.SECONDS) .readTimeout(15, TimeUnit.SECONDS) .build() return Retrofit.Builder() .baseUrl(BASE_URL) .client(okHttpClient) .addConverterFactory(GsonConverterFactory.create()) .build() .create(AuthApiService::class.java) } } ``` --- ## 8. Authentication Repository Create `data/repository/AuthRepository.kt`: ```kotlin package com.school.staffauth.data.repository import com.google.gson.Gson import com.school.staffauth.data.api.AuthApiService import com.school.staffauth.data.model.ApiResponse import com.school.staffauth.data.model.RequestOtpPayload import com.school.staffauth.data.model.UserProfile import com.school.staffauth.data.model.VerifyOtpPayload import com.school.staffauth.data.security.DeviceIdManager import com.school.staffauth.data.security.SessionManager import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext sealed class AuthResult { data class Success(val data: T, val message: String?) : AuthResult() data class Error(val code: String?, val message: String, val httpCode: Int) : AuthResult() } class AuthRepository( private val api: AuthApiService, private val deviceIdManager: DeviceIdManager, private val sessionManager: SessionManager ) { val deviceId: String get() = deviceIdManager.getOrCreateDeviceId() suspend fun requestOtp(mobile: String): AuthResult = withContext(Dispatchers.IO) { try { val payload = RequestOtpPayload(mobile = mobile, deviceId = deviceId) val response = api.requestOtp(payload) if (response.isSuccessful && response.body()?.success == true) { AuthResult.Success(Unit, response.body()?.message) } else { val errorBody = parseError(response.errorBody()?.string()) AuthResult.Error( code = errorBody?.code, message = errorBody?.message ?: "Failed to request OTP", httpCode = response.code() ) } } catch (e: Exception) { AuthResult.Error(code = "NETWORK_ERROR", message = e.localizedMessage ?: "Network error", httpCode = 0) } } suspend fun verifyOtp(mobile: String, otp: String): AuthResult = withContext(Dispatchers.IO) { try { val payload = VerifyOtpPayload(mobile = mobile, otp = otp, deviceId = deviceId) val response = api.verifyOtp(payload) if (response.isSuccessful && response.body()?.success == true) { val body = response.body()!! body.token?.let { sessionManager.saveSessionToken(it) } AuthResult.Success(body.user!!, body.message) } else { val errorBody = parseError(response.errorBody()?.string()) AuthResult.Error( code = errorBody?.code, message = errorBody?.message ?: "Verification failed", httpCode = response.code() ) } } catch (e: Exception) { AuthResult.Error(code = "NETWORK_ERROR", message = e.localizedMessage ?: "Network error", httpCode = 0) } } suspend fun logout(): Boolean = withContext(Dispatchers.IO) { try { api.logout() } catch (_: Exception) {} sessionManager.clearSession() true } suspend fun getProfile(): AuthResult = withContext(Dispatchers.IO) { try { val response = api.getProfile() if (response.isSuccessful && response.body()?.success == true) { AuthResult.Success(response.body()!!.user!!, null) } else { AuthResult.Error(code = "UNAUTHORIZED", message = "Session expired", httpCode = response.code()) } } catch (e: Exception) { AuthResult.Error(code = "NETWORK_ERROR", message = e.localizedMessage ?: "Network error", httpCode = 0) } } private fun parseError(json: String?): ApiResponse<*>? { if (json.isNullOrBlank()) return null return try { Gson().fromJson(json, ApiResponse::class.java) } catch (_: Exception) { null } } } ``` --- ## 9. Application Class Container Create `StaffAuthApplication.kt`: ```kotlin package com.school.staffauth import android.app.Application import com.school.staffauth.data.api.ApiClient import com.school.staffauth.data.repository.AuthRepository import com.school.staffauth.data.security.DeviceIdManager import com.school.staffauth.data.security.SessionManager class StaffAuthApplication : Application() { lateinit var deviceIdManager: DeviceIdManager private set lateinit var sessionManager: SessionManager private set lateinit var authRepository: AuthRepository private set override fun onCreate() { super.onCreate() deviceIdManager = DeviceIdManager(this) sessionManager = SessionManager(this) val api = ApiClient.create(sessionManager) authRepository = AuthRepository(api, deviceIdManager, sessionManager) } } ``` --- ## 10. UI Activities & State Handling ### Step 1: Request OTP Screen (`RequestOtpActivity.kt`) Handles entering the mobile number, displays the bound hardware device ID, and calls `requestOtp`: ```kotlin package com.school.staffauth.ui import android.content.Intent import android.os.Bundle import android.view.View import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.lifecycleScope import com.school.staffauth.StaffAuthApplication import com.school.staffauth.data.repository.AuthResult import com.school.staffauth.databinding.ActivityRequestOtpBinding import kotlinx.coroutines.launch class RequestOtpActivity : AppCompatActivity() { private lateinit var binding: ActivityRequestOtpBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val app = application as StaffAuthApplication // If user already has an active session token, direct to Dashboard if (app.sessionManager.isLoggedIn()) { startActivity(Intent(this, DashboardActivity::class.java)) finish() return } binding = ActivityRequestOtpBinding.inflate(layoutInflater) setContentView(binding.root) // Display current device ID for developer / user verification binding.tvDeviceId.text = "Device ID: ${app.deviceIdManager.getOrCreateDeviceId()}" binding.btnRequestOtp.setOnClickListener { val mobile = binding.etMobile.text.toString().trim() if (mobile.length < 10) { binding.etMobile.error = "Enter a valid 10-digit mobile number" return@setOnClickListener } performRequestOtp(mobile) } } private fun performRequestOtp(mobile: String) { val app = application as StaffAuthApplication binding.progressBar.visibility = View.VISIBLE binding.btnRequestOtp.isEnabled = false lifecycleScope.launch { when (val result = app.authRepository.requestOtp(mobile)) { is AuthResult.Success -> { binding.progressBar.visibility = View.GONE binding.btnRequestOtp.isEnabled = true Toast.makeText(this@RequestOtpActivity, "OTP dispatched to WhatsApp!", Toast.LENGTH_SHORT).show() val intent = Intent(this@RequestOtpActivity, VerifyOtpActivity::class.java).apply { putExtra("EXTRA_MOBILE", mobile) } startActivity(intent) } is AuthResult.Error -> { binding.progressBar.visibility = View.GONE binding.btnRequestOtp.isEnabled = true if (result.code == "OTP_LIMIT_EXCEEDED") { Toast.makeText(this@RequestOtpActivity, "Daily limit reached: Maximum 3 OTP requests per day.", Toast.LENGTH_LONG).show() } else { Toast.makeText(this@RequestOtpActivity, result.message, Toast.LENGTH_LONG).show() } } } } } } ``` --- ### Step 2: Verify OTP & Device Binding (`VerifyOtpActivity.kt`) **Critical Step:** Handles all 3 outcomes: * **Case A / B:** OTP verified and device binds / matches -> Session created -> Navigate to Dashboard. * **Case C:** Returns `DEVICE_NOT_REGISTERED` -> Displays a non-dismissible dialogue informing the user that this account is locked to another device and the administrator must deregister it first. ```kotlin package com.school.staffauth.ui import android.content.Intent import android.os.Bundle import android.view.View import android.widget.Toast import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.lifecycleScope import com.school.staffauth.StaffAuthApplication import com.school.staffauth.data.repository.AuthResult import com.school.staffauth.databinding.ActivityVerifyOtpBinding import kotlinx.coroutines.launch class VerifyOtpActivity : AppCompatActivity() { private lateinit var binding: ActivityVerifyOtpBinding private lateinit var mobile: String override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityVerifyOtpBinding.inflate(layoutInflater) setContentView(binding.root) mobile = intent.getStringExtra("EXTRA_MOBILE") ?: "" binding.tvMobileLabel.text = "OTP sent via WhatsApp to $mobile" binding.btnVerify.setOnClickListener { val otp = binding.etOtp.text.toString().trim() if (otp.length != 6) { binding.etOtp.error = "Enter 6-digit OTP" return@setOnClickListener } performVerifyOtp(otp) } } private fun performVerifyOtp(otp: String) { val app = application as StaffAuthApplication binding.progressBar.visibility = View.VISIBLE binding.btnVerify.isEnabled = false lifecycleScope.launch { when (val result = app.authRepository.verifyOtp(mobile, otp)) { is AuthResult.Success -> { binding.progressBar.visibility = View.GONE Toast.makeText(this@VerifyOtpActivity, "Login Successful! Device registered.", Toast.LENGTH_SHORT).show() val intent = Intent(this@VerifyOtpActivity, DashboardActivity::class.java).apply { flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK } startActivity(intent) finish() } is AuthResult.Error -> { binding.progressBar.visibility = View.GONE binding.btnVerify.isEnabled = true // Handle Section 5 Case C: DEVICE_NOT_REGISTERED if (result.code == "DEVICE_NOT_REGISTERED") { showDeviceNotRegisteredDialog(result.message) } else if (result.code == "OTP_MAX_ATTEMPTS_EXCEEDED") { showMaxAttemptsDialog() } else { Toast.makeText(this@VerifyOtpActivity, result.message, Toast.LENGTH_LONG).show() } } } } } private fun showDeviceNotRegisteredDialog(serverMessage: String) { AlertDialog.Builder(this) .setTitle("Device Not Registered") .setMessage(serverMessage) .setCancelable(false) .setPositiveButton("Contact Admin / Close") { dialog, _ -> dialog.dismiss() finish() } .show() } private fun showMaxAttemptsDialog() { AlertDialog.Builder(this) .setTitle("Too Many Attempts") .setMessage("Maximum 5 incorrect attempts exceeded. This OTP is invalidated. Please request a new OTP.") .setPositiveButton("OK") { dialog, _ -> dialog.dismiss() finish() } .show() } } ``` --- ### Step 3: Staff Dashboard Screen (`DashboardActivity.kt`) Displays profile information, verifies session validity with `/api/auth/me.php`, and provides a Logout action (which revokes only the session token while preserving device binding): ```kotlin package com.school.staffauth.ui import android.content.Intent import android.os.Bundle import android.view.View import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.lifecycleScope import com.school.staffauth.StaffAuthApplication import com.school.staffauth.data.repository.AuthResult import com.school.staffauth.databinding.ActivityDashboardBinding import kotlinx.coroutines.launch class DashboardActivity : AppCompatActivity() { private lateinit var binding: ActivityDashboardBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityDashboardBinding.inflate(layoutInflater) setContentView(binding.root) val app = application as StaffAuthApplication binding.tvDeviceId.text = "Bound Device ID:\n${app.deviceIdManager.getOrCreateDeviceId()}" fetchUserProfile() binding.btnLogout.setOnClickListener { lifecycleScope.launch { app.authRepository.logout() Toast.makeText(this@DashboardActivity, "Logged out. Device remains bound.", Toast.LENGTH_SHORT).show() val intent = Intent(this@DashboardActivity, RequestOtpActivity::class.java).apply { flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK } startActivity(intent) finish() } } } private fun fetchUserProfile() { val app = application as StaffAuthApplication binding.progressBar.visibility = View.VISIBLE lifecycleScope.launch { when (val result = app.authRepository.getProfile()) { is AuthResult.Success -> { binding.progressBar.visibility = View.GONE val user = result.data binding.tvStaffName.text = user.name binding.tvStaffRole.text = "Role: ${user.role.uppercase()}" binding.tvStaffMobile.text = "Mobile: ${user.mobile}" } is AuthResult.Error -> { binding.progressBar.visibility = View.GONE if (result.httpCode == 401) { Toast.makeText(this@DashboardActivity, "Session expired or revoked.", Toast.LENGTH_SHORT).show() app.sessionManager.clearSession() startActivity(Intent(this@DashboardActivity, RequestOtpActivity::class.java)) finish() } } } } } } ``` --- ## 11. Testing & Troubleshooting Checklist | Test Scenario | Steps to Execute | Expected Behavior | | :--- | :--- | :--- | | **1. First Login** | Install app on Phone A -> Enter mobile -> Submit WhatsApp OTP | `device_id` is sent to server; server binds Phone A and returns session token. | | **2. Login Again** | Logout on Phone A -> Request OTP -> Submit OTP | Login succeeds immediately because Phone A's stored ID matches server's `device_id`. | | **3. Second Device (Phone B)** | Install app on Phone B -> Enter same mobile -> Submit OTP | Server returns HTTP 403 `DEVICE_NOT_REGISTERED`. Phone B shows alert: *"This account is registered to another device. Please contact administrator."* | | **4. Admin Deregister** | Go to web admin dashboard (`/admin/users.php`) -> Click **Deregister Device** | Server clears `device_id` to `NULL` and revokes active sessions. | | **5. Device Swap** | On Phone B -> Request OTP -> Submit OTP | Phone B now registers itself as the single bound device. Phone A is permanently rejected until next deregistration. |