When i trying to wirte data in firebase db take an exception - javascript

I have got an a react native app, i need to save data in db with user's token. How can i do it?
It's my auth firebase:
Also i need an a real time db to save here data and user's token:
I have a registration of user, and i know that i need here to make an a api into realtime db mthod PUT for url: https://[PROJECT ID]-default-rtdb.firebaseio.com/, but how can i do it i didn't know, pls help:
const hanldeRegister = () => {
if (password !== confirmPassword){
alert("The passwords are different!")
}
else{
setIsLoading(true)
axios({
method: 'POST',
url: 'https://identitytoolkit.googleapis.com/v1/accounts:signUp',
params: {
key: 'A',
},
data: {
email,
password,
},
}).then((res) => {
axios({
method: 'POST',
url: 'https://identitytoolkit.googleapis.com/v1/accounts:update',
params: {
key: 'A',
},
data: {
idToken: res.data.idToken,
displayName: name + ' ' + surname
}
}).then((r) => {
setUser({...r.data, idToken: res.data.idToken})
}).catch(e => {
console.log(e, 'updaate profile error');
alert(e.message);
})
.finally(() => {
setIsLoading(false);
})
console.log(res.data)
})
.catch((error) => console.log(error.response.request._response))
}
}

Rather than attempt to explain the process in great depth, because that would be reiterating the already existing docs.
Here is a link to the getting started docs regarding firestorage.
https://firebase.google.com/docs/storage/web/start
You should also checkout the starting docs, in regards to setting up firebase with web.
https://firebase.google.com/docs/web/setup
Thi will guide you through the process of setting up and intergrading firebase with your JavaScript application.

Related

Is there a way to allow headers when doing a fetch request to the Stripe Billing Portal?

I have an app that allows a logged in user to upgrade their account by subscribing to a 'basic' or 'premium' subscription. Once they subscribe they can then click on a "Manage Billing" button and it will take them to a Billing Portal where they can cancel, or upgrade their subscription.
The issue that I am running into is that I am trying to make the customer be dynamic. So where it says customer: 'cus_IZvOkC9VtDRXUi', I can instead have something like customer: customer, where customer is a dynamic variable.
router.post('/customer-portal', async (req, res) => {
// const id = req.body.id
// console.log(req.body, 'ID HERE')
// User.findBy({ id })
// .then(found => {
// console.log(found, 'I FOUND YOU')
// })
// .catch(error => {
// console.log(error, 'error here on portal')
// })
// whatever customer is logged in, this needs to be the CUSTOMER line 45 - DYNAMIC
const session = await stripe.billingPortal.sessions.create({
customer: 'cus_IZvOkC9VtDRXUi',
return_url: 'http://localhost:3000/my-profile',
})
res.redirect(session.url)
const sessionURL = session.url
console.log(sessionURL,'this is session')
// console.log(session, 'this is the session')
// console.log(req,'this is req')
// res.status(302).redirect(sessionURL)
// next()
})
The problem is that when I try and send headers (so I can send the ID of the currently logged in user ID from the frontend), the req.body is an empty object and I can't see the ID. See frontend code here:
const state = useSelector(state => state)
const id = state.auth.user.id
const handlePortal = (e) => {
e.preventDefault()
console.log(id, 'JSJDHDHDHDHDHDHDH')
return fetch('http://localhost:5000/api/stripe/customer-portal', {
// mode: 'no-cors',
method: 'post',
// headers: {
// 'Content-Type': 'application/json',
// },
body: JSON.stringify({
id: id
})
})
.then((response) => {
console.log(response, 'this is the response')
const url = response.url
console.log(url, 'URURUIRIRLL')
// express cant force the front-end to redirect.
window.location = url
// return response.json()
})
.catch((error) => {
console.log(error.message, 'There was a dumb error')
})
}
The headers are commented out right now, but as soon as I add them in, I get this error:
CORS ERROR
What is super weird is this exact setup works when I create a Stripe Customer. I send the ID from the frontend at id: currentUserId. See code below:
const state = useSelector(state => state)
const currentUserId = state.auth.user.id
const handleSubmit = e => {
e.preventDefault()
return fetch(`http://localhost:5000/api/stripe/create-customer/`, {
method: 'post',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: email,
id: currentUserId
})
})
.then((response) => {
console.log(response, 'this is response handlesubmit')
return response.json()
})
.then((result) => {
setCustomer(result.customer)
console.log(result, 'THIS IS RESULT on register CUSTOMER')
})
}
Then on the backend I have my /create-customer endpoint and pull the id by req.body.id, then find the currently logged in user, then add the customer id given by stripe to the user table. This works fine without any CORS issues. See backend endpoint here:
router.post('/create-customer', async (req, res) => {
const id = req.body.id
const customer = await stripe.customers.create({
email: req.body.email,
})
res.send({ customer })
User.findBy({ id })
.then(found => {
User.updateStripeID(id, changes)
.then(changedUser => {
console.log(changedUser, 'changed!', id, changes)
})
.catch(error => {
console.log(error, 'this is stupid')
})
})
.catch(error => {
console.log(error, 'there was an error on catch', error.message)
})
})
So my question is, how do I get this working? Or how do I get my currently logged in user to the backend another way?
Couple things to note:
I do have a CORS extension that I am using in Chrome. The reason is that the my frontend will not even redirect to the Billing Portal and will throw an 'access-control-allow-origin' error. I have tried every solution on every stack overflow page about this. Literally. Spent days trying almost every solution about CORS issues. They do not work and I hope that when the app deploys live it won't have that redirect issue.
If you could not already tell my frontend is React, backend is NodeJS, and I am using Knex/SQLite3 for database tables/migrations/seeds etc.
Any help would be appreciated!

Is there any way to create users with roles assigned in keycloak using node?

i was trying a code to upload all users to keycloak user list and it works well. i used an excel file to read then push each row into keycloak field but i was thinking to add roles to each user at the same time. when i try out this code it says role field does not exist in user and gives me error
this is my code
Read From Excel and store in an array
let path = 'http://localhost:8080/auth/admin/realms/msportal';
let _userTobeCreated = ReadFromExcel('./uploads/employees-roles.xlsx');
function ReadFromExcel(filename) {
let userTobeCreated = []
xlsxFile(filename).then((rows) => {
rows.forEach(row => {
let userObject = {
username: row[0],
lastName: row[1],
firstName: row[2],
email: row[3],
roles: row[4].split(',')
}
userTobeCreated.push(userObject);
});
})
return userTobeCreated;
}
create function
function CreateKCBulkUser(user) {
let urlCreateUser = `${path}/users`;
return axios({
method: 'post',
url: urlCreateUser,
data: JSON.stringify(user),
headers: {
'content-type': 'application/json',
'Authorization': `Bearer ${kc_accessToken}`
}
})
.then(function (response) {
console.log("User created!!");
_userlists = response.data;
})
.catch(function (error) {
console.log(error);
});
}
Calling Function
_usersToBeCreated.forEach((v)=>{
CreateKCBulkUser(v);
})
excel file
Role is not a part of user entity. First you must create role entity and then you need to create role-mapping. See API doc.
BTW: role is vague definition, because Keycloak has real roles/client roles + I would use keycloak-nodejs-admin-client instead of plain axios requests.

Where to put API session auth token in SDK request methods?

I am using the ConnectyCube React Native SDK and have obtained an app auth token using their API. This token is required when making further requests - for example when logging in as a user. Their documentation says:
Upgrade session token (user login)
If you have an application session token, you can upgrade it to a user session by calling login method:
var userCredentials = {login: 'cubeuser', password: 'awesomepwd'};
ConnectyCube.login(userCredentials, function(error, user) {
});
The problem is it that when I use this method, I get an error in response saying 'Token is required'.
If I were interfacing with a REST API, I would put the token in the header of the request, but obviously in this instance I can't. So the question is, where do I put the token? I have it, the documentation just doesn't tell you how to use it! Any help appreciated.
Ok I came up with a fix. First of all I just tried passing the auth token in to the userCredntials object in the same way as in the documentation for social auth, that is absent from the description in my above code snippet taken from their docs.
Then I Promisified the API calls from within useEffect inside an async function to make sure everything was happening in the right order, and it works:
export default function App() {
const createAppSession = () => {
return new Promise((resolve, reject) => {
ConnectyCube.createSession((error, session) => {
!error
? resolve(session.token)
: reject(error, '=====1=====');
});
})
}
const loginUser = (credentials) => {
return new Promise((resolve, reject) => {
ConnectyCube.login(credentials, ((error, user) => {
!error
? resolve(user)
: reject(error, '=====2=====');
}));
})
}
useEffect(() => {
const ccFunc = async () => {
ConnectyCube.init(...config)
const appSessionToken = await createAppSession();
const userCredentials = { login: 'xxxxx', password: 'xxxxxxx', keys: { token: appSessionToken } };
const user = await loginUser(userCredentials);
console.log(user);
}
ccFunc()
}, []);
Hope it works....
please implement it by yourself...just take an understanding from code below.
code says: send the username and password to api...if all ok then authenticate else throw error ...if all ok..then store the returned token is asyncStorage...you can create the storage by any name you like...and use the token eveywhere in your app.
SignInUser = async () => {
this.setState({
username: this.state.username,
password:this.state.password,
})
if(this.state.username && this.state.password !== null){
try{
this.setState({
loading:true
})
const response = await fetch('YOUR API', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
username: this.state.username,
password: this.state.password
})
});
var promiseResponse = await response.json()
console.log(promiseResponse.token);
try {
await AsyncStorage.setItem('STORE_YOUR_LOGIN_TOKEN_HERE', JSON.stringify(promiseResponse.token));
console.log('Token Stored In Async Storage');
let tokenFromAsync = await AsyncStorage.getItem('STORE_YOUR_LOGIN_TOKEN_HERE');
console.log('Getting Token From Async...')
tokenFromAsync = JSON.parse(tokenFromAsync)
if(tokenFromAsync !== null){
console.log(tokenFromAsync);
this.setState({
loading:false
})
this.props.navigation.navigate('Tabnav');
}
} catch (error) {
// saving error
console.log(`ERROR OCCURED ${error}`)
}
//this.props.navigation.navigate('Tabnav')
} catch(error){
console.log(`COULDN'T SIGN IN ${error}`)
}
} else {
this.setState({
msg:'Invalid Credentials',
label:'red'
});
}
}
This is how i got the login to work in their sample react native app 1. i created a credentials object like this in my custom login function in src>components>AuthScreen>AuthForm.js
var credentials = {id:'',login: this.state.login,password: this.state.password}
2.I used their _signIn(credentials) function and set the 'id' attribute of my credentials object after their UserService.signin(credentials) resolved with a user object. (the resolved user object contained the logged-in user's id i.e user.id). Then it worked. This is how the code looked for the signin after the little tweak.
loginUser() { //my custom signin function
var credentials = {id:'',login: this.state.login,password: this.state.password} //my credentials object
this._signIn(credentials)
}
_signIn(userCredentials) { //their signin function
this.props.userIsLogging(true);
UserService.signin(userCredentials)
.then((user) => {
userCredentials.id = user.id //setting id of my credentials object after promise resolved
ChatService.connect(userCredentials) //using my credentials object with id value set
.then((contacts) => {
console.warn(contacts)
this.props.userLogin(user);
this.props.userIsLogging(false);
Actions.videochat(); //login worked
})
.catch(e => {
this.props.userIsLogging(false);
alert(`Error.\n\n${JSON.stringify(e)}`);
})
})
.catch(e => {
this.props.userIsLogging(false);
alert(`Error.\n\n${JSON.stringify(e)}`);
})
}

How to login user to spring-security app using Vue.js?

Hi it's my first post on stack overflow. I want to separate back-end from front-end and create REST API using my Spring Boot app. I use spring-security to login. It use something called JSESSION_ID but how to login and authorize users using Vue.js? I want to make form for login to my service and authorize request with JSESSION_ID.
It's my first app in Vue.js. I try to use code from tutorials and docs but it didn't solve my problem. I also have issues with CORS.
export default {
name: 'Login',
data(){
return{
username: '',
password: '',
error: false
}
},
updated(){
if (localStorage.token){
this.$router.replace(this.$route.query.redirect || '/')
}
},
methods:{
login(){
this.$http.post('http://localhost:8080/login', { username: this.username, password: this.password })
.then(request => this.loginSuccessful(request))
.catch(() => this.loginFailed())
},
loginSuccessful (req) {
if (!req.data.token) {
this.loginFailed();
return
}
this.error = false;
localStorage.token = req.data.token;
this.$router.replace(this.$route.query.redirect || '/')
},
loginFailed () {
this.error = 'Login failed!';
delete localStorage.token
}
}
}
I expect to login and authorize users from Vue.js using REST Spring-Boot API.
The problem is that you try to pass the object { username: this.username, password: this.password } as the data to the request, but you do not specify the Content-Type, which probably defaults to 'text/html' or 'application/json'. You could try to first convert that into form data and then pass it to the request, here is an example with AXIOS:
login() {
let formData = new FormData();
formData.set("username", this.username);
formData.set("password", this.password);
AXIOS.post('/login', formData, {headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
.then((result) => {
this.loginSuccessful(result);
})
.catch((error) => {
this.loginFailed();
})
}
Perhaps it would also work without specifying the header, like AXIOS.post('/login', formData, null), haven't tried it.

How to save an axios request as json object?

I am building a web applications with offline capabilities and i want to save the API requests as json in localStorage and make the request when connection is available, i am using axios to make the API requests, so lets say i have this request
$axios.post(`/users/`, {username: 'user', password: 'supersecretpassword'})
.then(response => {
console.log(response);
})
.catch(error => {
});
what i want to do is get this request as an object and use that object later to make the request. is this possible? how?
Thank You.
localStorage does not allow saving functions, but what you could do is save the request options object and use with a slightly different but documented Axios syntax:
var requestParams = {
method: 'post',
url: '/users',
data: {
username: 'user',
password: 'supersecret password'
}
}
axios(requestParams).then(....)
You can then decide to keep requestParams in localStorage and use it whenever you wish.
You have to create a function for this:
function getUsers(){
return $axios.post(`/users/`, {username: 'user', password: 'supersecretpassword'})
.then(response => {
console.log(response);
})
.catch(error => {
});
}

Categories

Resources