Skip to content

Session not saving / persisting in non production mode #880

@physimo

Description

@physimo

I'm not sure what I did wrong
Last project before this was fine, session is saving / persisting

Stack: MEAN
Node version: v14.15.0
Express version: v4.17.1
Express session version: v1.17.2

app.ts

// ...
_session: typeof expressSession = require('express-session')
/* Session Store */; this.session_store = new MongoStore({ mongoUrl: this.dbURL });
        this.session = this._session({
            secret: this.keys,
            store: this.session_store,
            saveUninitialized: false,
            resave: true,
            cookie: {
                path: '/',
                httpOnly: true,
                secure: false,
                maxAge: 1 * 12 * 60 * 60 * 1000 // 12 hours
            },
            rolling: true
        })
// ...
/* Config */; require('./config.ts');

config.ts

// ...
/* Session Middleware */; app.use((request, response, next) => APP.session(request, response, next));
// ...

login.ts

app.post("/api/login", async (request, response) => {
    let body = request.body,
        username: string = body.username,
        password: string = body.password,
        db_account = APP.db.collection("accounts");

    if ((!username || !password)) {
        if (!request.session["_register"]) return response.sendStatus(411)
        username = request.session["_register"].username
        password = request.session["_register"].password
        // request.session["_register"] = undefined
    }
    // validator check
    if (!validator.isAlphanumeric(username) && !validator.isEmail(username)) return response.status(400).send("username")

    // find DB, either username or email
    const docs = await db_account.find({ $or: [{ username: username }, { email: username }] }).toArray()

    // Not found
    if (!docs.length) return response.status(404).json({ error: "username" })

    let account: Account = docs[0] as any
    if (password != account.password) return response.status(401).json({ error: "password" })

    request.session["auth"] = username
    console.log(request.session["auth"]) // username attribute exist at this point
    return response.status(200).json({ error: null })
})

app.post('/api/auth', async (request, response) => {
    console.log(request.session["auth"]); // undefined

    request.session["auth"]
        ? response.send({ auth: true })
        : response.send({ auth: false })
})

Front end side
login.component.ts

  async login() {
    if (this.password.invalid || this.username.invalid) return;

    let res: any = await lastValueFrom(this.http.post(server_host() + "/api/login", {
      username: this.username.value,
      password: md5(this.password),
    }))
      .catch(err => {
        if (err)
          return alert("Something went wrong. Please refresh the page and try again.")
      })

    if (res && !res.error) {
      localStorage.setItem("auth", "true")
      return this.router.navigate([''])
    }
    return alert("Something went wrong. Please refresh the page and try again.")
  }

Front end middleware
app.component.ts

  async auth(): Promise<boolean> {
    if (!localStorage.getItem('auth')) return false
    var res = await lastValueFrom(this.http.post(server_host() + "/api/auth", {}, { withCredentials: true })) as any;
    if (!res.auth) { localStorage.removeItem("auth"); return false }
    return true
  }

// ...
      if (ev instanceof NavigationStart) {
        //Middleware
        this.loading = true;
        await this.auth();
      }
// ...

On previous project, following more or less same template / work logic, it works as intended (session persisting / saving)
Where did I go wrong?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions