Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Notification keys are now stored in RefreshToken documents instead of in the User document #144

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 31 additions & 19 deletions controllers/Temp.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,31 +48,43 @@ const { blurEmailFunction, mailTransporter } = require('../globalFunctions.js');

const { tokenValidation, refreshTokenEncryption, refreshTokenDecryption } = require("../middleware/TokenHandler");

const { Expo } = require('expo-server-sdk')

class TempController {
static #sendnotificationkey = (userId, notificationKey) => {
static #sendnotificationkey = (userId, notificationKey, refreshTokenId) => {
return new Promise(resolve => {
if (typeof notificationKey !== 'string') {
return resolve(HTTPWTHandler.badInput(`notificationKey must be a string. Provided type: ${typeof notificationKey}`))
}

if (!Expo.isExpoPushToken(notificationKey)) {
return resolve(HTTPWTHandler.badInput('notificationKey must be a valid Expo push token.'))
}

if (typeof refreshTokenId !== 'string') {
return resolve(HTTPWTHandler.badInput(`refreshTokenId must be a string. Provided type: ${typeof refreshTokenId}`))
}

User.findOne({_id: {$eq: userId}}).lean().then(userData => {
if (userData) {
const notificationKeys = userData.notificationKeys;
if (notificationKeys.includes(notificationKey)) {
return resolve(HTTPWTHandler.OK('Notification key already exists in account data'))
} else if (notificationKey == null) {
return resolve(HTTPWTHandler.badInput('Notification key cannot be null'))
} else {
User.findOneAndUpdate({_id: {$eq: userId}}, {$push : {notificationKeys: notificationKey}}).then(function() {
return resolve(HTTPWTHandler.OK('Notification key saved.'))
}).catch(err => {
console.error('An error occurred while adding notification key to user with id:', userId, '. The error was:', err)
return resolve(HTTPWTHandler.serverError('An error occurred while saving notification key. Please try again'))
})
}
} else {
return resolve(HTTPWTHandler.notFound("Couldn't find user while sending device notification key."))
if (!userData) {
return resolve(HTTPWTHandler.notFound('Could not find user with provided userId'))
}

RefreshToken.findOne({_id: {$eq: refreshTokenId}}).lean().then(refreshTokenFound => {
if (!refreshTokenFound) {
return resolve(HTTPWTHandler.notFound('Could not find refresh token with provided id.'))
}

RefreshToken.findOneAndUpdate({_id: {$eq: refreshTokenId}}, {notificationKey}).then(() => {
return resolve(HTTPWTHandler.OK('Notification key saved.'))
}).catch(error => {
console.error('An error occurred while updating notificationKey field with:', notificationKey, 'for RefreshToken with id:', refreshTokenId, '. The error was:', error)
return resolve(HTTPWTHandler.serverError('An error occurred while saving notification key. Please try again.'))
})
}).catch(error => {
console.error('An error occurred while finding one refresh token with id:', refreshTokenId, '. The error was:', error)
return resolve(HTTPWTHandler.serverError('An error occurred while saving notification key. Please try again.'))
})
}).catch(err => {
console.error('An error occurred while finding one user with id:', userId, '. The error was:', err)
return resolve(HTTPWTHandler.serverError('An error occurred while finding user to save notification key to.'))
Expand Down Expand Up @@ -6406,8 +6418,8 @@ class TempController {
})
}

static sendnotificationkey = async (userId, notificationKey) => {
return await this.#sendnotificationkey(userId, notificationKey)
static sendnotificationkey = async (userId, notificationKey, refreshTokenId) => {
return await this.#sendnotificationkey(userId, notificationKey, refreshTokenId)
}

static changedisplayname = async (userId, desiredDisplayName) => {
Expand Down
3 changes: 2 additions & 1 deletion models/RefreshToken.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ const RefreshTokenSchema = new Schema({
IP: String,
createdAt: Date,
userId: mongoose.Schema.Types.ObjectId,
admin: Boolean
admin: Boolean,
notificationKey: String
});

const RefreshToken = mongoose.model('RefreshToken', RefreshTokenSchema);
Expand Down
66 changes: 30 additions & 36 deletions notificationHandler.js
Original file line number Diff line number Diff line change
@@ -1,46 +1,40 @@
const { Expo } = require('expo-server-sdk')
const { Expo } = require('expo-server-sdk');
let expo = new Expo();

const User = require('./models/User');
const RefreshToken = require('./models/RefreshToken');

async function createMessages(userId, message, data, callback) {
console.log("hi1")
await User.find({_id: userId}).then(userFound =>{
if (userFound.length) {
console.log("hi2")
let messages = [];
let notifKeys = userFound[0].notificationKeys
for (var i = 0; i < notifKeys.length; i++) {
console.log("hi3")
if (Expo.isExpoPushToken(notifKeys[i])) {
messages.push({
to: notifKeys[i],
sound: 'default',
title: message.title, // e.g "Post Upvoted"
body: message.body, // e.g "thekookiekov upvoted your post"
data: data // id of other and of post e.g "thekookiekovs id" "image posts id" "post type"
})
} else {
console.log("Not valid token found: " + notifKeys)
}
}
console.log("hi4")
console.log(messages)
if (messages.length > 0) {
console.log("messages returning")
return callback(messages);


function createMessages(userId, message, data, callback) {
RefreshToken.find({userId: {$eq: userId}}, 'notificationKey').lean().then(refreshTokens => {
const notificationKeys = refreshTokens.map(token => token.notificationKey)
const messages = [];

for (let i = 0; i < notificationKeys.length; i++) {
if (Expo.isExpoPushToken(notificationKeys[i])) {
messages.push({
to: notificationKeys[i],
sound: 'default',
title: message.title, // e.g "Post Upvoted"
body: message.body, // e.g "thekookiekov upvoted your post"
data: data // id of other and of post e.g "thekookiekovs id" "image posts id" "post type"
})
} else {
console.log("No valid notif keys")
return callback("Failed");
console.error('Not valid token found at index', i, 'of notificationKeys array from RefreshTokens belonging to user with id:', userId, '. Notification key found:', notificationKeys[i])
}
}

if (messages.length > 0) {
console.log("messages returning")
callback(messages)
} else {
console.log("Notification key user finding couldn't be found: " + userId)
return callback("Failed");
console.log('No valid notification keys')
return callback("Failed")
}
}).catch(err => {
console.log(err)
return callback("Failed");
})
}).catch(error => {
console.error('An error occurred while finding refresh tokens with userId:', userId, 'and projecting "notificationKey". The error was:', error)
callback("Failed")
})
}

function sendNotifications(userId, message, data) {
Expand Down
2 changes: 1 addition & 1 deletion routes/Temp.js
Original file line number Diff line number Diff line change
Expand Up @@ -882,7 +882,7 @@ router.post('/sendnotificationkey', rateLimiters['/sendnotificationkey'], (req,
const worker = new Worker(workerPath, {
workerData: {
functionName: 'sendnotificationkey',
functionArgs: [req.tokenData, req.body.keySent]
functionArgs: [req.tokenData, req.body.keySent, req.body.refreshTokenId]
}
})

Expand Down