canopy/www/doc/server/schemas_user_emailChangeSchema.js.html

232 lines
12 KiB
HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JSDoc: Source: schemas/user/emailChangeSchema.js</title>
<script src="scripts/prettify/prettify.js"> </script>
<script src="scripts/prettify/lang-css.js"> </script>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
<link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css">
</head>
<body>
<div id="main">
<h1 class="page-title">Source: schemas/user/emailChangeSchema.js</h1>
<section>
<article>
<pre class="prettyprint source linenums"><code>/*Canopy - The next generation of stoner streaming software
Copyright (C) 2024-2025 Rainbownapkin and the TTN Community
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see &lt;https://www.gnu.org/licenses/>.*/
//You could make an argument for making this part of the userModel
//However, this is so rarely used the preformance benefits aren't worth the extra clutter
//Config
const config = require('../../../config.json');
//Node Imports
const crypto = require("node:crypto");
//NPM Imports
const {mongoose} = require('mongoose');
//Local Imports
const hashUtil = require('../../utils/hashUtils');
const mailUtils = require('../../utils/mailUtils');
/**
* Email change token retention time
*/
const daysToExpire = 7;
/**
* DB Schema for Document representing a single email change request
*/
const emailChangeSchema = new mongoose.Schema({
user: {
type: mongoose.SchemaTypes.ObjectID,
ref: "user",
required: true
},
newEmail: {
type: mongoose.SchemaTypes.String,
required: true
},
token: {
type: mongoose.SchemaTypes.String,
required: true,
//Use a cryptographically secure algorythm to create a random hex string from 16 bytes as our change/cancel token
default: ()=>{return crypto.randomBytes(16).toString('hex')}
},
ipHash: {
type: mongoose.SchemaTypes.String,
required: true
},
date: {
type: mongoose.SchemaTypes.Date,
required: true,
default: new Date()
}
});
/**
* Pre-Save function, ensures IP's are hashed and previous requests are deleted upon request creation
*/
emailChangeSchema.pre('save', async function (next){
//If we're saving an ip
if(this.isModified('ipHash')){
//Hash that sunnuvabitch
this.ipHash = hashUtil.hashIP(this.ipHash);
}
if(this.isModified('user')){
//Delete previous requests for the given user
const requests = await this.model().deleteMany({user: this.user._id});
}
next();
});
/**
* Schedulable function for processing expired email change requests
*/
emailChangeSchema.statics.processExpiredRequests = async function(){
//Pull all requests from the DB
//Tested finding request by date, but mongoose kept throwing casting errors.
//This seems to be an intermittent issue online. Maybe it will work in a future version?
const requestDB = await this.find({});
//Fire em all off at once without waiting for the last one to complete since we don't fuckin' need to
for(let requestIndex in requestDB){
//Pull request from requestDB by index
const request = requestDB[requestIndex];
//If the request hasn't been processed and it's been expired
if(request.getDaysUntilExpiration() &lt;= 0){
//Delete the request
await this.deleteOne({_id: request._id});
}
}
}
/**
* Consumes email change token, changing email address on a given user
*/
emailChangeSchema.methods.consume = async function(){
//Populate the user reference
await this.populate('user');
const oldMail = this.user.email;
//Set the new email
this.user.email = this.newEmail;
//Save the user
await this.user.save();
//Delete the request token now that it has been consumed
await this.deleteOne();
//If we had a previous email address
if(oldMail != null &amp;&amp; oldMail != ''){
//Notify it of the change
await mailUtils.mailem(
oldMail,
`Email Change Notification - ${this.user.user}`,
`&lt;h1>Email Change Notification&lt;/h1>
&lt;p>The ${config.instanceName} account '${this.user.user}' is no longer associated with this email address.&lt;br>
&lt;sup>If you received this email without request, you should &lt;strong>immediately&lt;/strong> change your password and contact the server adminsitrator! -Tokebot&lt;/sup>`,
true
);
}
//Notify the new inbox of the change
await mailUtils.mailem(
this.newEmail,
`Email Change Notification - ${this.user.user}`,
`&lt;h1>Email Change Notification&lt;/h1>
&lt;p>The ${config.instanceName} account '${this.user.user}' is now associated with this email address.&lt;br>
&lt;sup>If you received this email without request, you should &lt;strong>immediately&lt;/strong> check who's been inside your inbox! -Tokebot&lt;/sup>`,
true
);
}
/**
* Generates email change URL from a given token
* @returns {String} Email change URL generated from token
*/
emailChangeSchema.methods.getChangeURL = function(){
//Check for default port based on protocol
if((config.protocol == 'http' &amp;&amp; config.port == 80) || (config.protocol == 'https' &amp;&amp; config.port == 443 || config.proxied)){
//Return path
return `${config.protocol}://${config.domain}/emailChange?token=${this.token}`;
}else{
//Return path
return `${config.protocol}://${config.domain}:${config.port}/emailChange?token=${this.token}`;
}
}
/**
* Calculates days until token expiration
* @returns {Number} Days until token expiration
*/
emailChangeSchema.methods.getDaysUntilExpiration = function(){
//Get request date
const expirationDate = new Date(this.date);
//Get expiration days and calculate expiration date
expirationDate.setDate(expirationDate.getDate() + daysToExpire);
//Calculate and return days until request expiration
return ((expirationDate - new Date()) / (1000 * 60 * 60 * 24)).toFixed(1);
}
module.exports = mongoose.model("emailChange", emailChangeSchema);
</code></pre>
</article>
</section>
</div>
<nav>
<h2><a href="index.html">Home</a></h2><h3>Classes</h3><ul><li><a href="activeChannel.html">activeChannel</a></li><li><a href="channelManager.html">channelManager</a></li><li><a href="chat.html">chat</a></li><li><a href="chatBuffer.html">chatBuffer</a></li><li><a href="chatHandler.html">chatHandler</a></li><li><a href="commandPreprocessor.html">commandPreprocessor</a></li><li><a href="commandProcessor.html">commandProcessor</a></li><li><a href="connectedUser.html">connectedUser</a></li><li><a href="media.html">media</a></li><li><a href="playlistHandler.html">playlistHandler</a></li><li><a href="queue.html">queue</a></li><li><a href="queuedMedia.html">queuedMedia</a></li><li><a href="tokebot.html">tokebot</a></li></ul><h3>Global</h3><ul><li><a href="global.html#authenticateSession">authenticateSession</a></li><li><a href="global.html#cache">cache</a></li><li><a href="global.html#channelBanSchema">channelBanSchema</a></li><li><a href="global.html#channelPermissionSchema">channelPermissionSchema</a></li><li><a href="global.html#channelSchema">channelSchema</a></li><li><a href="global.html#chatSchema">chatSchema</a></li><li><a href="global.html#comparePassword">comparePassword</a></li><li><a href="global.html#consoleWarn">consoleWarn</a></li><li><a href="global.html#daysToExpire">daysToExpire</a></li><li><a href="global.html#emailChangeSchema">emailChangeSchema</a></li><li><a href="global.html#emoteSchema">emoteSchema</a></li><li><a href="global.html#errorHandler">errorHandler</a></li><li><a href="global.html#errorMiddleware">errorMiddleware</a></li><li><a href="global.html#escapeRegex">escapeRegex</a></li><li><a href="global.html#exceptionHandler">exceptionHandler</a></li><li><a href="global.html#exceptionSmith">exceptionSmith</a></li><li><a href="global.html#failedAttempts">failedAttempts</a></li><li><a href="global.html#fetchMetadata">fetchMetadata</a></li><li><a href="global.html#fetchVideoMetadata">fetchVideoMetadata</a></li><li><a href="global.html#fetchYoutubeMetadata">fetchYoutubeMetadata</a></li><li><a href="global.html#fetchYoutubePlaylistMetadata">fetchYoutubePlaylistMetadata</a></li><li><a href="global.html#flairSchema">flairSchema</a></li><li><a href="global.html#genCaptcha">genCaptcha</a></li><li><a href="global.html#getLoginAttempts">getLoginAttempts</a></li><li><a href="global.html#getMediaType">getMediaType</a></li><li><a href="global.html#hashIP">hashIP</a></li><li><a href="global.html#hashPassword">hashPassword</a></li><li><a href="global.html#kickoff">kickoff</a></li><li><a href="global.html#killSession">killSession</a></li><li><a href="global.html#lifetime">lifetime</a></li><li><a href="global.html#localExceptionHandler">localExceptionHandler</a></li><li><a href="global.html#mailem">mailem</a></li><li><a href="global.html#markLink">markLink</a></li><li><a href="global.html#maxAttempts">maxAttempts</a></li><li><a href="global.html#mediaSchema">mediaSchema</a></li><li><a href="global.html#passwordResetSchema">passwordResetSchema</a></li><li><a href="global.html#permissionSchema">permissionSchema</a></li><li><a href="global.html#playlistMediaProperties">playlistMediaProperties</a></li><li><a href="global.html#playlistSchema">playlistSchema</a></li><li><a href="global.html#processExpiredAttempts">processExpiredAttempts</a></li><li><a href="global.html#queuedProperties">queuedProperties</a></li><li><a href="global.html#rankEnum">rankEnum</a></li><li><a href="global.html#refreshRawLink">refreshRawLink</a></li><li><a href="global.html#schedule">schedule</a></li><li><a href="global.html#securityCheck">securityCheck</a></li><li><a href="global.html#sendAddressVerification">sendAddressVerification</a></li><li><a href="global.html#socketCriticalExceptionHandler">socketCriticalExceptionHandler</a></li><li><a href="global.html#socketErrorHandler">socketErrorHandler</a></li><li><a href="global.html#socketExceptionHandler">socketExceptionHandler</a></li><li><a href="global.html#spent">spent</a></li><li><a href="global.html#statSchema">statSchema</a></li><li><a href="global.html#throttleAttempts">throttleAttempts</a></li><li><a href="global.html#tokeCommandSchema">tokeCommandSchema</a></li><li><a href="global.html#transporter">transporter</a></li><li><a href="global.html#typeEnum">typeEnum</a></li><li><a href="global.html#userBanSchema">userBanSchema</a></li><li><a href="global.html#userSchema">userSchema</a></li><li><a href="global.html#verify">verify</a></li><li><a href="global.html#yankMedia">yankMedia</a></li><li><a href="global.html#ytdlpFetch">ytdlpFetch</a></li></ul>
</nav>
<br class="clear">
<footer>
Documentation generated by <a href="https://github.com/jsdoc/jsdoc">JSDoc 4.0.4</a> on Fri Sep 05 2025 05:52:24 GMT-0400 (Eastern Daylight Time)
</footer>
<script> prettyPrint(); </script>
<script src="scripts/linenumber.js"> </script>
</body>
</html>