Replit auth in nodejs?

I am trying to recreate this, but in nodejs, and so far I cannot get past the IF statement part. I only seem to get as far as logging in and getting the users id, and username.

nodejs auth

that already exists lol. https://docs.replit.com/hosting/repl-auth-sidebar

1 Like

I understand that exists, but I am trying to only allow specific users into the website if their replit user id is in the list. That is the part I am trying to get into the nodejs repl, but i cannot seem to figure it out.

1 Like

oh I see sorry I never read, well you can just have a repl db entry called like ids and check the headers for X-Replit-User-Id :+1: you probably already know this srry I’m not a help

1 Like

Is that even possible with replit db? If so, how do you even check for headers? (sorry im dumb)

1 Like

ummm I think you can do with express:

...
req.headers["X-Replit-User-Id"]

it’s just json so

1 Like

oh BTW follow up, you are not dumb

2 Likes

Just a quick question, do I have to make a key for each userid, or just one that includes all of them?

try doing:

db.set("user_ids", ["userid1"...]);
2 Likes

On line 17 you have this: if (user && userids.includes('X-Replit-User-Id')) {, I think you meant to do this: if (user && userids.includes(req.headers['X-Replit-User-Id'])) {

1 Like

Sorry for asking so many questions, but how would i check if the userid is in user_ids? kinda like

if (userid in "user_ids") {
     res.sendFile('index.html');
  else {
     res.sendFile('login.html');
}
}
1 Like

"user_ids" is a string so the if statement will always return false. Please ensure that you have a basic understanding of Javascript before attempting to tackle this.

4 Likes

If I understand correctly, I did that in node.js at https://replit.com/@doxr/SchoolHub

so maybe this is the code you’re looking for:

const HTTPS = process.env['html']; // The HTML is in a secret so nobody can get it
const users = require('./users.json');

app.get('/', (req, res) => {
  const user = getUserInfo(req); // Repl Auth
  if (users.allowedUsers.includes(user.name)) {
    // User is allowed, send HTTPS content
    res.send(HTTPS);
  } else {
    // User is not allowed, send 403 rickroll page
    res.sendFile('/403.html', {
      root: path.join(__dirname, './')
    });
  }
});

for example, this is what users.json looked like

{
  "allowedUsers": [
    "doxr",
    "amasad",
    "totallygoogledrive"
  ]
}

the HTML part is optional (it’s what i used to secure index.html) but if you’ll send a file I’m pretty sure you have to change res.send(); because HTTPS variable looked like this:

<html>
<head>
<title>no</title>
</head>
</html>

The main idea is that it’s just HTML, not a way to send a file

3 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.