Skip to content

Commit

Permalink
- Adds back handler
Browse files Browse the repository at this point in the history
- sends package name and signature
  • Loading branch information
guillermo-bucksapp committed Mar 14, 2022
1 parent 5661780 commit ad04a85
Show file tree
Hide file tree
Showing 6 changed files with 136 additions and 151 deletions.
96 changes: 0 additions & 96 deletions androidsdk/build.gradle
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
plugins {
id 'com.android.library'
id 'kotlin-android'
id 'maven-publish'
}

android {
Expand All @@ -25,26 +24,6 @@ android {
}
}

defaultPublishConfig "productionRelease"

flavorDimensions "version"

productFlavors {
production {
dimension "version"
buildConfigField("String", "API_URL", "\"https://api.dev.bucksapp.com\"")
buildConfigField("String", "ENV", "\"production\"")
}
sandbox {
dimension "version"
buildConfigField("String", "API_URL", "\"https://api.dev.bucksapp.com\"")
buildConfigField("String", "ENV", "\"development\"")
}
}

// default build flavour
defaultPublishConfig "productionRelease"

compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
Expand All @@ -54,15 +33,6 @@ android {
}
}

task sourcesJar(type: Jar) {
archiveClassifier.set("sources")
from android.sourceSets.main.javaDirectories
}
//
//artifacts {
// archives sourcesJar
//}

dependencies {

implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
Expand All @@ -78,69 +48,3 @@ dependencies {
implementation "com.squareup.okhttp3:okhttp:4.9.3"
implementation 'com.google.code.gson:gson:2.9.0'
}

group = 'com.github.bucksapp-corp.android-bucksapp-sdk'
version = library_version

afterEvaluate {
publishing {
publications {
production(MavenPublication) {
from components.productionRelease

groupId = 'com.github.bucksapp-corp'
artifactId = 'android-bucksapp-sdk'
version = library_version
artifact(sourcesJar)
artifact("$buildDir/outputs/aar/android-bucksapp-sdk-production-release.aar") {
classifier 'production'
extension 'aar'
}
}

sandbox(MavenPublication){
from components.sandboxRelease

groupId = 'com.github.bucksapp-corp'
artifactId = 'android-bucksapp-sdk'
version = library_version
artifact(sourcesJar)
artifact("$buildDir/outputs/aar/android-bucksapp-sdk-sandbox-release.aar") {
classifier 'dev'
extension 'aar'
}
}
}
}
}
//
//if (android.productFlavors.size() > 0) {
// android.libraryVariants.all { variant ->
//
// if (variant.name.toLowerCase().contains("debug")) {
// return
// }
//
// def bundleTask = tasks["bundle${variant.name.capitalize()}Aar"]
//
// artifacts {
// archives(bundleTask.archivePath) {
// classifier variant.flavorName
// builtBy bundleTask
// name = project.name
// }
// }
//
// def flavorName = variant.flavorName.toLowerCase()
// def flavorSourcesTask = tasks.create(name : "${flavorName}SourcesJar", type: Jar) {
// archiveClassifier.set("${flavorName}-sources")
// from android.sourceSets.main.javaDirectories
// from android.sourceSets[flavorName].javaDirectories
// }
//
// artifacts {
// archives flavorSourcesTask
// }
//
// }
//}
90 changes: 46 additions & 44 deletions androidsdk/src/main/java/com/bucksapp/androidsdk/Bucksapp.kt
Original file line number Diff line number Diff line change
Expand Up @@ -8,60 +8,61 @@ import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
import java.io.IOException


object Bucksapp {
private val client = OkHttpClient()
private const val defaultLanguage = "es"
fun init(context: Context, apiKey: String, uuid: String) {
val mediaType = "application/json; charset=utf-8".toMediaType()
val gson = Gson()
val jsonString = String.format("{\"user\": \"%s\"}", uuid)
val body: RequestBody = jsonString.toRequestBody(mediaType);
val request: Request = Request.Builder()
.url(java.lang.String.format("%s/api/fi/v1/authenticate", BuildConfig.API_URL))
.method("POST", body)
.addHeader("jwt_aud", BuildConfig.ENV)
.addHeader("Content-Type", "application/json")
.addHeader("X-API-KEY", apiKey)
.build()
client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
e.printStackTrace()
}
private const val stagingEnv = "development"
private const val productionEnv = "production"
private const val defaultEnv = stagingEnv

@Throws(IOException::class)
override fun onResponse(call: Call, response: Response) {
try {
response.body.use { responseBody ->
if (!response.isSuccessful) throw IOException(
"""Unexpected code ${response.body!!.string()}
Headers: ${request.headers}"""
)
val authResponse =
gson.fromJson(responseBody!!.string(), AuthResponse::class.java)
val i = Intent(context, BucksappActivity::class.java)
i.putExtra("TOKEN", authResponse.token)
i.putExtra("LANG", defaultLanguage)
context.startActivity(i)
}
} catch (e: Exception) {
e.printStackTrace()
}
}
})
fun getHost(env: String = defaultEnv): String {
if (env == productionEnv) {
return "https://app.dev.bucksapp.com"
}
return "https://app.dev.bucksapp.com"
}

fun init(context: Context, apiKey: String, uuid: String, language: String) {
val lang = if (language != null || language !== "") language else defaultLanguage
fun getApiAuthHost(env: String = defaultEnv): String {
if (env == productionEnv) {
return "https://api.dev.bucksapp.com"
}
return "https://api.dev.bucksapp.com"
}

fun init(
context: Context,
apiKey: String,
uuid: String,
env: String = defaultEnv,
language: String = defaultLanguage
) {
val signatures = SignatureUtil.getSignatures(context.packageManager,
context.applicationInfo.packageName)
var signature = ""
if (signatures != null) {
if (signatures.isNotEmpty()){
signature = signatures[0]!!
}
}

val mediaType = "application/json; charset=utf-8".toMediaType()
val gson = Gson()
val jsonString = String.format("{\"user\": \"%s\"}", uuid)
val jsonString = String.format(
"{\"user\": \"%s\"}",
uuid,
)
val body: RequestBody = jsonString.toRequestBody(mediaType);
val host: String = getHost(env)
val authHost: String = getApiAuthHost(env)
val request: Request = Request.Builder()
.url(java.lang.String.format("%s/api/fi/v1/authenticate", BuildConfig.API_URL))
.url("$authHost/api/fi/v1/authenticate")
.method("POST", body)
.addHeader("jwt_aud", BuildConfig.ENV)
.addHeader("jwt_aud", env)
.addHeader("Content-Type", "application/json")
.addHeader("X-API-KEY", apiKey)
.addHeader("package_name", context.applicationInfo.packageName)
.addHeader("build_signature", signature)
.build()
client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
Expand All @@ -73,14 +74,15 @@ object Bucksapp {
try {
response.body.use { responseBody ->
if (!response.isSuccessful) throw IOException(
"""Unexpected code ${response.body!!.string()}
Headers: ${request.headers}"""
"""Unexpected code ${response.body!!.string()}
|Headers: ${request.headers}""".trimMargin()
)
val authResponse =
gson.fromJson(responseBody!!.string(), AuthResponse::class.java)
val i = Intent(context, BucksappActivity::class.java)
i.putExtra("TOKEN", authResponse.token)
i.putExtra("LANG", lang)
i.putExtra("LANG", language)
i.putExtra("HOST", host)
context.startActivity(i)
}
} catch (e: Exception) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,41 +1,59 @@
package com.bucksapp.androidsdk

import android.app.Activity
import androidx.appcompat.app.AppCompatActivity
import android.content.Context
import android.os.Bundle
import android.webkit.CookieManager
import android.webkit.JavascriptInterface
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.appcompat.app.AppCompatActivity

/** Instantiate the interface and set the context */
class WebAppInterface(private val mContext: Context) {

/** Show a toast from the web page */
@JavascriptInterface
fun handlerBack() {
val activity = mContext as BucksappActivity
activity.finish()
}
}

class BucksappActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_bucksapp)
var token: String? = null
var lang: String? = null
var host: String? = null
if (savedInstanceState == null) {
val extras = intent.extras
if (extras != null) {
token = extras.getString("TOKEN")
lang = extras.getString("LANG")
host = extras.getString("HOST")
}
} else {
token = savedInstanceState.getSerializable("TOKEN") as String?
lang = savedInstanceState.getSerializable("LANG") as String?
host = savedInstanceState.getSerializable("HOST") as String?
}
val webView = findViewById<WebView>(R.id.webView)
val webViewClient = WebViewClient()
webView.webViewClient = webViewClient
val cookieManager = CookieManager.getInstance()
cookieManager.setAcceptCookie(true)
cookieManager.removeAllCookie()
cookieManager.setCookie("https://app.dev.bucksapp.com/", String.format("token=%s;", token))
cookieManager.setCookie(host, String.format("token=%s;", token))
cookieManager.setCookie(
"https://app.dev.bucksapp.com/",
host,
String.format("NEXT_LOCALE=%s;", lang)
)
webView.loadUrl("https://app.dev.bucksapp.com")
val webSettings = webView.settings
webSettings.javaScriptEnabled = true
if (host != null) {
webView.loadUrl(host)
webView.settings.javaScriptEnabled = true
webView.addJavascriptInterface(WebAppInterface(this), "BucksappAndroid")
}

}
}
65 changes: 65 additions & 0 deletions androidsdk/src/main/java/com/bucksapp/androidsdk/SignatureUtil.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package com.bucksapp.androidsdk

import android.annotation.SuppressLint
import android.content.pm.PackageManager
import android.content.pm.Signature
import android.os.Build
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
import java.util.*

object SignatureUtil {
private fun signatureDigest(sig: Signature): String? {
val signature = sig.toByteArray()
return try {
val md = MessageDigest.getInstance("SHA1")
val digest = md.digest(signature)
val hexBuilder = StringBuilder();
for(b in digest){
hexBuilder.append(String.format("%02x:", b));
}
val hexSignature = hexBuilder.toString().toUpperCase();
hexSignature.dropLast(1)
} catch (e: NoSuchAlgorithmException) {
null
}
}


private fun signatureDigest(sigList: Array<Signature>): List<String?> {
val signaturesList: MutableList<String?> = ArrayList()
for (signature in sigList) {
if (signature != null) {
signaturesList.add(signatureDigest(signature))
}
}
return signaturesList
}

fun getSignatures(pm: PackageManager, packageName: String): List<String?>? {
return try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
val packageInfo =
pm.getPackageInfo(packageName, PackageManager.GET_SIGNING_CERTIFICATES)
if (packageInfo == null
|| packageInfo.signingInfo == null
) {
return null
}
if (packageInfo.signingInfo.hasMultipleSigners()) {
signatureDigest(packageInfo.signingInfo.apkContentsSigners)
} else {
signatureDigest(packageInfo.signingInfo.signingCertificateHistory)
}
} else {
@SuppressLint("PackageManagerGetSignatures") val packageInfo =
pm.getPackageInfo(packageName, PackageManager.GET_SIGNATURES)
if (packageInfo == null || packageInfo.signatures == null || packageInfo.signatures.size == 0 || packageInfo.signatures[0] == null) {
null
} else signatureDigest(packageInfo.signatures)
}
} catch (e: PackageManager.NameNotFoundException) {
null
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ class MainActivity : AppCompatActivity() {
this@MainActivity,
"12TvAswlCh03Qhj5uxiM7w",
"1c111bf4-7646-4b84-bc4c-4426fb596a87",
"es"
)
}

Expand Down
3 changes: 0 additions & 3 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,6 @@ buildscript {
dependencies {
classpath "com.android.tools.build:gradle:4.1.1"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

// classpath 'com.github.dcendents:android-maven-gradle-plugin:2.1'

}
}

Expand Down

0 comments on commit ad04a85

Please sign in to comment.