registration codes

This commit is contained in:
Erik 2022-11-24 13:20:43 +02:00
parent f5538b6a95
commit dc71a19fa8
Signed by: Navy.gif
GPG Key ID: 811EC0CD80E7E5FB
2 changed files with 37 additions and 5 deletions

View File

@ -5,6 +5,7 @@ const { inspect } = require('node:util');
const { AbstractUserDatabase } = require("../interfaces/"); const { AbstractUserDatabase } = require("../interfaces/");
const { User } = require("../structures"); const { User } = require("../structures");
const UserApplicataion = require("../structures/UserApplication"); const UserApplicataion = require("../structures/UserApplication");
const { Util } = require("../../util");
// MongoDB based user db // MongoDB based user db
class UserDatabase extends AbstractUserDatabase { 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 * Updates user entry
* *

View File

@ -13,8 +13,9 @@ class RegisterEndpoint extends ApiEndpoint {
[ 'post', this.register.bind(this), [ this.notLoggedIn.bind(this) ]] [ 'post', this.register.bind(this), [ this.notLoggedIn.bind(this) ]]
]; ];
this.subpaths = [ this.subpaths = [
[ '/finalise', 'post', this.finaliseRegistration.bind(this), [ this.loggedIn.bind(this) ]], [ '/finalise', 'post', this.finaliseRegistration.bind(this), [ server.auth.authenticate ]],
[ '/toggle', 'post', this.toggleRegistration.bind(this), [ server.authenticator.createAuthoriser('administrator', 5) ]] [ '/toggle', 'post', this.toggleRegistration.bind(this), [ server.auth.createAuthoriser('administrator', 5) ]],
[ '/code', 'get', this.registrationCode.bind(this), [ server.auth.createAuthoriser('administrator', 5) ]]
]; ];
this.middleware = [ ]; this.middleware = [ ];
@ -69,9 +70,10 @@ class RegisterEndpoint extends ApiEndpoint {
} }
loggedIn (req, res, next) { async registrationCode (req, res) {
if (!req.user) return res.status(400).end(); const code = await this.userdb.createRegistrationCode();
next(); delete code._id;
res.json(code);
} }
notLoggedIn (req, res, next) { notLoggedIn (req, res, next) {