i am trying to set some user data along with token ID in Cookie. Token is set perfectly and also in console.log output but my user JSON object is unable to set and shows me "object Object" as Cookies but my user data present in console.log. i think i am unable to convert JSON data into cookie. here is my code of nextjs and packages i use for this.
package use
js-cookies
nextjs - latest version
here is my API for user login
import db from "../../helpers/initDB";
import User from "../../models/User";
import bcrypt from 'bcryptjs'
import jwt from 'jsonwebtoken'
db.connect();
// eslint-disable-next-line import/no-anonymous-default-export
export default async (req,res)=>{
const {email,password} = req.body
try{
if(!email || !password){
return res.status(422).json({error:"All Fields Are Required"})
}
const user = await User.findOne({email})
if(!user){
return res.status(404).json({error:"user dont exists with that email"})
}
const doMatch = await bcrypt.compare(password,user.password)
if(doMatch){
const token = jwt.sign({userId:user._id},process.env.JWT_SECRET,{
expiresIn:"7d"
})
const {name,role,email} = user
res.status(201).json({token,user:{name,role,email}})
}else{
return res.status(401).json({error:"email or password dont match"})
}
}catch(err){
console.log(err)
}
}
db.disconnect();
my api is working fine and set the res.status with all my data.
here is code part where i am trying to set cookie
console.log(res2)
Cookie.set('user', res2.user);
Cookie.set('token', res2.token);
router.push('/dashboard/')
and here is my console.log output where user data and token is present
Object { token:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI2MWE4YzcwMGIxZmI3OWJmOGNjOWY3ZjUiLCJpYXQiOjE2Mzg1MTczODIsImV4cCI6MTYzOTEyMjE4Mn0.9T-B4c3xtsgCSGSWUMCZ_GU56FYC5VLeVDhGzAWiwjA", user: {…} }
user: Object { name: "mohit nagar", role: "user", email: "gujjarmaxx#gmail.com" }
: Object { … }
and here is my cookies
{
"Request Cookies": {
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI2MWE4YzcwMGIxZmI3OWJmOGNjOWY3ZjUiLCJpYXQiOjE2Mzg1MTY1NzcsImV4cCI6MTYzOTEyMTM3N30.PoBD03Qp-7-iN5yvnjvQfflTI5DO8z3Lqk3sMYZs0Y0",
"user": "[object Object]"
}
}
i don't know what i am doing wrong.
A value of a cookie must be a string. You can stringify your user object into JSON
Cookie.set('user', JSON.stringify(res2.user))
When you want to read your cookie you will parse the string
const user = JSON.parse(Cookie.get('user'))
Related
I'm new to web development and as part of a project have made a Django React Redux app. The frontentd has a component with form entry - when a form is submitted, the component calls an action that sends an axios request to a python twitter crawler script in the backend. The script returns a response containing a string array (the tweets are inside the array). I then try to dispatch the array contained in the response.data, as a payload to a reducer. However I keep getting an error saying that the payload of what I have dispatched is undefined.
This is the return statement of the python method that is called - corpus is a string array.
return JsonResponse({"results:": corpus})
This is the code for the action that sends a GET request to the python method. It's then returned the string array inside a json object.
// GET_TWEETS - get list of tweets from hashtag search
export const getTweets = (hashtag) => dispatch => {
axios
.get('http://localhost:8000/twitter_search', {
params: {text: hashtag}
})
.then(res => {
console.log(res.data); //check if python method returns corpus of tweets
//const results = Array.from(res.data.results);
dispatch({
type: GET_TWEET,
payload: res.data.results
});
})
.catch(err => console.log(err));
}
The console log shows that the object is returned successfully from the python script.
console log
This is the code for my reducer. I want my action to contain the string array and then assign that string array to 'tweets' in the state, so that I can return this to a component and then access the array from the component and then display contents of thisx array of tweets on the frontend
import { GET_TWEET } from '../actions/types';
const initialState = {
tweets: []
}
export default function(state = initialState, action) {
console.log(action.payload)
switch(action.type) {
case GET_TWEET:
return {
...state,
tweets: [...action.payload]
}
default:
return state;
}
}
Also, this is some of the code for the component that I want to receive the string array, I hope I have set this part up properly:
export class Tweets extends Component {
static propTypes = {
tweets: PropTypes.array.isRequired,
getTweets: PropTypes.func.isRequired
}
...
const mapStateToProps = state => ({
tweets: state.TweetsReducer.tweets
});
export default connect(mapStateToProps, { getTweets })(Tweets);
Here is the error I get from the console. Console logging the payload of the action also shows that its value is undefined: undefined error
I've been trying to solve this for several days now, but am completely lost and I have a hunch the solution to this is pretty simple...
I want to update the newly created User's data. The returned JSON is:
{
"user":{
"uid":"test123",
"displayName":null,
"photoURL":null,
"email":"test12#test.com",
"emailVerified":false,
"phoneNumber":null,
"isAnonymous":false,
"tenantId":null,
"providerData":[
{
"uid":"test12#test.com",
"displayName":null,
"photoURL":null,
"email":"test12#test.com",
"phoneNumber":null,
"providerId":"password"
}
],
"apiKey":"test123",
"appName":"[DEFAULT]",
"authDomain":"test123.firebaseapp.com",
"stsTokenManager":{
"apiKey":"test123",
"refreshToken":"test123",
"accessToken":"test123",
"expirationTime":1571238989357
},
"redirectEventId":null,
"lastLoginAt":"1571235389108",
"createdAt":"1571235389108"
},
"credential":null,
"additionalUserInfo":{
"providerId":"password",
"isNewUser":true
},
"operationType":"signIn"
}
This is my callout and update:
createUser = async (userData) => {
return await firebase.auth().createUserWithEmailAndPassword(userData.get('userName'), userData.get('password'))
.then((authData) => {
firebase.database().ref('users/' + authData.user.uid + '/').set({
fullName: userData.get('fullName'),
pictures: userData.get('pictures'),
phoneNumber: userData.get('phoneNumber')
});
})
};
Is it possible to add to the User table custom fields?
A few things are happening. It appears that userData can not be seen in the .then statement. So to solve this I attempted to pass in the userData JSON as a param. This did not work. I then broke out each value out of userData, saved it into a const and passed that value. This did not work.
I can see that userData has values in it before the .then statement. I am able to successfully create a new user with the right userName and password. This means to me either:
A - I am not passing the userData JSON correctly or
B - I am not allowed to pass data to firebase like I am doing
My end goal is to sign up a user and then take all of the data they input from a registration form (aka userData) and update the user table with it.
Articles I am using are:
https://firebase.google.com/docs/auth/web/manage-users
https://medium.com/mindorks/firebase-realtime-database-with-react-native-5f357c6ee13b
Main class that calls the createUser function:
const signUp = (dispatch) => {
return async (userData)=>{
try{
const response = await config.createUser(userData);
console.log('sign up resonse1: ' + response); //coming back as undefined
//todo:: figure out how to parse out the apikey out of response
await AsyncStorage.setItem('token', '123mockToken');
dispatch({type: 'sign_up', payload: '123mockToken'});
navigate('mainFlow');
} catch(e){
dispatch({type: 'add_error', payload: '' + e}); //we call dispatch anytime we want to update our state
}
}
};
I understand that the parameter userData holds all the data you want to use for creating the user ("all of the data they input from a registration form").
The following should work:
createUser = async userData => {
try {
const userCredential = await firebase
.auth()
.createUserWithEmailAndPassword(
userData.get('userName'),
userData.get('password')
);
const userId = userCredential.user.uid;
await firebase
.database()
.ref('users/' + userId + '/')
.set({
fullName: userData.get('fullName'),
pictures: userData.get('pictures'),
phoneNumber: userData.get('phoneNumber')
});
return userId; //As per your comment below
} catch (error) {
return error;
}
};
The createUserWithEmailAndPassword() method returns a UserCredential which contains a User.
I would like to create user data (name, email, phone number) in Firestore. This should be triggered with on create an authenticated user.
at functions-> src-> index.ts
// Sends email to user after signup
export { welcomeEmail } from './send_email';
// Saves user after signup
export { createUserDoc } from './save_user';
at functions-> src-> save_user.ts
// Firebase Config
import * as functions from "firebase-functions";
import * as firebase from "firebase-admin";
import {MD5} from "crypto-js";
export const createUserDoc = functions.auth.user().onCreate(event => {
const firebaseUser = event.data;
// Use gravatar as default if photoUrl isn't specified in user data
let fileEnding = "jpg";
let photoURL = `https://www.gravatar.com/avatar/${MD5(firebaseUser.email).toString().toLowerCase()}.jpg?s=1024&d=robohash`;
if (firebaseUser.photoURL) {
fileEnding = firebaseUser.photoURL.substr(firebaseUser.photoURL.lastIndexOf(".") + 1);
photoURL = firebaseUser.photoURL;
}
const fileName = `users/${firebaseUser.uid}/profile.${fileEnding}`;
const profilePhotoStorageOpts = {
destination: fileName,
metadata: {
contentType: `image/${fileEnding}`
}
};
const user = {
name: firebaseUser.displayName || "No Name",
email: firebaseUser.email,
photoUrl: `gs://${firebase.storage().bucket().name}/${fileName}`
};
return Promise.all([
firebase.storage().bucket().upload(photoURL, profilePhotoStorageOpts),
firebase.firestore().collection("users").doc(firebaseUser.uid).set(user)
]);
});
The goal was, for each created account I would now find a corresponding user document in Firestore and a profile image in the cloud storage.
instead I'm getting:
Property 'data' does not exist on type 'UserRecord'.ts(2339)
'Promise' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the lib compiler option to es2015 or later.ts(2585)
Help would be appreciated. Thanks
As you will see in the documentation for the onCreate method, the first parameter of the handler function is a UserRecord which does not have a data property.
So the first error you get is normal.
In your case, if you want, for example, to get the user's photoURL, you should do event.photoURL (Since event is of type UserRecord). Similarly, you will do event.uid to get the user's uid.
For the second error, you may have a look at https://stackoverflow.com/a/43122423/3371862 or How to resolve 'Build:'Promise' only refers to a type, but is being used as a value here.'
I'm working on a Vue frontend/Express backend application and am having an issue with a numbers in a JSON response 'arriving' at the frontend as null.
server:
db.boards.getUserBoards(user.user_id).then((boards) => {
let userBoards = [];
if (boards) userBoards = boards;
user.boards = userBoards;
const token = jwt.sign(JSON.stringify(user), config.secret);
res.json({ message: 'Token granted', token, user });
Where boards is an array such as:
"boards": [
{
"board_id": 1,
"name": "test"
}
]
This works fine in postman (that's where the above was directly copied from), but the response in my client application has a null value
see response. It seems to only affect the numerical values within the boards array, as the user object has an numerical id field that makes it across without issue.
client:
Axios.post(`${api}/api/stuff`, credentials)
.then(({data}) => { console.log(data) })
What am I missing?!
Is there a recommended way to handle data from data file in protractor scripts?
If I want to keep all the test data (like login details, user input values) in separate data file then what type of file should I use and how should I import them to my protractor scripts?
If suppose you need to work with json then:
Suppose your json for username and password of a login page looks like:
Example of JSON:
[
{
"username": "kishan",
"password": "patel"
}
]
Then you can simply import this to your code and access it as below.
describe ('Login Page Data Driven' , function() {
browser.ignoreSynchronization = true;
beforeEach(function(){
browser.get('your url');
browser.driver.manage().window().maximize();
});
it('To verify Login, using Data Driven Technique from Json file', function()
{
var testData = require('D:/json path'); //this is the path where your json is stored
var user= element(by.id("username"));
var password = element(by.id("password"));
user.sendKeys(testData[0].username);
password.sendKeys(testData[0].password);
});
This Is just an Example. I hope you can Relate and apply.
Try at your end & Let me know for more concerns.
I typically create a separate data file, and require it as needed in my specs. I have a working example on my github protractor-examples repo. Here's the jist:
// userData.js
var UserData = {
testUser : {'username': 'test', 'password': 'test'},
};
module.exports = UserData;
then in my spec...
// nonAngularLoginSpec.js
it('should goto friend pages on successful login', function() {
loginPage.loginAs(userData.testUser);
expect(friendPage.at()).toBeTruthy();
});