Javascript get all user info

GET information from user in database

I am making full stack app and learn from tutorials and videos . I have a problem with GET request to get information about user which is login in the system. I use Postman to check the requests. When I add user with /login , the Postman look user’s accesstoken code. I copy his code and paste it in authorization key in headers in Postman and when I change the URL in localhost to /infor to get information about this user and send it. But it say me «Invalid Authentication». I can’t find the wrong. I think the problem is in controllers/userCtrl.js in getUser function. Can you help me? I put the code: server.js

require('dotenv').config() const express = require('express') const mongoose = require('mongoose') const cors = require('cors') const fileUpload = require('express-fileupload') const cookieParser = require('cookie-parser') const app = express() app.use(express.json()) app.use(cookieParser()) app.use(cors()) // Use temp files instead of memory for managing the upload process. app.use(fileUpload(< useTempFiles: true >)) // Routes app.use('/user', require('./routes/userRouter')) // Connect to Mongodb const URL = process.env.MONGO_URL mongoose.connect(URL,< useCreateIndex: true, useFindAndModify: false, useNewUrlParser: true, useUnifiedTopology: true >, err =>< if(err) throw err; console.log('Connected to MongoDB') >) const PORT = process.env.PORT || 5000 app.listen(PORT, () => < console.log('Server is running on port', PORT) >) 
MONGO_URL = *********** ACCESS_TOKEN_SECRET = *********** REFRESH_TOKEN_SECRET = ************* 
require('dotenv').config() const express = require('express') const mongoose = require('mongoose') const cors = require('cors') const fileUpload = require('express-fileupload') const cookieParser = require('cookie-parser') const app = express() app.use(express.json()) app.use(cookieParser()) app.use(cors()) // Use temp files instead of memory for managing the upload process. app.use(fileUpload(< useTempFiles: true >)) // Routes app.use('/user', require('./routes/userRouter')) // Connect to Mongodb const URL = process.env.MONGO_URL mongoose.connect(URL,< useCreateIndex: true, useFindAndModify: false, useNewUrlParser: true, useUnifiedTopology: true >, err =>< if(err) throw err; console.log('Connected to MongoDB') >) const PORT = process.env.PORT || 5000 app.listen(PORT, () => < console.log('Server is running on port', PORT) >) 
const mongoose = require('mongoose') const userSchema = new mongoose.Schema(< name: < type: String, required: true, trim: true >, email: < type: String, required: true, unique: true >, password: < type: String, required: true, >, role: < type: Number, default: 0 >, cart: < type: Array, default: [] >>, < timestamps: true >) module.exports = mongoose.model('Users', userSchema) 
const jwt = require('jsonwebtoken') const auth = (req, res, next) => < try< const token = req.header("Authorization") if(!token) return res.status(400).json(< msg: "Invalid Authentication" >) jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, user) => < if(!err) return res.status(400).json() req.user = user next() >) > catch (err) < return res.status(500).json() > > module.exports = auth 
const Users = require('../models/userModel') const bcrypt = require('bcrypt') const jwt = require('jsonwebtoken') const userCtrl = < register: async (req, res) => < // async before a function means one simple thing: a function always returns a promise. try< const < name, email, password >= req.body const user = await Users.findOne(< email >) // wait until the promise resolves if(user) return res.status(400).json() if(password.length < 6) return res.status(400).json() //Password encryption const passwordHash = await bcrypt.hash(password, 10) const newUser = new Users(< name, email, password: passwordHash >) // save mongodb await newUser.save() //then create jsonwebtoken to authentication const accesstoken = createAccessToken(< id: newUser._id >) const refreshtoken = createRefreshToken(< id: newUser._id >) res.cookie('refreshtoken', refreshtoken, < httpOnly: true, path: '/user/refresh_token' >); res.json() > catch(err)< return res.status(500).json() > >, login: async (req, res) => < try< const = req.body; const user = await Users.findOne() if(!user) return res.status(400).json() const isMatch = await bcrypt.compare(password, user.password) if(!isMatch) return res.status(400).json() // if login success, create access token and refresh token const accesstoken = createAccessToken(< id: user._id >) const refreshtoken = createRefreshToken(< id: user._id >) res.cookie('refreshtoken', refreshtoken, < httpOnly: true, path: '/user/refresh_token' >); res.json() > catch(err)< return res.status(500).json() > >, logout: async (req, res)=> < try< res.clearCookie('refreshtoken', ) return res.json() >catch(err)< return res.status(500).json() > >, refreshToken: (req, res) => < try< const rftoken = req.cookies.refreshtoken if(!rftoken) return res.status(400).json() jwt.verify(rftoken, process.env.REFRESH_TOKEN_SECRET, (err, user) => < if(err) return res.status(400).json() const accesstoken = createAccessToken() res.json(< accesstoken >) >) >catch (err) < return res.status(500).json() > >, getUser: async (req, res) => < // problem try< const user = await (await Users.findById(req.user.id)).isSelected('-password') if(!user) return res.status(400).json(< msg: "Useer does not exist.">) res.json(req.user) >catch (err) < return res.status(500).json() > > > const createAccessToken = (user) => < return jwt.sign(user, process.env.ACCESS_TOKEN_SECRET, < expiresIn: '1d' >) > const createRefreshToken = (user) => < return jwt.sign(user, process.env.REFRESH_TOKEN_SECRET, < expiresIn: '7d' >) > module.exports = userCtrl 

Источник

Читайте также:  jQuery UI Dialog - Default functionality

Get More Data About a User with JavaScript Variable

In one of my previous blog posts, I’ve explained what is JavaScript variable in Google Tag Manager and how to use it. This time, I thought I’d give you more examples where you can apply it.

Currently, my courses are hosted on Teachable. I decided that I don’t want to spend my time building and hosting some custom solutions, therefore, I chose a ready-made platform.

Even though Teachable offers a built-in Google Analytics tracking, I’m not happy with it as I did not manage to make it work together with a cookie consent mechanism. In other words, the built-in GA functionality fires regardless of user’s/visitor’s privacy preferences.

That’s why I’m doing some generic tracking myself with GTM there. By doing that, I came up with an idea for this blog post: did you know that it’s fairly easy to obtain logged in user’s data (e.g. user ID) with JS variable? The knowledge of this possibility becomes very useful when a developer is super busy (or unavailable) and cannot push user data to the Data Layer.

Before we continue

This guide will not be one of those where “copy-paste” will work. Every website/web app has its own unique structure, therefore, what works on one site, might not work on another.

The goal of this blog post is to show you the possibility and the workflow to make this technique work. However, there is always a chance of failure.

Also, this topic is thoroughly explained in my Intermediate Google Tag Manager course. So if you prefer video content and you want to learn many other cool features/tricks/tips in Google Tag Manager, consider enrolling.

Enroll in Intermediate Google Tag Manager course

What is JavaScript Variable?

A quick refresher. If you haven’t read it, please go and check this guide first.

Before we start digging deeper, you need to learn about the scope. In JavaScript, there are two types of scope:

Читайте также:  Html table row css

Variables declared within a JavaScript function, become LOCAL to the function, meaning that they are not accessible (visible) from outside the function. Take a look at the example below:

// code here can not use authorName variable function myFunction() < var authorName = "Julius"; // code here can use authorName variable >

There is a variable authorName and it only can be accessed within the function called myFunction.

Contrary to that, a variable declared outside a function becomes GLOBAL. A global variable has global scope: all scripts and functions on a web page can access it. Let’s use the same code example but place the variable outside the function.

// code here can use authorName variable var authorName = "Julius"; function myFunction() < // code here can use authorName variable >

What does it have to do with the JavaScript Variable in Google Tag Manager? Well, it can fetch the values of any global variable which is present at that moment.

So what?

Usually, user ID or some other data is often stored in global JavaScript variables. You just need to find it. Be aware, that sometimes the search of particular variables might be really time-consuming to do that and even might end up in achieving absolutely nothing.

But it’s definitely worth a shot 🙂 Also, if you can reach out to a developer, you can ask him/her what is global JS variable where the user ID stored (or maybe some other useful data is available as well?). Giving the answer should not be time-consuming for a dev.

Search for the right Global Variable(s)

To start the search, go to the developer console of your browser (here’s the tutorial on how to do that on Chrome), type window and hit enter (like in the screenshot below).

window in console

Click the black triangle near the Window and you’ll see a list of properties that we’ll be able to access with a JavaScript Variable in GTM. Brace yourself, that list will be huge.

global js variables

Let’s go back to my Teachable’s example. I know that previously Teachable was known as Fedora. So my guess would be to keep looking for variables somehow related to either Teachable or Fedora.

Let’s start playing a detective. Bingo, I see 3 variables related to Fedora:

fedora variables

Since I’m currently interested in user data, I’ll click the black triangle next to fedora_user to expand it. Bingo, there’s a bunch of data that I could possibly use, for example, ID, name, etc.

User data in Teachable

Just a friendly reminder: email and name must not be sent to Google Analytics because this data is PII (personally identifiable information). But maybe you plan to send it to some other tool which allows it? Another friendly reminder: you need to get consent from your users/visitors to process this personal information (due to GDPR).

Personally, I don’t plan to use this data in my generic tracking but I wanted to show you what’s under the hood and what you can do.

Читайте также:  Link with javascript action

Create JavaScript variables in Google Tag Manager

Next, let’s create those variables in GTM. Go to Variables > New and choose JavaScript Variable. For each data point you’ll need to create a separate JS variable:

Here’s an example of User ID variable. Let’s remember how we found that data point in the developer’s console. First, we clicked fedora_user and then id. So the value that we need to enter in the JavaScript variable (in GTM) is fedora_user.id (every level needs to be separated by a dot).

fedora user id

Save the variable and check whether it’s properly fetched. Refresh the GTM Preview and Debug mode, then go to the website you’re working on and refresh it as well.

In Preview and Debug console, go to Variables and check that JS variable you’ve just created. If it’s undefined, you’ve entered something wrong (maybe some typo?).

JS variable in GTM preview and debug mode

More examples

Keep in mind that the path to the correct variable will be different on most websites/web applications because the naming convention solely depends on developers (there are no widely accepted standards). For example, in one of the projects that I worked on, user ID’s path was app.id, which is super generic. But there’s nothing you can do about it, you can either adapt to it or do nothing at all.

Here’s a couple of more examples to give you a better understanding of where to keep looking for useful data:

Prestashop data

  • In Prestashop 1.7, (when a user is logged in) you can go to prestashop property and see for yourself what you can use. In this example, unfortunately, I don’t see an ID anywhere, but there are some other possibly useful data points. So if I was interested in, say, the first name, its path would be prestashop.customer.firstname
  • In Shopify, there are several options how to get logged in user’s ID:
    • ShopifyAnalytics.meta.page.customerId
    • or __st.cid

You’re probably wondering how could I possibly know where to find the user ID on Shopify? Listen very carefully, I’m about to share with you my super secret never-heard-before unique method: I googled it.

using google to find the answer

People have offered several options there. The fastest way to check whether the suggestion is working or not is to copy that suggested variable (e.g. ShopifyAnalytics.meta.page.customerId), paste it to browser’s developer console and hit enter. If you get an error, that’s not going to work. If you get the actual value, cha-ching!

Final words

In this blog post, I’ve explained a trick that I sometimes apply in my projects when a developer is not available. However, this solution is not fail-proof. If a developer changes the name of any variable in the path (that you entered in the JavaScript variable in GTM), the implementation will break. If a developer changes the data structure, this method will also fail.

So if possible, always try to get the developer to push the user data to the Data Layer. But if that’s not possible, you’ve just learned one more option.

Источник

Оцените статью