Commit c1d16d72 authored by Yoon, Daeki's avatar Yoon, Daeki 😅
Browse files

auth, user 추가

parent 8385a937
import jwt from 'jsonwebtoken'
import expressJwt from 'express-jwt'
import User from '../user/user.model.js'
import config from '../config/config.js'
const signin = async (req, res) => {
try {
let user
let user = await User.findOne({ 'email': req.body.email })
if (!user) {
return res.status(401).json({
error: 'User not found'
})
}
if (!user.authenticate(req.body.password)) {
return res.status(401).json({
error: "Email and password don't match"
})
}
const token = jwt.sign({ _id: user._id }, config.jwtSecret)
return res.json({
token,
user: {
_id: user._id,
name: user.name,
email: user.email,
}
})
} catch (error) {
return res.status(400).json({
error: 'User not found'
error: 'Could not sign in'
})
}
}
const signout = (req, res) => {
return res.json({
message: 'Signed out'
})
}
const requireSignin = expressJwt({
secret: config.jwtSecret,
requestProperty: 'auth',
algorithms: ['HS256']
})
const hasAuthorization = (req, res, next) => {
const authorized = req.profile && req.auth && req.profile._id === req.auth._id
if (!authorized) {
return res.status(403).json({
error: 'User is not authorized'
})
}
next()
}
export default {
signin,
signout,
requireSignin,
hasAuthorization,
}
\ No newline at end of file
import express from 'express'
import authCtrl from './auth.controller'
const router = express.Router()
router.route('/auth/signin')
.post(authCtrl.signin)
router.route('/auth/signout')
.get(authCtrl.signout)
export default router
\ No newline at end of file
const config = {
env: process.env.NODE_ENV || 'development',
port: process.env.PORT || 3000,
jwtSecret: 'My_Secure_Screte',
mongoUri: process.env.MONGODB_URI || 'mongodb://localhost:27017/quizcompetition'
}
......
......@@ -10,8 +10,15 @@ app.use(bodyParser.urlencoded({ extended: true }))
app.use('/', userRoutes)
app.use((err, req, res, next) => {
if (err) {
console.log('Error in Express', err)
if (err.name === 'UnauthorizedError') {
res.status(401).json({
error: err.name + ': ' + err.message
})
} else if (err) {
res.status(400).json({
error: err.name + ': ' + err.message
})
console.log(err)
}
})
......
import User from './user.model.js';
import User from './user.model.js'
import formidable from 'formidable'
import extend from 'lodash/extend'
import fs from 'fs'
const create = async (req, res) => {
const user = new User(req.body)
try {
await user.save()
return res.json({
message: 'Succefully signed up!'
message: 'Successfully signed up!'
})
} catch (error) {
return res.status(400).json({
......@@ -19,13 +22,85 @@ const list = async (req, res) => {
let users = await User.find().select('name email updated created').exec()
return res.json(users)
} catch (error) {
return res.status(400).json({
error: 'Users not found'
})
}
}
const read = (req, res) => {
req.profile.hashedPassword = undefined
req.profile.salt = undefined
return res.json(req.profile)
}
const update = async (req, res) => {
let form = new formidable.IncomingForm()
form.keepExtensions = true
form.parse(req, async (err, fields, files) => {
if (err) {
return res.status(400).json({
error: 'Photo could not be uploaded'
})
}
let user = req.profile
user = extend(user, fields)
user.updated = new Date()
if (files.photo) {
user.photo.data = fs.readFileSync(files,photo.path)
user.photo.contentType = files.photo.type
}
try {
await user.save()
user.hashedPassword = undefined
user.salt = undefined
res.json(user)
} catch (error) {
return res.status(400).json({
error: 'User save error'
})
}
})
}
const remove = async (req, res) => {
try {
let user = req.profile
let deletedUser = await user.remove()
deletedUser.hashedPassword = undefined
deletedUser.salt = undefined
res.json(deletedUser)
} catch (error) {
return res.status(400).json({
error: 'User delete error'
})
}
}
const userById = async (req, res, next, id) => {
try {
let user = await User.findById(id)
.exec()
if (!user) {
return res.status(400).json({
error: 'User not found'
})
}
req.profile = user
next()
} catch (error) {
return res.status(400).json({
error: 'Could not retrieve user'
})
}
}
export default {
create,
list,
read,
update,
remove,
userById,
}
\ No newline at end of file
......@@ -24,6 +24,10 @@ const UserSchema = new mongoose.Schema({
required: 'Password is required'
},
salt: String,
photo: {
data: Buffer,
contentType: String,
},
})
UserSchema.virtual('password')
......
import express from 'express'
import authCtrl from '../auth/auth.controller.js'
import userCtrl from './user.controller.js'
const router = express.Router()
router.route('/api/users')
.get(userCtrl.list)
.post(userCtrl.create)
.get(userCtrl.list)
.post(userCtrl.create)
router.route('/api/users/:userId')
.get(authCtrl.requireSignin, userCtrl.read)
.put(authCtrl.requireSignin, authCtrl.hasAuthorization, userCtrl.update)
.delete(authCtrl.requireSignin, authCtrl.hasAuthorization, userCtrl.remove)
router.param('userId', userCtrl.userById)
export default router
\ No newline at end of file
......@@ -518,6 +518,11 @@ finalhandler@~1.1.2:
statuses "~1.5.0"
unpipe "~1.0.0"
formidable@^1.2.2:
version "1.2.2"
resolved "https://registry.yarnpkg.com/formidable/-/formidable-1.2.2.tgz#bf69aea2972982675f00865342b982986f6b8dd9"
integrity sha512-V8gLm+41I/8kguQ4/o1D3RIHRmhYFG4pnNyonvua+40rqcEmT4+V71yaZ3B457xbbgCsCfjSPi65u/W6vK1U5Q==
forwarded@~0.1.2:
version "0.1.2"
resolved "https://registry.yarnpkg.com/forwarded/-/forwarded-0.1.2.tgz#98c23dab1175657b8c0573e8ceccd91b0ff18c84"
......@@ -908,6 +913,11 @@ lodash.set@^4.0.0:
resolved "https://registry.yarnpkg.com/lodash.set/-/lodash.set-4.3.2.tgz#d8757b1da807dde24816b0d6a84bea1a76230b23"
integrity sha1-2HV7HagH3eJIFrDWqEvqGnYjCyM=
lodash@^4.17.20:
version "4.17.20"
resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.20.tgz#b44a9b6297bcb698f1c51a3545a2b3b368d59c52"
integrity sha512-PlhdFcillOINfeV7Ni6oF1TAEayyZBoZ8bcshTHqOYJYlrqzRK5hagpagky5o4HfCzzd1TRkXPMFq6cKk9rGmA==
lowercase-keys@^1.0.0, lowercase-keys@^1.0.1:
version "1.0.1"
resolved "https://registry.yarnpkg.com/lowercase-keys/-/lowercase-keys-1.0.1.tgz#6f9e30b47084d971a7c820ff15a6c5167b74c26f"
......
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