diff --git a/src/server/components/UserDatabase.js b/src/server/components/UserDatabase.js index 4f34078..a71927d 100644 --- a/src/server/components/UserDatabase.js +++ b/src/server/components/UserDatabase.js @@ -5,6 +5,7 @@ const { inspect } = require('node:util'); const { AbstractUserDatabase } = require("../interfaces/"); const { User } = require("../structures"); const UserApplicataion = require("../structures/UserApplication"); +const { Util } = require("../../util"); // MongoDB based user db class UserDatabase extends AbstractUserDatabase { @@ -185,6 +186,35 @@ class UserDatabase extends AbstractUserDatabase { } + /** + * Create code for letting users register when registration is disabled + * + * @param {number} [validFor=1] Amount of days the code is valid + * @memberof UserDatabase + */ + async createRegistrationCode (validFor = 1) { + const string = Util.randomString(); + const now = Date.now(); + const obj = { code: string, validFor: validFor * 24 * 60 * 60 * 1000, created: now }; + await this.db.insertOne('registrationCodes', obj); + return obj; + } + + async consumeRegistrationCode (code) { + const result = await this.db.findOne('registrationCodes', { code }); + + // Invalid conditions + if (!result) return false; + if (result.created + result.validFor < Date.now()) { + // Code existed but is no longer valid + await this.db.deleteOne('registrationCodes', { _id: ObjectId(result._id) }); + return false; + } + // Valid code + await this.db.deleteOne('registrationCodes', { _id: ObjectId(result._id) }); + return true; + } + /** * Updates user entry * diff --git a/src/server/endpoints/api/Register.js b/src/server/endpoints/api/Register.js index e2de3f0..63a58f9 100644 --- a/src/server/endpoints/api/Register.js +++ b/src/server/endpoints/api/Register.js @@ -13,8 +13,9 @@ class RegisterEndpoint extends ApiEndpoint { [ 'post', this.register.bind(this), [ this.notLoggedIn.bind(this) ]] ]; this.subpaths = [ - [ '/finalise', 'post', this.finaliseRegistration.bind(this), [ this.loggedIn.bind(this) ]], - [ '/toggle', 'post', this.toggleRegistration.bind(this), [ server.authenticator.createAuthoriser('administrator', 5) ]] + [ '/finalise', 'post', this.finaliseRegistration.bind(this), [ server.auth.authenticate ]], + [ '/toggle', 'post', this.toggleRegistration.bind(this), [ server.auth.createAuthoriser('administrator', 5) ]], + [ '/code', 'get', this.registrationCode.bind(this), [ server.auth.createAuthoriser('administrator', 5) ]] ]; this.middleware = [ ]; @@ -69,9 +70,10 @@ class RegisterEndpoint extends ApiEndpoint { } - loggedIn (req, res, next) { - if (!req.user) return res.status(400).end(); - next(); + async registrationCode (req, res) { + const code = await this.userdb.createRegistrationCode(); + delete code._id; + res.json(code); } notLoggedIn (req, res, next) {