Created
September 1, 2020 20:40
-
-
Save tadeuszkora/3aff4bf07d279dc7d1c31af57ddf6466 to your computer and use it in GitHub Desktop.
one file Koa admin panel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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