Skip to content

Commit

Permalink
wip: New subscription email can be misleading #979
Browse files Browse the repository at this point in the history
  • Loading branch information
cnouguier committed Dec 7, 2024
1 parent 2e89867 commit 831a977
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 24 deletions.
30 changes: 17 additions & 13 deletions core/api/hooks/hooks.push.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,35 +14,41 @@ export async function sendNewSubscriptionEmail (hook) {
if (hook.type !== 'after') {
throw new Error('The \'sendNewSubscriptionEmail\' hook should only be used as a \'after\' hook.')
}

// Check for a new subscription if any
const updatedUser = hook.result
const currentUser = hook.result
const previousUser = hook.params.user
// If we can't compare abort, eg f-a-m might patch user to update tokens
if (!updatedUser || !previousUser) return hook
const newSubscription = _.differenceBy(_.get(updatedUser, 'subscriptions', []), _.get(previousUser, 'subscriptions', []), 'endpoint')
if (_.size(newSubscription) !== 1) return

// Data
if (!currentUser || !previousUser) return
// Retrieve the last subscription
const lastSubscription = _.last(_.get(currentUser, 'subscriptions', []))
if (!lastSubscription) return
// Check whether the subscription has an existing fingerprint
const existingSubscription = _.find(_.get(previousUser, 'subscriptions', []), subscription => {
return _.isEqual(subscription.fingerprint, lastSubscription.fingerprint)
})
if (existingSubscription) {
debug('Last subscription uses an existing fingerprint')
return
}
debug('Last subscription uses uses a new fingerprint')
// Send an email to notify the user
const app = hook.app
console.log(app)
const mailerService = app.getService('mailer')
const domainPath = app.get('domain') + '/#/'
const email = {
subject: 'Security alert - new browser detected',
from: mailerService.options.from || mailerService.options.auth.user,
to: updatedUser.email,
to: currentUser.email,
link: domainPath,
domainPath
}

// Build the subject & link to the app to perform the different actions
const templateDir = path.join(mailerService.options.templateDir, 'newSubscription')
const template = new emails.EmailTemplate(templateDir)
// Errors does not seem to be correctly catched by the caller
// so we catch them here to avoid any problem
try {
const emailContent = await template.render({ email, user: updatedUser, subscription: _.first(newSubscription) }, updatedUser.locale || 'en-us')
const emailContent = await template.render({ email, user: currentUser, subscription: lastSubscription }, currentUser.locale || 'en-us')
// Update compiled content
email.html = emailContent.html
debug('Sending email ', email)
Expand All @@ -51,6 +57,4 @@ export async function sendNewSubscriptionEmail (hook) {
debug('Sending email failed', error)
app.logger.error(error)
}

return hook
}
25 changes: 14 additions & 11 deletions core/client/utils/utils.push.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
import _ from 'lodash'
import logger from 'loglevel'
import moment from 'moment'
import { Notify } from 'quasar'
import {
checkPrerequisites,
getPushSubscription,
subscribePushNotifications,
requestNotificationPermission,
addSubscription
} from '@kalisio/feathers-webpush/client.js'
import { Notify } from 'quasar'
import logger from 'loglevel'
import _ from 'lodash'
import moment from 'moment'
import { i18n } from '../i18n.js'
import { Store } from '../store.js'
import { api } from '../api.js'
import { getPlatform } from './utils.platform.js'
import { Platform } from '../platform.js'

export async function subscribeToPushNotifications () {
// Check prerequisites & notification permission
Expand All @@ -25,29 +25,32 @@ export async function subscribeToPushNotifications () {
}
// Data
const userService = api.service('api/users')
const platform = getPlatform()
const date = moment.utc().toISOString()
const currentSubscription = await getPushSubscription()
const user = Store.get('user')
if (!user) {
logger.error(`[KDK] User must be authenticated before calling 'subscribeToPushNotifications'`)
}
// Check if user is already subscribed
if (currentSubscription && _.find(_.get(user, 'subscriptions', []), subscription => subscription.endpoint === currentSubscription.endpoint)) {
// Patch subscription connection date
const subscriptions = _.map(user.subscriptions, subscription => {
if (subscription.endpoint === currentSubscription.endpoint) subscription.lastActivity = date
return subscription
})
userService.patch(Store.user._id, { subscriptions: subscriptions })
userService.patch(user._id, { subscriptions: subscriptions })
logger.debug(`[KDK] New connection with subscription endpoint: ${currentSubscription.endpoint}`)
return
}
// Subscribe to web webpush notifications
const subscription = await subscribePushNotifications(Store.get('capabilities.api.vapidPublicKey'))
// Set platform informations
subscription.browser = { name: platform.name, version: platform.version }
subscription.platform = platform.platform
// Set platform information's
subscription.fingerprint = Platform.fingerprint
subscription.browser = _.pick(Platform.getData('browser'), ['name', 'version'])
subscription.system = _.pick(Platform.getData('system'), ['os'])
subscription.lastActivity = date
// Patch user subscriptions
await addSubscription(user, subscription, 'subscriptions')
userService.patch(Store.user._id, { subscriptions: user.subscriptions })
userService.patch(user._id, { subscriptions: user.subscriptions })
logger.debug(`[KDK] New webpush subscription registered with endpoint: ${subscription.endpoint}`)
}

0 comments on commit 831a977

Please sign in to comment.