Commit 85f24361 authored by Jarrod's avatar Jarrod 💬

Merge branch 'feat/remove-auth' into 'master'

Feat/remove auth

See merge request !2
parents c48334ab bb6ac458
Pipeline #4242 passed with stages
in 41 seconds
......@@ -33,7 +33,7 @@ module.exports = {
// We determine its name using the bare action name.
var bareActionName = target.action.replace(/\//g, '-')
var methodName = target.name || _.camelCase(bareActionName)
var methodName = target.sdk || target.name || _.camelCase(bareActionName)
var expandedAddress = sails.getRouteFor(target)
// Skip routes that just serve views.
......
const render = require('./render-template')
if (typeof sails === 'undefined') {
sails = { config: { environment: 'production', custom: { site: { name: 'test cmd', emailFrom: 'root@zhdict.net' } } } }
}
module.exports = async function sendWithPostal(template, to, args) {
const config = sails.config.custom
const axios = require('axios')
let html = template ? await render(`${template}`, args) : ''
let text = args.text
var data = {
to: [to],
from: args.from || config.site.emailFrom,
subject: args.subject || `Notification from ${config.site.name}`,
plain_body: text,
html_body: html ? html : text ? text.replace(/\n/g, '<br/>') : ''
};
if (sails.config.environment !== 'production') {
console.log(`~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`)
console.log(`Not sending email as not in production mode`)
console.log(`I would have sent the following message:`)
console.log(` To: ${data.to}`)
console.log(` Subject: ${data.subject}`)
console.log(` Message:\n${data.html}`)
return true
}
// Send mail
config.postal = {
apiHost: 'https://postal.chenggong.carrotlabs.net',
apiKey: 'aBZuUSZ7qeElyHJOOJ5PH1Qs'
}
try {
const res = await axios.post(
config.postal.apiHost + '/api/v1/send/message',
data,
{
headers: {
'X-Server-API-Key': config.postal.apiKey
}
}
)
console.log('Sent email: ', res.status)
console.log('Sent email: ', res.statusCode)
console.log('Sent email: ', res.data)
return true
} catch (err) {
console.error('Failed to send email', err.stack)
return false
}
}
\ No newline at end of file
module.exports = async function renderEmailTemplate(template, args = { }) {
const config = sails.config.custom
// Determine appropriate email layout and template to use.
const path = require('path')
const emailTemplatePath = path.join('email/', template);
let layout = path.relative(path.dirname(emailTemplatePath), path.resolve('layouts/', args.layout || 'layout'));
// Compile HTML template.
// > Note that we set the layout, provide access to core `url` package (for
// > building links and image srcs, etc.), and also provide access to core
// > `util` package (for dumping debug data in internal emails).
var htmlEmailContents = await sails.renderView(
emailTemplatePath,
_.extend({ layout }, { data: args, site: config.site, title: args.subject || '' }, args.templateData)
)
.intercept((err)=>{
err.message =
'Could not compile view template.\n'+
'(Usually, this means the provided data is invalid, or missing a piece.)\n'+
'Details:\n'+
err.message;
return err;
});
return htmlEmailContents
}
\ No newline at end of file
const render = async function(template, args = { }) {
const config = sails.config.custom
// Determine appropriate email layout and template to use.
const path = require('path')
const emailTemplatePath = path.join('email/', template);
let layout = path.relative(path.dirname(emailTemplatePath), path.resolve('layouts/', args.layout || 'layout'));
// Compile HTML template.
// > Note that we set the layout, provide access to core `url` package (for
// > building links and image srcs, etc.), and also provide access to core
// > `util` package (for dumping debug data in internal emails).
var htmlEmailContents = await sails.renderView(
emailTemplatePath,
_.extend({ layout }, { data: args, site: config.site, title: args.subject || '' }, args.templateData)
)
.intercept((err)=>{
err.message =
'Could not compile view template.\n'+
'(Usually, this means the provided data is invalid, or missing a piece.)\n'+
'Details:\n'+
err.message;
return err;
});
return htmlEmailContents
async function send (template, to, args) {
// return require('./lib/postal')(template, to, args)
return sendWithMailgun(template, to, args)
}
async function send (template, to, args) {
async function sendWithMailgun (template, to, args) {
const config = sails.config.custom
const render = require('./lib/render-template')
const mailgun = require('mailgun-js')( config.mailgun )
return new Promise(async (resolve, reject) => {
......
......@@ -8,7 +8,7 @@ const cacheMiddleware = require('./middleware/cache')
module.exports = class SailsPluggable {
constructor (opt = {}) {
this.opt = opt
// FUTURE MAYBE: Can probably guess this based on the upstream hooks folder name?
// FUTURE MAYBE: `key` Can probably guess this based on the upstream hooks folder name?
this.opt.key = this.opt.key || this.opt.apiBase
this.core = this.opt.key === 'ahoy'
this.log = function () { sails.log[sails.hooks.ahoy.logLevel || 'info'](...arguments) }
......@@ -33,6 +33,7 @@ module.exports = class SailsPluggable {
await this.registerActions()
await this.registerModels()
await this.registerEventHandlers()
if (this.opt.initialize) {
await this.opt.initialize()
......@@ -52,13 +53,14 @@ module.exports = class SailsPluggable {
if (def.extend) {
_.each(def.extend, (attributes, name) => {
sails.log.info(`Ahoy: Extending ${name}`, attributes)
const model = sails.config.orm.moduleDefinitions.models[name] // || sails.models[name]
const model = sails.config.orm.moduleDefinitions.models[name] || sails.models[name] // || sails.models[name]
if (!model || !model.attributes) {
sails.log.error(`Unable to extend model ${name} from ${extender}`)
sails.log.error(`Unable to extend model ${name} from ${extender}`, { model})
} else {
_.each(attributes, (opt, field) => {
(sails.config.orm.moduleDefinitions.models[name] || sails.models[name]).attributes[field] = opt
})
}
_.each(attributes, (opt, field) => {
sails.config.orm.moduleDefinitions.models[name].attributes[field] = opt
})
})
}
})
......@@ -66,7 +68,12 @@ module.exports = class SailsPluggable {
// Reload the Sails ORM
sails.hooks.orm.reload((err) => {
if (err) { sails.log.error(`Unable to reload sails ORM`, err.stack) }
sails.emit('ahoy:ready')
console.log(`Running sails migrations (again?) ${sails.config.models.migrate}`)
const wlUtils = require('waterline-utils')
wlUtils.autoMigrations(sails.config.models.migrate, sails.hooks.orm._orm, function onAutoMigrationsManuallyTriggered () {
sails.emit('ahoy:ready')
})
})
// Retrofit our route-level middlewares
......@@ -74,15 +81,13 @@ module.exports = class SailsPluggable {
_.each(sails.config.routes, (def, path) => {
if (!def.action) { return }
// TODO: Will this work in the upstream auth modules? Might / should.. time will tell.
// If/when it does get rid of this commented junkskie :)
// if (def.auth || def.permission) {
// sails.log.verbose('Initializing permissions middleare for ', path)
// sails.registerActionMiddleware(permissionsMiddleware, def.action)
// }
if ('auth' in sails.hooks && _.isFunction(sails.config.auth.permissionsMiddleware)) {
sails.log.verbose('Binding permissions middleware to: ', path)
sails.registerActionMiddleware(sails.config.auth.permissionsMiddleware, def.action)
}
if (def.cache) {
sails.log.verbose('Initializing cache middleware for ', path)
sails.log.verbose('Initializing cache middleware to: ', path)
sails.registerActionMiddleware(cacheMiddleware, def.action)
}
})
......@@ -121,8 +126,8 @@ module.exports = class SailsPluggable {
})
}
async registerModels () {
const modelDir = path.join(this.opt.dir, 'models')
async registerModels (_dirOverride) {
const modelDir = _dirOverride || path.join(this.opt.dir, 'models')
if (!fs.existsSync(modelDir)) {
return
}
......@@ -141,7 +146,7 @@ module.exports = class SailsPluggable {
// Check for model collisions. In theory userland models should take preference/override the core Ahoy user model
if (sails.models[lcName] || sails.config.orm.moduleDefinitions.models[lcName]) {
sails.log.warn(`Ahoy: Skip loading model "${name}" as it already exists on the Sails instance (this *could* be the expected behaviour if you have created a userland model with the name ${name}, but could also be attributed to ahoy plugin model collisons.)`)
sails.log.debug(`Ahoy: Skip loading model "${name}" from '${this.opt.key}' as it already exists on the Sails instance (this *could* be the expected behaviour if you have created a userland model with the name ${name}, but could also be attributed to ahoy plugin model collisons or some other cancerous nonsense.)`)
return
}
......@@ -152,6 +157,39 @@ module.exports = class SailsPluggable {
})
}
registerEventHandlers () {
const modelDir = path.join(this.opt.dir, 'event-handlers')
if (!fs.existsSync(modelDir)) {
return
}
const models = includeAll({
dirname : modelDir,
filter : /(.*)\.js$/
})
if (_.isEmpty(models)) {
return
}
_.each(models, (def, name) => {
if (_.isString(def.event)) {
def.event = [def.event]
}
def.event.forEach(e => {
if (!_.isString(e) || _.isEmpty(e) || !_.isFunction(def.fn)) {
sails.log.error(`Unable to initialize event handler [${e}] from Ahoy pluggable [${this.opt.key}] - Invalid definition\n`
+ ` Event handler should contain keys:\n - 'event' string|array event name(s), ie 'ahoy:reporting:create'\n`
+ ` - 'fn' event handler method`)
return
}
sails.log.debug(`Initializing event handler from [${this.opt.key}] - ${e}`)
sails.on(e, def.fn)
})
})
}
toHook () {
const that = this
return function (sails) {
......@@ -176,6 +214,9 @@ module.exports = class SailsPluggable {
}
}
// Bodge on userland models
that.registerModels(sails.config.paths.models)
// Find other Ahoy hooks
_.each(sails.hooks, (hook, name) => {
if (hook.ahoy) {
......
{
"name": "@nahanil/ahoy",
"version": "0.1.0",
"version": "0.2.0",
"description": "",
"main": "lib/index.js",
"scripts": {
......@@ -15,12 +15,10 @@
"author": "Jarrod Linahan <jarrod@linahan.id.au>",
"license": "MIT",
"dependencies": {
"@nahanil/sails-hook-api-log": "^1.0.0",
"@sailshq/lodash": "^3.10.3",
"axios": "^0.19.2",
"mailgun-js": "^0.22.0",
"memory-cache": "^0.2.0",
"sails": "^1.2.3",
"sails-hook-orm": "^2.1.1",
"uuid": "^3.3.2"
},
"devDependencies": {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment