Add foreign IP login notifications
This commit is contained in:
45
app/services/activity.service.js
Normal file
45
app/services/activity.service.js
Normal file
@@ -0,0 +1,45 @@
|
||||
const { Service } = require('flitter-di')
|
||||
|
||||
class ActivityService extends Service {
|
||||
static get services() { return ['models', 'jobs'] }
|
||||
|
||||
model() {
|
||||
return this.models.get('Activity')
|
||||
}
|
||||
|
||||
async login(req) {
|
||||
const Activity = this.model()
|
||||
const activity = new Activity({
|
||||
user_id: req.session.auth.user_id,
|
||||
session_id: req.session.id,
|
||||
action: 'login',
|
||||
metadata: {
|
||||
ip: req.ip
|
||||
}
|
||||
})
|
||||
|
||||
// If this is a new IP login, send an e-mail alert
|
||||
const foreign_ip = await this.foreign_login_ip(req.session.auth.user_id, req.ip)
|
||||
if ( foreign_ip ) {
|
||||
await this.jobs.queue('notifications').add('ForeignIPLoginAlert', {
|
||||
ip: req.ip,
|
||||
user_id: req.session.auth.user_id,
|
||||
})
|
||||
}
|
||||
|
||||
await activity.save()
|
||||
}
|
||||
|
||||
async foreign_login_ip(user_id, ip) {
|
||||
const Activity = this.model()
|
||||
const existing_ip = await Activity.findOne({
|
||||
user_id,
|
||||
action: 'login',
|
||||
'metadata.ip': ip,
|
||||
})
|
||||
|
||||
return !existing_ip
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = exports = ActivityService
|
||||
Reference in New Issue
Block a user