Getting Unhandled Exception: [cloud_firestore/permission-denied]. I have checked everything was fine in firebase - flutter

Hello Guys I had created the flutter application in which when a user pressed signup button then they will be checked that provided email exists in the firestore database or not if no then they will be move to next screen. I am getting this [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: [cloud_firestore/permission-denied] The caller does not have permission to execute the specified operation. exception even everything looks fine in my code and firestore configuration
Here is my firestore database rules:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if request.auth != null;
}
}
}
Here is my project level build.gradle:
buildscript {
ext.kotlin_version = '1.6.10'
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:7.1.2'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath 'com.google.gms:google-services:4.3.13'
}
}
allprojects {
repositories {
google()
mavenCentral()
}
}
rootProject.buildDir = '../build'
subprojects {
project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
project.evaluationDependsOn(':app')
}
task clean(type: Delete) {
delete rootProject.buildDir
}
Here is my app-level build.gradle
def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
localPropertiesFile.withReader('UTF-8') { reader ->
localProperties.load(reader)
}
}
def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}
def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
flutterVersionCode = '1'
}
def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
flutterVersionName = '1.0'
}
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
android {
compileSdkVersion flutter.compileSdkVersion
ndkVersion flutter.ndkVersion
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
}
defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId "com.recipedia.fyp.recipedia"
// You can update the following values to match your application needs.
// For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-build-configuration.
minSdkVersion 21
targetSdkVersion flutter.targetSdkVersion
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
}
buildTypes {
release {
// TODO: Add your own signing config for the release build.
// Signing with the debug keys for now, so `flutter run --release` works.
signingConfig signingConfigs.debug
}
}
}
flutter {
source '../..'
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
implementation platform('com.google.firebase:firebase-bom:31.0.3')
}
Here is my signup code:
onPressed: () async {
if (nameTextController.text.isEmpty) {
displayToastMessage(
"Please enter name", context);
} else if (nameTextController.text.length < 3) {
displayToastMessage("Name must be atleast 3 characters", context);
} else if (nameTextController.text.contains(RegExp(r'[0-9]'))) {
displayToastMessage("Numbers and special characters cannot be included", context);
} else if (emailTextController.text.isEmpty) {
displayToastMessage("Please enter email", context);
} else if (!emailTextController.text.contains('#')) {
displayToastMessage("Please enter a valid email", context);
} else if (passwordTextController.text.isEmpty) {
displayToastMessage("Please enter password", context);
} else if (passwordTextController.text.length < 6) {
displayToastMessage("Password must be at-least 6 Characters", context);
} else {
print('Before emailExists');
emailExists = await UserModel().checkIfEmailExists(email);
print('Email exist: $emailExists');
if (emailExists == true) {
snackBar(context, 'Email is already registered');
} else {
/*Move to next screen*/
}
}
}
User Model class checkIfEmailExist function
Future<bool> checkIfEmailExists(String email) async {
try {
var collectionReference = FirebaseFirestore.instance.collection('users');
var doc = await collectionReference.doc(email).get();
return doc.exists;
} catch (e) {
rethrow;
}
}

Solution: In Firestore database rule:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if true;
}
}
}

Related

Geofire setLocation failed DatabaseError: Permission denied

I am trying to set the location of a user by using GeoFire's setLocation but I am getting a permission denied error.
String uid = (Provider.of<UserData>(context, listen: false).uid);
print(uid);
bool? response = await Geofire.setLocation(uid, location.latitude ?? 0.0, location.longitude ?? 0.0);
print(response);
Here is the output:
I/flutter (23479): z9jbb4W9gvbfkOt9mnPhsJBNxSX2
I/TAG (23479): setLocation
W/RepoOperation(23479): setValue at /users/z9jbb4W9gvbfkOt9mnPhsJBNxSX2 failed: DatabaseError: Permission denied
I/flutter (23479): false
Here are my gradle files:
android/build.gradle
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'com.android.support:multidex:1.0.3'
implementation 'com.google.firebase:firebase-core:16.0.0'
implementation 'com.google.firebase:firebase-auth:16.0.1'
implementation 'com.google.firebase:firebase-database:12.0.1'
implementation 'com.google.firebase:firebase-storage:12.0.1'
implementation 'com.google.firebase:firebase-appcheck:16.0.0'
implementation 'com.firebase:geofire-android:2.3.1'
}
app/build.gradle
dependencies {
classpath 'com.android.tools.build:gradle:4.1.0'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath 'com.google.gms:google-services:4.0.1'
}
and here are my database rules on firestore:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if request.auth != null;
}
match /users/{userId}/{documents=**} {
allow read, write: if request.auth != null && request.auth.uid == userId;
}
}
}
I have tried setting the rules to True for everything and still get the same error.

How to set darkmode in webview using jetpack compose?

I try to enable dark mode on webview, which is not working, and also setForceDark is deprecated.
I am looking solution to enable dark mode on web view using jetpack compose
package com.blogspot.boltuix
import android.annotation.SuppressLint
import android.content.res.Configuration
import android.os.Bundle
import android.view.ViewGroup
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.viewinterop.AndroidView
import androidx.webkit.WebSettingsCompat
import androidx.webkit.WebViewFeature
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
WebViewPage("https://www.boltuix.com/")
}
}
}
#SuppressLint("SetJavaScriptEnabled")
#Composable
fun WebViewPage(url: String){
val context = LocalContext.current
//The Configuration object represents all of the current configurations, not just the ones that have changed.
val configuration = LocalConfiguration.current
when (configuration.orientation) {
Configuration.ORIENTATION_LANDSCAPE -> {
Toast.makeText(context, "landscape", Toast.LENGTH_SHORT).show()
}
else -> {
Toast.makeText(context, "portrait", Toast.LENGTH_SHORT).show()
}
}
// Adding a WebView inside AndroidView
// with layout as full screen
AndroidView(factory = {
WebView(it).apply {
layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
webViewClient = WebViewClient()
// to play video on a web view
settings.javaScriptEnabled = true
// to verify that the client requesting your web page is actually your Android app.
settings.userAgentString = System.getProperty("http.agent") //Dalvik/2.1.0 (Linux; U; Android 11; M2012K11I Build/RKQ1.201112.002)
// feature 1 : dark mode (auto system setup)
if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
WebSettingsCompat.setForceDark(settings, WebSettingsCompat.FORCE_DARK_ON)
}
loadUrl(url)
}
}, update = {
it.loadUrl(url)
})
}
App-level Gradle file:
plugins {
id 'com.android.application'
id 'org.jetbrains.kotlin.android'
}
android {
namespace 'com.blogspot.boltuix'
compileSdk 33
defaultConfig {
applicationId "com.blogspot.boltuix"
minSdk 24
targetSdk 33
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
vectorDrawables {
useSupportLibrary true
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
buildFeatures {
compose true
}
composeOptions {
kotlinCompilerExtensionVersion '1.2.0-beta01'
}
packagingOptions {
resources {
excludes += '/META-INF/{AL2.0,LGPL2.1}'
}
}
}
dependencies {
implementation 'androidx.core:core-ktx:1.8.0'
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.5.0'
implementation 'androidx.activity:activity-compose:1.5.0'
implementation "androidx.compose.ui:ui:1.3.0-alpha01"
implementation "androidx.compose.ui:ui-tooling-preview:1.3.0-alpha01"
implementation 'androidx.compose.material3:material3:1.0.0-alpha14'
testImplementation 'junit:junit:4.13.2'
implementation "androidx.webkit:webkit:1.5.0-beta01"
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
androidTestImplementation "androidx.compose.ui:ui-test-junit4:1.3.0-alpha01"
debugImplementation "androidx.compose.ui:ui-tooling:1.3.0-alpha01"
debugImplementation "androidx.compose.ui:ui-test-manifest:1.3.0-alpha01"
}
I tested OS 11 and 13 - WEB VIEW is working, but not changing dark mode.
This is what I did...
Added this dependency in build.gradle.
implementation "androidx.webkit:webkit:$webkitVersion"
Declare the object below. It is responsible to provide the correct Configuration object in according to the Dark Mode.
object ConfigurationUtil {
fun getConfiguration(context: Context): Configuration {
/**
* issue tracker : https://issuetracker.google.com/issues/170328697
* Web view resets uiMode (Day/Night) in Configuration
*/
val configuration = context.resources.configuration
val configurationNighMode = configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
val appCompatNightMode = AppCompatDelegate.getDefaultNightMode()
val newUiModeConfiguration = when {
configurationNighMode == Configuration.UI_MODE_NIGHT_NO && appCompatNightMode == UiModeManager.MODE_NIGHT_YES -> {
Configuration.UI_MODE_NIGHT_YES or (configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK.inv())
}
configurationNighMode == Configuration.UI_MODE_NIGHT_YES && appCompatNightMode == UiModeManager.MODE_NIGHT_NO -> {
Configuration.UI_MODE_NIGHT_NO or (configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK.inv())
}
else -> null
}
if (newUiModeConfiguration != null) {
val fixedConfiguration = Configuration().apply {
configuration.uiMode = newUiModeConfiguration
}
context.createConfigurationContext(fixedConfiguration)
}
return configuration
}
}
Use the WebView inside of an AndroidView....
#Composable
fun WebViewScreen() {
AndroidView(
modifier = Modifier
.fillMaxSize()
.padding(16.dp),
factory = { context ->
object : WebView(context) {
init {
val assetLoader = WebViewAssetLoader.Builder()
.addPathHandler("/res/", WebViewAssetLoader.ResourcesPathHandler(context))
.build()
webChromeClient = WebChromeClient()
webViewClient = object : WebViewClient() {
override fun shouldOverrideUrlLoading(
view: WebView,
request: WebResourceRequest
): Boolean {
return false
}
override fun shouldInterceptRequest(
view: WebView,
request: WebResourceRequest
): WebResourceResponse? {
return assetLoader.shouldInterceptRequest(request.url)
}
}
setBackgroundColor(0)
val configuration = ConfigurationUtil.getConfiguration(context)
if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
when (configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK) {
Configuration.UI_MODE_NIGHT_YES -> {
WebSettingsCompat.setForceDark(
settings,
WebSettingsCompat.FORCE_DARK_ON
)
}
Configuration.UI_MODE_NIGHT_NO, Configuration.UI_MODE_NIGHT_UNDEFINED -> {
WebSettingsCompat.setForceDark(
settings,
WebSettingsCompat.FORCE_DARK_OFF
)
}
else -> {
WebSettingsCompat.setForceDark(
settings,
WebSettingsCompat.FORCE_DARK_AUTO
)
}
}
}
settings.allowFileAccess = false
settings.allowContentAccess = false
setDownloadListener { url, _, _, _, _ ->
url?.let {
try {
context.startActivity(
Intent(Intent.ACTION_VIEW).apply {
data = Uri.parse(it)
}
)
} catch (e: Exception) {
Toast.makeText(context, "Error opening link", Toast.LENGTH_LONG)
.show()
}
}
}
loadDataWithBaseURL(
ResourceBaseUrl,
"This is a web view. Check if it is working on Dark Mode",
"text/html",
"UTF-8",
null
)
}
}
}
)
}

How to fix "Your Android App Bundle is signed with the wrong key"?

I'm trying to upload my appbundle but all the time I get this error "Your Android App Bundle is signed with the wrong key". I have already reseted my key with google, waited the 48h hours but I still got the error. I am using the new keystore.jks file on my key.properties, the same one I send as a pem file to google.
here is my key.properties:
storePassword=******
keyPassword=******
keyAlias=key
storeFile=/Users/ricardooscarkanitz/Projects/Apps/e_ai_casimiro_key/keystore.jks
and my build.gradle:
def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
localPropertiesFile.withReader('UTF-8') { reader ->
localProperties.load(reader)
}
}
def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in
the local.properties file.")
}
def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
flutterVersionCode = '2'
}
def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
flutterVersionName = '2.0'
}
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
def keystoreProperties = new Properties()
def keystorePropertiesFile = rootProject.file('key.properties')
if (keystorePropertiesFile.exists()) {
keystoreProperties.load(new FileInputStream(keystorePropertiesFile))
}
android {
compileSdkVersion 29
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
}
lintOptions {
disable 'InvalidPackage'
}
defaultConfig {
// TODO: Specify your own unique Application ID
(https://developer.android.com/studio/build/application-id.html).
applicationId "br.com.kanitzdev.e_ai_casimiro"
minSdkVersion 16
targetSdkVersion 29
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
multiDexEnabled true
}
signingConfigs {
release {
keyAlias keystoreProperties['keyAlias']
keyPassword keystoreProperties['keyPassword']
storeFile keystoreProperties['storeFile'] ? file(keystoreProperties['storeFile']) :
null
storePassword keystoreProperties['storePassword']
}
}
buildTypes {
release {
signingConfig signingConfigs.debug
}
}
}
flutter {
source '../..'
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
}
apply plugin: 'com.google.gms.google-services'
I have already tried to upload the key.jks file that I first got from keytool but it shows me the same error. Do you guys have any Idea on how to fix it?
You're still trying to generate the app bundle via the debug mode.
Instead of :
signingConfig signingConfigs.debug
Try this :
signingConfig signingConfigs.release

After updating to ionic 5 and Angular 9 , error TS2698: Spread types may only be created from object types

After updating to Ionic 5 and Angular 9, I get the following error:
error TS2698: Spread types may only be created from object types.
ERROR in src/app/providers/firestore-db.service.ts:19:13 - error
TS2698: Spread types may only be created from object types. [ng] 19
...doc.payload.doc.data()
This is the related code:
import { Injectable } from '#angular/core';
import { AngularFirestore } from '#angular/fire/firestore';
import { map } from 'rxjs/operators';
#Injectable({
providedIn: 'root'
})
export class FirestoreDbService {
constructor(private db: AngularFirestore) { }
getAllData(collectionId) {
/* return this.db.collection('product').valueChanges(); */
return this.db.collection(collectionId).snapshotChanges().pipe(
map(docArray => {
return docArray.map(doc => {
return {
id: doc.payload.doc.id,
...doc.payload.doc.data()
}
})
})
)
}
async insertData(collectionId, data) {
try {
const result = await this.db.collection(collectionId).add(data);
return result;
} catch (error) {
throw new Error(error);
}
}
async getDataById(collectionId, docId) {
try {
const result = await this.db.collection(collectionId).doc(docId).ref.get();
if (result.exists) {
return result.data();
} else {
throw new Error('Data not found with given id');
}
} catch (error) {
throw new Error(error);
}
}
async updateData(collectionId, docId, updatedData) {
try {
const result = await this.db.doc(`${collectionId}/${docId}`).update(updatedData);
return result;
} catch (error) {
throw new Error(error);
}
}
async deleteData(collectionId, docId) {
try {
const result = await this.db.doc(`${collectionId}/${docId}`).delete();
return result;
} catch (error) {
throw new Error(error);
}
}
}
I solved the issue by downgrading typescript from 3.7.5 to 3.6.4
npm install typescript#3.6.4
and make sure it is also 3.6.4 in the package.json

Gatling Gradle Build to add scala Simulations and Config files as Fatjar

I have written the build.gradle which is compiling and generating the fatjar. which include the gatling simulation files in the Fatjar. But not able to execute the fatjar. Which says " Main class not found".
Below is the build.gradle
buildscript {
repositories {
jcenter()
maven { url "https://oss.sonatype.org/content/groups/public" }
}
dependencies {
classpath "com.github.mperry:gradle-gatling-plugin:0.2-SNAPSHOT"
}
}
//mainClassName = "simulations.basic.KafkaSimulation2"
apply plugin: 'scala'
apply plugin: "com.github.mperry.gatling"
defaultTasks "build"
ext {
}
repositories {
jcenter()
maven { url "https://oss.sonatype.org/content/groups/public" }
}
/*
gatling {
list true
dryRun false
include "simulations.basic.KafkaSimulation2" // include all simulations in this package
// exclude ".*"
}
test.dependsOn gatlingRun
*/
dependencies {
compile 'org.apache.commons:commons-io:1.3.2'
compile 'org.codehaus.jackson:jackson-mapper-asl:1.9.13'
compile 'org.scala-lang:scala-library:2.11.7'
compile 'org.apache.kafka:kafka-clients:0.8.2.0'
testCompile 'io.gatling.highcharts:gatling-charts-highcharts:2.1.+'
compile "com.github.mperry:gradle-gatling-plugin:0.2-SNAPSHOT"
compile files('src/main/resources/lib/gatling-kafka-assembly-0.1.0-SNAPSHOT.jar')
// testCompile 'simulations.basic.KafkaSimulation2'
runtime fileTree(dir: 'src', include: '*.scala')
// runtime fileTree(dir: 'conf', include: '*.conf')
}
jar {
manifest {
attributes(
'Main-Class': 'KafkaSimulation2',
)
}
}
sourceSets {
api
impl
main {
scala {
srcDirs = ['src/test/scala', 'src/test/scala']
}
}
}
sourceSets {
api
impl
}
jar {
from sourceSets.api.output
from sourceSets.impl.output
}
task fatJar(type: Jar) {
manifest.from jar.manifest
classifier = 'confubers'
destinationDir new File("$buildDir")
into('lib'){
from "$projectDir/conf"
}
from {
configurations.compile.collect {
it.isDirectory() ? it : zipTree(it)
}
configurations.runtime.collect { it.isDirectory() ? it : zipTree(it) }
} {
exclude "META-INF/*.SF"
exclude "META-INF/*.DSA"
exclude "META-INF/*.RSA"
}
with jar
}
artifacts {
archives fatJar
}
Looks like all you have to do is provide a fully-qualified class name in the Main-Class attribute, instead of just the name: simulations.basic.KafkaSimulation2 instead of just KafkaSimulation2.