2

I have created a backend for user registration and login, I do not know how sessions are handled and verified in the back end.

I read some articles on how to generate the session token but I have no clue of how to validate that token once send to the server side asking for some information

this is what i did, stored the session in the backend for each user and then with a handmade middle-ware asked if this session is created for that user or not which i know is inefficient

router.post("/createUser",(req,res)=>{
    const {Name, Email , Phone , Password, UserName} = req.body
    console.log(Email,Phone,Password)
    if(Name && Email && Phone && Password){
        const user = new UserModel({Name,Email,Phone,Password,UserName})
        user.save((e)=>e? console.log(e): console.log("success"))
        const Session = new SessionModel({userID:user._id,session:req.sessionID})
        Session.save()
        res.status(201).send(req.sessionID)
    }else{
        res.status(500).send()
    }
})

and this is how i validate the request

router.use("/profile",(req, res , next)=>{
    const {SessionID , UserID} = req.query

    SessionModel.findOne({userID:UserID},(err,session)=>{
        if(session.session === SessionID){
            next()
        }else{
            return res.status(500).send()
        }
    })})


router.get("/profile",(req,res)=>{
    res.send("works")
})

1 Answers1

0

You are quite duplicating things: express-sessions already manages sessions for you, there is no sense in duplicating those sessions into a database (express-sessions can do that for you if you have to scale beyond one server).

Actually you could just store the userID in the session, then check wether a userID exists in the session to validate the request. If you need to access the user data, you can just look the user up based on the id.

 router.post("/createUser",(req,res) => {
   // ...
   req.session.userID = user._id;
   //...
 });

 router.use((req, res, next) => {
   if(!req.session.userID)
     return res.status(403).send("not logged in");
  next();
 });

 // all routes are secured beyond this point

Mandatory Note: Never ever store plain text passwords in your database (aka don't be like Facebook ;)). At least hash them, if you want to do it right hash them with a per user salt.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • I thought the session is encrypted in some sort of a way once sent to the server it's decrypted to ensure the user id – Just A Practical Monster Apr 23 '19 at 14:27
  • Yes, to encrypt the communication channel [use HTTPS](https://stackoverflow.com/questions/11744975/enabling-https-on-express-js) – Jonas Wilms Apr 23 '19 at 14:28
  • There is no sense in hashing / encrypting the session, it will be thrown away soon, so there is no sense in encrypting it. All you have to do is to make sure that only your user knows the session (with HTTPS, and proper password checking) – Jonas Wilms Apr 23 '19 at 14:29
  • if this is the case why the session maxage is there?. by how i'm going about this i'd have to manually write code to delete the session after some time. – Just A Practical Monster Apr 23 '19 at 14:29
  • Sessions timeout because you assume that multiple people use the same device or do have access to it. If someone logged into his bank account using this browser one year ago, you don't want to trust the browser today. – Jonas Wilms Apr 23 '19 at 14:32
  • AHA, so should i add a setTimeout to eliminate the session after some time from the database ?.. if that's the case why is express-session providing a property of maxAge in their package? – Just A Practical Monster Apr 23 '19 at 14:34
  • By this way i'm never gonna use it as i would have manually delete it from the database – Just A Practical Monster Apr 23 '19 at 14:35
  • Wait a minute, I just realized that you are using express sessions, I'll rewrite my answer. – Jonas Wilms Apr 23 '19 at 14:37
  • is that safe to do ?, I mean does the userID exists in the request along with the session when it's submitted to the server or does express-session add it through the middleware when the request is issued to the server ? – Just A Practical Monster Apr 23 '19 at 14:47
  • Have you read [the docs](https://www.npmjs.com/package/express-session)? – Jonas Wilms Apr 23 '19 at 14:51