Better username validation for chat registration.
This commit is contained in:
40
api/chat.js
40
api/chat.js
@@ -1,22 +1,46 @@
|
|||||||
const path = require("path");
|
const path = require("path");
|
||||||
const { addMessage } = require(path.join(__dirname + "/redis.js"));
|
const { addMessage } = require(path.join(__dirname + "/redis.js"));
|
||||||
|
|
||||||
|
const validateUsername = (username) => {
|
||||||
|
let error = undefined;
|
||||||
|
const illegalChars = /\W/;
|
||||||
|
const minLength = 3;
|
||||||
|
const maxLength = 15;
|
||||||
|
|
||||||
|
if (typeof username !== 'string') {
|
||||||
|
error = 'Ugyldig brukernavn.';
|
||||||
|
} else if (username.length === 0) {
|
||||||
|
error = 'Vennligst oppgi brukernavn.';
|
||||||
|
} else if (username.length < minLength || username.length > maxLength) {
|
||||||
|
error = `Brukernavn må være mellom ${minLength}-${maxLength} karaktere.`
|
||||||
|
} else if (illegalChars.test(username)) {
|
||||||
|
error = 'Brukernavn kan bare inneholde tall og bokstaver.'
|
||||||
|
}
|
||||||
|
|
||||||
|
return error;
|
||||||
|
}
|
||||||
|
|
||||||
const io = (io) => {
|
const io = (io) => {
|
||||||
io.on("connection", socket => {
|
io.on("connection", socket => {
|
||||||
let username = null;
|
let username = null;
|
||||||
|
|
||||||
socket.on("username", msg => {
|
socket.on("username", msg => {
|
||||||
if (msg.username == null) {
|
const usernameValidationError = validateUsername(msg.username);
|
||||||
|
if (usernameValidationError) {
|
||||||
username = null;
|
username = null;
|
||||||
socket.emit("accept_username", false);
|
socket.emit("accept_username", {
|
||||||
return;
|
reason: usernameValidationError,
|
||||||
}
|
success: false,
|
||||||
if (msg.username.length > 3 && msg.username.length < 30) {
|
username: undefined
|
||||||
|
});
|
||||||
|
} else {
|
||||||
username = msg.username;
|
username = msg.username;
|
||||||
socket.emit("accept_username", true);
|
socket.emit("accept_username", {
|
||||||
return;
|
reason: undefined,
|
||||||
|
success: true,
|
||||||
|
username: msg.username
|
||||||
|
});
|
||||||
}
|
}
|
||||||
socket.emit("accept_username", false);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
socket.on("chat", msg => {
|
socket.on("chat", msg => {
|
||||||
|
|||||||
Reference in New Issue
Block a user