rsnext/examples/with-passport-and-next-connect/pages/api/users.js
Hoang Vo ee372f472f
feat(example): add CRUD example with next-connect and passport (#11359)
* Add with-next-connect example

* Update README

* Fix code and lint

* Fix typo

* Run prettier

* Include username

* Rename example

* Match with-passport styling

* Add comments in code

* Run prettier

* Rewrite example

* Add some comments

* Update README.md

* keys -> secret

* Updated package.json and readme

* UX changes

* Securely encrypt cookie with @hapi/iron

* Update README

* Abstract db related actions and update README

* security: add note on password hashing

* remove unused dep

* Updated readme

Co-authored-by: Luis Alvarez <luis@zeit.co>
2020-04-13 18:07:54 -05:00

38 lines
1.2 KiB
JavaScript

import nextConnect from 'next-connect'
import auth from '../../middleware/auth'
import { getAllUsers, createUser, findUserByUsername } from '../../lib/db'
const handler = nextConnect()
handler
.use(auth)
.get((req, res) => {
// For demo purpose only. You will never have an endpoint which returns all users.
// Remove this in production
res.json({ users: getAllUsers(req) })
})
.post((req, res) => {
const { username, password, name } = req.body
if (!username || !password || !name) {
return res.status(400).send('Missing fields')
}
// Here you check if the username has already been used
const usernameExisted = !!findUserByUsername(req, username)
if (usernameExisted) {
return res.status(409).send('The username has already been used')
}
const user = { username, password, name }
// Security-wise, you must hash the password before saving it
// const hashedPass = await argon2.hash(password);
// const user = { username, password: hashedPass, name }
createUser(req, user)
req.logIn(user, err => {
if (err) throw err
// Log the signed up user in
res.status(201).json({
user,
})
})
})
export default handler