I integrated supabase with react-native I followed this article
But I couldn't signUp
import AsyncStorage from '#react-native-async-storage/async-storage'
import { createClient } from '#supabase/supabase-js'
import { SUPABASE_URL, SUPABASE_ANON_KEY } from '../constants'
export const supabase = createClient(SUPABASE_URL, SUPABASE_ANON_KEY, {
localStorage: AsyncStorage as any,
})
const signup = async (email, password)=>{
const { user, error } = await supabase.auth.signUp({
email,
password,
})
if(error){
console.log(error);
// Object {
// "message": "Unable to validate email address: invalid format",
// "status": 422,
// }
return
}
return user;
}
When I Invoke signup function it prints
Unable to validate email address: invalid format
I had a similar issue with auth.generateLink. It turned out that my arguments were in the wrong order.
Related
I've been working on the user registration of my React-Redux project (I'm really new to Redux), and I'm having trouble with registering Users with error handling...
My curriculum teaches nothing on using Redux with React (which is what my project does) to send data to an backend database.
I have been using useState for setting both the current user (currentUser, onLogin) and any errors (errors, setErrors) inside of UserInput.jsx, and I'm trying to move that functionality over to usersSlice.js.
Right now, I am trying to set my User object to be the action.payload. I also need to deal with how to pass the new User's info from my form, to my Slice.
Any solutions?
My code:
usersSlice.js
import { createAsyncThunk, createSlice } from "#reduxjs/toolkit";
export const signup = createAsyncThunk("users/signup", async ({username, password}, thunkAPI) => {
await fetch("/signup", {
method: "POST",
headers: headers,
body: JSON.stringify({user: {username, password}})
}).then((data) => {
data.json().then((data) => {
if(data.errors){
return thunkAPI.rejectWithValue(data.errors);
} else{
// Find a way to set the current user!!!
return data;
}
})
})
});
const usersSlice = createSlice({
name: "users",
initialState: {
user: [], // This should be an SINGLE User Object!!!
errorMessage: null,
status: 'idle',
},
reducers: {
userLogin(state, action){
state.user.push(action.payload);
},
userLogout(state){
state.user = [];
},
},
extraReducers(builder){
// Omit extraReduxers logic
}
});
UserInput.jsx:
function UserInput({onLogin, username, setUsername, password, setPassword, errors, setErrors}){
const dispatch = useDispatch();
function handleSubmit(e){
e.preventDefault();
const user ={
username: username,
password: password
}
dispatch(signup(user));
if(user.errors) { // Returns null due to the user object above...
setErrors(user.errors);
}
else{
setErrors(null);
onLogin(user); // setCurrentUser(user);
}
}
// Omit the signup form
}
export default UserInput;
I am working with react and firebase ver 9. As firebase offers limited field and I need to send some more data while registering a user. I saw that you can do this while uploading document whenever a user signs up. I have written the code for it but when I run it only users are registered but my document doesn`t get uploaded.
Here`s my code:
import { useState } from "react"
import { auth, db } from "../Authentication/firebaseConfig"
import { createUserWithEmailAndPassword } from "firebase/auth"
import {
collection,
setDoc,
addDoc,doc
} from "firebase/firestore";
export const useSignup = () => {
const [error, setError] = useState(null)
const signup = async (email, password, displayName) => {
setError(null)
const current_user = await createUserWithEmailAndPassword(auth, email, password, displayName);
const uid = current_user.user.uid;
await addDoc(collection(db, "users"), {
uid: uid,
displayName,
email,
})
.then((res) => {
console.log('user signed up:', res.user)
})
.catch((err) => {
setError(err.message)
})
}
return { error, signup }
}
As stated by #Danial, the error was produced by Cloud Firestore Rules that is set to false.
Sample Rule:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if false;
}
}
}
Sample Firestore rule above will prohibit you to read and write to any collection and document. Changing it to true allows the public to read and write to Firestore.
update 2, i logged the errors
update: I changed const db = getDatabase to const db getDatabase()
it printed to the console that the credentials were removed, but when i checked database, they still remain.
plus this error
I am trying to delete the user data as well as the authenticated data. I am successfully deleting the authenticated data, but it leaves the rest of the data in the database untouched. I have tried the following code:
import React from "react";
import { getAuth, deleteUser, onAuthStateChanged } from "firebase/auth";
import { remove, ref, getDatabase } from "firebase/database";
import { connectStorageEmulator } from "firebase/storage";
function DeleteUser() {
const auth = getAuth();
const user = auth.currentUser;
const db = getDatabase;
const del = ()=>{
if (user) {
remove(ref(db,'users'+user.uid))
.then(()=>{
console.log("credentials emoved")
})
.catch((error)=>{
console.log('failed')
});
deleteUser(user)
.then(() => {
console.log("User deleted");
})
.catch((error) => {
console.log("failed");
});
} else {
console.log("user is sighned out");
}
}
return (
<div>
<button onClick={del}>Delete</button>
</div>
);
}
export default DeleteUser;
I am using this bit to try removing the data, but I am getting some errors
remove(ref(db,'users'+user.uid))
.then(()=>{
console.log("credentials emoved")
})
.catch((error)=>{
console.log('failed')
});
The getDatabase() is a function but you are just assigning that to a variable instead of calling it.
const db = getDatabase;
// change that to
const db = getDatabase();
The recent login required essentially means user must have logged in (by entering their password, signing in by Google, etc) recently. If they have been logged in for a while then you'll need to reauthenticate the user (ask them to enter their password if using Email-password auth).
Checkout Firebase: recent login requested for more information.
I am building an app in NextJS which uses Firebase authentication. After successful authentication, I then wish to fetch additional details about the customer stored within a MongoDB instance (or create a new document for the customer on first login). Because I cannot access the firebase auth object inside getServerSideProps, I have redirected after firebase.auth() to /dashboard/${user.uid} which then getsServerSideProps using the uid passed to fetch customized/dynamic content.
dashboard.js
export default function DashboardAuth(props) {
const [user, loading, error] = useAuthState(firebase.auth())
if (user){
return window.location.href = `/dashboard/${user.uid}`
} else {
return <SignIn/>
}
}
/dashboard/[id].js
export async function getServerSideProps({ params }) {
let userData
console.log("Logging in ")
const { db } = await connectToDatabase();
console.log("connected to database, awaiting query response with uid")
const findUserResp = await db
.collection("users")
.findOne({'uid': params.id})
if(findUserResp ){
console.log("user data exists")
userData = {
uid: findUserResp.uid,
email: findUserResp.email,
displayName: findUserResp.displayName,
photoURL: findUserResp.photoURL,
storageQuoteRemaining: findUserResp.storageQuoteRemaining,
emailVerified: findUserResp.emailVerified,
currentPage: '/dashboard'
}
}else{
console.log("user data does not exist")
userData = {
uid:params.id,
email: '',
displayName: '',
photoURL: '',
storageQuoteRemaining: 0,
emailVerified: false,
currentPage: '/dashboard'
}
const addUserResp = await db
.collection("users")
.insertOne(userData)
}
console.log("returning userdata below")
console.log(userData)
return {
props: {
userData
}
}
}
export default function Dashboard(props) {
const [user, loading, error] = useAuthState(firebase.auth())
const userContext = getUserContext()
useEffect(() => {
userContext.handleCurrentUser(props.userData)
}, []);
if (user && props.userData.uid === user.uid){
return <Layout children={<CreateItem/>}/>
}else{
return <SignIn/>
}
}
My main issue is that after the user is initially added to mongodb on first login, immediatley after redirect to [id].js, I am presented with an error
Error: Error serializing `.userData._id` returned from `getServerSideProps` in "/dashboard/[id]".
Reason: `object` ("[object Object]") cannot be serialized as JSON. Please only return JSON serializable data types.
but on refresh this disappears.
Also I don't like how I have written my redirect but useRouter does not work. Any advice on how to better do this would be appreciated.
Looks like your first issue is related to what is being said here - https://github.com/vercel/next.js/issues/11993#issuecomment-617375501. The solve being to:
JSON.parse(JSON.stringify(findUserResp)) which is the data returned.
You should do a middleware solve (NextJS 12) as explained here or a redirect key inside your getServerSeideProps if using older than NextJS 12
if (user) {
return {
redirect: {
destination: '/dashboard/${user.uid}',
permanent: false,
},
}
I'm trying to sign up a new user with email and password using Firebase.
Below you can see my Vue method.
signup() {
if (!this.validate()) return
const auth = getAuth()
createUserWithEmailAndPassword(auth, this.email, this.password)
.then(() => {
console.log("Signup successful!")
})
.catch((error) => {
const errorMessage = error.message
console.error("Signup error! ", errorMessage)
})
}
Right below my script tag I have this import:
import { getAuth, createUserWithEmailAndPassword } from "#/firebase.js"
And in my firebase.js file I have this code:
import { initializeApp } from "firebase/app"
import { getAuth, createUserWithEmailAndPassword } from "firebase/auth"
const firebaseConfig = {
// here I pasted the config object I got from Firebase
}
initializeApp(firebaseConfig)
export { getAuth, createUserWithEmailAndPassword }
When I try to sign a new user up, I get this printed out in the console:
POST https://identitytoolkit.googleapis.com/v1/accounts:lookup?key=AIzaSyDmpWucdj9MuwM5mvjA5_TKMCFlsUXUGpg 400
Signup successful!
I can see that I have a new user registered in my Firebase console. Why is this error showing up then?