import jsonwebtoken
const { sign } = require('jsonwebtoken');
response
application
we can check the token
if I input none user info,
AuthMiddleware.js
fileall i wanna to do is be able to grab the token that is sent through the front-end then validate by using jwt function called verify and im going to verify to see if it's valid if it is valid, then i want to continue with the request and send the comment add the comment to TutorialDB / comments
if not , im going to return sort of json response in the request with some sort of error
create validateToken
./route/Comment/post("/)
and whenever someone makes a request to this comments endpoint , they want to first go to this function make a bunch of checks including to see if the user is authenticated it's and if the user is then , i call this next function and this is basically means is i want to continue forward with my request. so it means it will just come here(./route/Comment/post("/)
) and do whatever which is just like creating and adding the comment to the TutorialDB / comments. However if it isnt a valid token, then i should return directly from here(validateToken
in AuthMiddleware.js) and some sort of error to let the user know in the front-end that thet are not authenticatedreq.header()
and then inside of here we pass the name of the header object that im going to pass. im not currently passing this in the front-end but im gonna to do that later so let's assume that in the front it will pass some sort of key in the headers called accessToken
and this should have a value of the actual access token in my session storage. if(!accessToken)
), so if there's no accessToken if this doesn't return any accessToken i just want to return from response.json (return res.json()
) and this json will be an object containing error and i will say like "사용자가 로그인 되지 않았습니다."
and if the user has an accessToken
i now need to check to see if the accessToken
is actually valid. if they didnt just make up the string and it's pretending to that it acutually is the correct one. so to do that im going to be using a function called verify which is from jsonwebtoken
const { verify } = require("jsonwebtoken")
try / catch
which is something i've to do because im going to verifing it so i can say try / catch
and catch
will grab any errors that occurs and in the try
what im going to try is grab a valid token AuthMiddleware
in the comments endpoint , just have to import this. const { validateToken } = require('../middlewares/AuthMiddleware');
axios.post
im going to pass my headers.accessToken
)then()
to if there's err, alert it.TutoralDB
import { useHistory } from 'react-router-dom';
let history = useHistory();
history.push('/');
in login function