doge58426
doge58426

Reputation: 11

Random Password Across Site in JS

I'm making a game where when you complete a Level it sends you back to the home screen. on the home screen there will be an input box for a password from each of the three levels.

I want the password for each Level to be completely random from person to person so that no one can share the password and have it work on their instance of the site only. here is how my website is structured:

/game
└── /home
    ├── scripts.js
    └── styles.css
└── /level 1
    ├── main.html
    ├── scripts.js
    └── styles.css
└── /level 2
    ├── main.html
    ├── scripts.js
    └── styles.css
└── /level 3
    ├── main.html
    ├── scripts.js
    └── styles.css
└── index.html

I was thinking something about using the users cookies somehow. And if there is another way I'm all ears.

By the way, I'm not very experienced in stuff like this and in web development.

Upvotes: 1

Views: 39

Answers (1)

makkusu
makkusu

Reputation: 858

⚠️ Storing clear password strings in cookies or localStorage can lead to dangerous situations. However, I'm assuming that these passwords will not protect real secure content and are mainly used as a way for users to access their most recent progress.

In your levels you could read the current state of the stored data and set a randomly generated string for this level once the user has passed the level or gained access to it (what ever suits you best):

// Generates random string of given length using characters from range 33 to 126
function generateRandomString(length) {
  const min = 33;
  const max = 126;
  return Array(length).fill('').map(() => String.fromCharCode(Math.floor(Math.random() * (max - min + 1) + min))).join('');
}

// Call if user gained access to the level
function setLevelPassword() {
  const levelNumber = 1; // Adjust for each level
  const levelData = JSON.parse(localStorage.getItem('levels')) ?? {}; // Read data from local storage (set empty object if nothing is stored yet)

  levelData[`level${levelNumber}`] = generateRandomString(16);

  localStorage.setItem('level', JSON.stringify(levelData)); // Update stored data in local storage
}

On your index page you can read the data from localStorage, parse the JSON and check if a key for the desired level exists and its value matches what the user entered in the text input. This, however, will not prevent users from accessing the deep link to the level. Inside of the levels code you could also do a check if a key (eg: levelData.level1 for this level already exists and grand access. This will still not prevent people from accessing the deep link who already received access earlier, I'll leave that up to you :)

Upvotes: 0

Related Questions