Skip to content

Instantly share code, notes, and snippets.

@tadeuszkora
Created September 1, 2020 20:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tadeuszkora/3aff4bf07d279dc7d1c31af57ddf6466 to your computer and use it in GitHub Desktop.
Save tadeuszkora/3aff4bf07d279dc7d1c31af57ddf6466 to your computer and use it in GitHub Desktop.
one file Koa admin panel
const AdminBro = require('admin-bro')
const mongoose = require('mongoose')
const AdminBroMongoose = require('@admin-bro/mongoose')
const { buildAuthenticatedRouter } = require('@admin-bro/koa')
const passwordFeature = require('@admin-bro/passwords')
const argon2 = require('argon2')
const Koa = require('koa')
const app = new Koa()
app.keys = ['super-secret1', 'super-secret2'
]
AdminBro.registerAdapter(AdminBroMongoose)
const User = mongoose.model('User', {
email: { type: String, required: true },
encryptedPassword: { type: String, required: true },
});
const run = async () => {
const mongoose = require('mongoose')
await mongoose.connect('mongodb://localhost:27017/test', {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const adminBro = new AdminBro({
resources: [{
resource: User,
options: {
properties: { encryptedPassword: { isVisible: false } },
},
features: [passwordFeature({
properties: { encryptedPassword: 'encryptedPassword' },
hash: argon2.hash,
})]
}],
rootPath: '/admin',
})
adminBro.watch()
const router = buildAuthenticatedRouter(adminBro, app, {
authenticate: async (email, password) => {
const user = email && await User.findOne({ email })
if (password && user && await argon2.verify(user.encryptedPassword, password)){
return user.toJSON()
}
return null
},
})
app
.use(router.routes())
.use(router.allowedMethods())
app.listen(3000)
}
run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment