Last active
July 10, 2018 19:59
-
-
Save sebastianfrey/0b716ebae461afb08dfdf7f4b4fae802 to your computer and use it in GitHub Desktop.
Example for @konmuc/authc and @konmuc/authz usage.
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
// import the @konmuc/authc dependencies | |
const express = require('express'); | |
const mongoose = require('mongoose'); | |
const { Schema } = mongoose; | |
const bodyParser = require('body-parser'); | |
// import the @konmuc/authc middleware and router | |
const authc = require('@konmuc/authc'); | |
const authcRouter = require('@konmuc/authc/router'); | |
const UserSchema = require('@konmuc/authc/schemas/UserSchema'); | |
const configureAuthz = require('@konmuc/authz'); | |
UserSchema.configure({ | |
role: String | |
}); | |
const PostSchema = new Schema({ | |
owner: String, | |
content: String | |
}); | |
const Post = mongoose.model('Post', PostSchema.create()); | |
const authz = configureAuthz({ | |
user: { | |
can: [{ | |
name: 'post:edit', | |
when: (params) => params.user.username === params.post.owner | |
}], | |
inherits: ['guest'], | |
}, | |
guest: { can: ['post:view'], inherits: [] } | |
}); | |
// app setup goes here | |
mongoose.connect('mongodb://localhost/authc').then(() => { | |
// create express app | |
const app = express(); | |
// register json middleware | |
app.use(bodyParser.json()); | |
// register @konmuc/authcRouter with user managment support | |
app.use('/', authcRouter); | |
// register @konmuc/authc middleware | |
app.use(authc({ secret: 'NOT_SO_SECURE_SECRET' })); | |
app.get('/posts/:id', authz('post:view') , async (req, res) => { | |
const post = await Post.findOne({ _id: req.params.id }); | |
res.status(200).send(post); | |
}); | |
app.post('/posts', async (req, res) => { | |
const { body, user } = req; | |
const post = new Post({ | |
owner: user.username, | |
content: body.content | |
}); | |
await post.save(); | |
res.status(200).send(post); | |
}); | |
app.put('/posts/:id', authz('post:edit', async (req) => { | |
req.post = await Post.findOne({ _id: req.params.id }); | |
return req; | |
}), async (req, res) => { | |
const { post, body } = req; | |
post.content = body.content; | |
await post.save(); | |
res.status(200).send(post); | |
}); | |
// start express app | |
app.listen(PORT, () => { console.log(`Listening on ${PORT}.`); }); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment