registration codes
This commit is contained in:
parent
f5538b6a95
commit
dc71a19fa8
@ -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
|
||||
*
|
||||
|
@ -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) {
|
||||
|
Loading…
Reference in New Issue
Block a user