numandev1 / react-native-keys

πŸ” Protected .ENVs variables in React Native πŸš€βœ¨
MIT License
304 stars 25 forks source link

Not working on react native 0.71.12 on windows #43

Closed lukkimo closed 11 months ago

lukkimo commented 1 year ago

I simply create a keys.development.json in the root of my project with secure and public objects. then build the project with npx react-native run-android command. but I cannot get strings in my components neither with Keys.secureFor('some secret') nor Keys.somePublicString. I checked the example folder but it did not help me!

Can anyone tell me what I miss here?

github-actions[bot] commented 1 year ago

πŸ‘‹ @lukkimo Thanks for opening your issue here! If you find this package useful hit the star🌟!

numandev1 commented 1 year ago

@lukkimo can you share your app/build.gradle code?

lukkimo commented 1 year ago

@lukkimo can you share your app/build.gradle code?

Sure.

apply plugin: "com.android.application"
apply plugin: "com.facebook.react"

import com.android.build.OutputFile

/**
 * This is the configuration block to customize your React Native Android app.
 * By default you don't need to apply any configuration, just uncomment the lines you need.
 */
react {
    /* Folders */
    //   The root of your project, i.e. where "package.json" lives. Default is '..'
    // root = file("../")
    //   The folder where the react-native NPM package is. Default is ../node_modules/react-native
    // reactNativeDir = file("../node_modules/react-native")
    //   The folder where the react-native Codegen package is. Default is ../node_modules/react-native-codegen
    // codegenDir = file("../node_modules/react-native-codegen")
    //   The cli.js file which is the React Native CLI entrypoint. Default is ../node_modules/react-native/cli.js
    // cliFile = file("../node_modules/react-native/cli.js")

    /* Variants */
    //   The list of variants to that are debuggable. For those we're going to
    //   skip the bundling of the JS bundle and the assets. By default is just 'debug'.
    //   If you add flavors like lite, prod, etc. you'll have to list your debuggableVariants.
    // debuggableVariants = ["liteDebug", "prodDebug"]

    /* Bundling */
    //   A list containing the node command and its flags. Default is just 'node'.
    // nodeExecutableAndArgs = ["node"]
    //
    //   The command to run when bundling. By default is 'bundle'
    // bundleCommand = "ram-bundle"
    //
    //   The path to the CLI configuration file. Default is empty.
    // bundleConfig = file(../rn-cli.config.js)
    //
    //   The name of the generated asset file containing your JS bundle
    // bundleAssetName = "MyApplication.android.bundle"
    //
    //   The entry file for bundle generation. Default is 'index.android.js' or 'index.js'
    // entryFile = file("../js/MyApplication.android.js")
    //
    //   A list of extra flags to pass to the 'bundle' commands.
    //   See https://github.com/react-native-community/cli/blob/main/docs/commands.md#bundle
    // extraPackagerArgs = []

    /* Hermes Commands */
    //   The hermes compiler command to run. By default it is 'hermesc'
    // hermesCommand = "$rootDir/my-custom-hermesc/bin/hermesc"
    //
    //   The list of flags to pass to the Hermes compiler. By default is "-O", "-output-source-map"
    // hermesFlags = ["-O", "-output-source-map"]
}

/**
 * Set this to true to create four separate APKs instead of one,
 * one for each native architecture. This is useful if you don't
 * use App Bundles (https://developer.android.com/guide/app-bundle/)
 * and want to have separate APKs to upload to the Play Store.
 */
def enableSeparateBuildPerCPUArchitecture = false

/**
 * Set this to true to Run Proguard on Release builds to minify the Java bytecode.
 */
def enableProguardInReleaseBuilds = false

/**
 * The preferred build flavor of JavaScriptCore (JSC)
 *
 * For example, to use the international variant, you can use:
 * `def jscFlavor = 'org.webkit:android-jsc-intl:+'`
 *
 * The international variant includes ICU i18n library and necessary data
 * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that
 * give correct results when using with locales other than en-US. Note that
 * this variant is about 6MiB larger per architecture than default.
 */
def jscFlavor = 'org.webkit:android-jsc:+'

/**
 * Private function to get the list of Native Architectures you want to build.
 * This reads the value from reactNativeArchitectures in your gradle.properties
 * file and works together with the --active-arch-only flag of react-native run-android.
 */
def reactNativeArchitectures() {
    def value = project.getProperties().get("reactNativeArchitectures")
    return value ? value.split(",") : ["armeabi-v7a", "x86", "x86_64", "arm64-v8a"]
}

apply from: "../../node_modules/@sentry/react-native/sentry.gradle"
android {
    ndkVersion rootProject.ext.ndkVersion

    compileSdkVersion rootProject.ext.compileSdkVersion

    namespace "com.peaktowertech.digivcard"
    defaultConfig {
        applicationId "com.peaktowertech.digivcard"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 10
        versionName "0.5.2"

        missingDimensionStrategy "store", "play"

        //for react-native-crop-image
        vectorDrawables.useSupportLibrary = true
    }

    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include (*reactNativeArchitectures())
        }
    }
    signingConfigs {
        debug {
            storeFile file('debug.keystore')
            storePassword 'android'
            keyAlias 'androiddebugkey'
            keyPassword 'android'
        }
        release {
            if (project.hasProperty('MYAPP_UPLOAD_STORE_FILE')) {
                storeFile file(MYAPP_UPLOAD_STORE_FILE)
                storePassword MYAPP_UPLOAD_STORE_PASSWORD
                keyAlias MYAPP_UPLOAD_KEY_ALIAS
                keyPassword MYAPP_UPLOAD_KEY_PASSWORD
            }
        }
    }
    buildTypes {
        debug {
            signingConfig signingConfigs.debug
        }
        release {
            // Caution! In production, you need to generate your own keystore file.
            // see https://reactnative.dev/docs/signed-apk-android.
            // signingConfig signingConfigs.debug
            signingConfig signingConfigs.release
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
        }
    }

    // applicationVariants are e.g. debug, release
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            // For each separate APK per architecture, set a unique version code as described here:
            // https://developer.android.com/studio/build/configure-apk-splits.html
            // Example: versionCode 1 will generate 1001 for armeabi-v7a, 1002 for x86, etc.
            def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]
            def abi = output.getFilter(OutputFile.ABI)
            if (abi != null) {  // null for the universal-debug, universal-release variants
                output.versionCodeOverride =
                        defaultConfig.versionCode * 1000 + versionCodes.get(abi)
            }

        }
    }
}

dependencies {
    // The version of react-native is set by the React Native Gradle Plugin
    implementation("com.facebook.react:react-android")

    implementation("androidx.core:core-splashscreen:1.0.0")

    implementation("androidx.swiperefreshlayout:swiperefreshlayout:1.0.0")

    debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}")
    debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {
        exclude group:'com.squareup.okhttp3', module:'okhttp'
    }

    debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}")
    if (hermesEnabled.toBoolean()) {
        implementation("com.facebook.react:hermes-android")
    } else {
        implementation jscFlavor
    }
}

apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)
apply from: "../../node_modules/react-native-code-push/android/codepush.gradle"
numandev1 commented 1 year ago

@lukkimo you did not add these lines into app/build.gradle

project.ext.keyFiles = [
   development: "keys.development.json",
   production: "keys.production.json",
   staging: "keys.staging.json"
]

apply from: project(':react-native-keys').projectDir.getPath() + "/RNKeys.gradle"

reference: https://github.com/numandev1/react-native-keys/blob/b2702ac66460a2d0103c450e08d4bfd32cf7832b/example/android/app/build.gradle#L4C1-L8C2

after that run the build and let me know if you face any issue?

lukkimo commented 1 year ago

Thanks @numandev1 . I applied changes in app/build.gradle, clean project (gradlew clean), then build it, but ran into following error:

> Configure project :app

*********************************************************************************************************************
***                             If you are running build flavour then                                            ****
*** from app/build.gralde file, project.ext.keyFiles is missing key for debug flavour, please define it.
*********************************************************************************************************************

Choose keys.development.json file for react-native-keys to avoid stop any build process

5 actionable tasks: 5 up-to-date

FAILURE: Build completed with 2 failures.

1: Task failed with an exception.
-----------
* Where:
Script 'F:\PeakTower\Main projects\digivcard-app\node_modules\react-native-keys\android\RNKeys.gradle' line: 86

* What went wrong:
A problem occurred evaluating script.
> Cannot run program "/bin/sh": CreateProcess error=2, The system cannot find the file specified

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.
==============================================================================

2: Task failed with an exception.
-----------
* What went wrong:
A problem occurred configuring project ':app'.
> compileSdkVersion is not specified. Please add it to build.gradle

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.
==============================================================================

* Get more help at https://help.gradle.org

BUILD FAILED in 9s

error Failed to install the app. Make sure you have the Android development environment set up: https://reactnative.dev/docs/environment-setup.
Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=8081

FAILURE: Build completed with 2 failures.

1: Task failed with an exception.
-----------
* Where:
Script 'F:\PeakTower\Main projects\digivcard-app\node_modules\react-native-keys\android\RNKeys.gradle' line: 86

* What went wrong:
A problem occurred evaluating script.
> Cannot run program "/bin/sh": CreateProcess error=2, The system cannot find the file specified

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.
==============================================================================

2: Task failed with an exception.
-----------
* What went wrong:
A problem occurred configuring project ':app'.
> compileSdkVersion is not specified. Please add it to build.gradle

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.
==============================================================================

* Get more help at https://help.gradle.org

BUILD FAILED in 9s

    at makeError (F:\PeakTower\Main projects\digivcard-app\node_modules\execa\index.js:174:9)
    at F:\PeakTower\Main projects\digivcard-app\node_modules\execa\index.js:278:16
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async runOnAllDevices (F:\PeakTower\Main projects\digivcard-app\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\runOnAllDevices.js:82:7)
    at async Command.handleAction (F:\PeakTower\Main projects\digivcard-app\node_modules\@react-native-community\cli\build\index.js:108:9)
info Run CLI with --verbose flag for more details.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
numandev1 commented 1 year ago

@lukkimo I am MacBook user so I did not test this line in the window, sh does not available in the window, can you replace node_modules\react-native-keys\android\RNKeys.gradle:86 line with the line i provided below and let me know if it is working for the window or not

def proc = ["cmd", "/c", "set", "&&", exportCommand].execute()
lukkimo commented 1 year ago

@lukkimo I am MacBook user so I did not test this line in the window, sh does not available in the window, can you replace node_modules\react-native-keys\android\RNKeys.gradle:86 line with the line i provided below and let me know if it is working for the window or not

def proc = ["cmd", "/c", "set", "&&", exportCommand].execute()

Build issue is addressed, but still can't get my api key string!

import RNKeys from 'react-native-keys';

export const places_API_KEY = RNKeys.secureFor('GOOGLE_PLACES_API_KEY');
console.log('*********** ===> ', places_API_KEY);

export const reverseGeocodingURL = (
    lat: number,
    lng: number,
    api_key: string = places_API_KEY,
) =>
    `https://maps.googleapis.com/maps/api/geocode/json?latlng=${lat},${lng}&key=${api_key}`;

my keys.development.json:

{
    "secure": {
        "GOOGLE_PLACES_API_KEY": "some secure api key"
    },
    "public": {
        "APP_NAME": "example app"
    }
}
numandev1 commented 1 year ago

@lukkimo can we both see this issue on zoom or TeamViewer, i don't have a windows machine, hopefully, this issue will not take much time.

numandev1 commented 1 year ago

@lukkimo ?

numandev1 commented 1 year ago

@lukkimo is there any update?πŸ‘€

raulangelj commented 1 year ago

I am facing the same issue. On my windows machine when I try to get the key ether from secure or public it is not finding the value πŸ˜” it is not showing any error but only returning empty value for all the keys. I have change the proc var mention above but it is still not retrieving the keys from file

numandev1 commented 1 year ago

@raulangelj can we both see this issue on zoom or TeamViewer, i don't have a windows machine, hopefully, this issue will not take much time.

raulangelj commented 1 year ago

@numandev1 sure! Let me send you a email and we can arrange a call later today.

numandev1 commented 1 year ago

@raulangelj muhammadnuman70@gmail.com is my email

numandev1 commented 1 year ago

@raulangelj can you test #48 PR?

numandev1 commented 1 year ago

@raulangelj @lukkimo can you test https://github.com/numandev1/react-native-keys/pull/48 PR?