Skip to content

Commit

Permalink
fix authenticated
Browse files Browse the repository at this point in the history
  • Loading branch information
blade8128ch committed Nov 6, 2023
1 parent f10c2ee commit 2bedfb4
Show file tree
Hide file tree
Showing 4 changed files with 147 additions and 163 deletions.
89 changes: 34 additions & 55 deletions controllers/apis/user-controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,18 @@ const { Op } = require("sequelize");
const userController = {
signUp: (req, res, next) => {
if (req.body.password !== req.body.checkPassword) throw new Error('Passwords do not match!')
User.findOne( { where: { [Op.or]: [{email: req.body.email} , {account: req.body.account}] } } )
.then(user => {
if(user===null) user=[]
if (user.account===req.body.account) throw new Error('account 已重複註冊!')
else if (user.email===req.body.email) throw new Error('email 已重複註冊!')
User.findOne({ where: { [Op.or]: [{ email: req.body.email }, { account: req.body.account }] } })
.then(user => {
if (user === null) user = []

if (user.account === req.body.account) throw new Error('account 已重複註冊!')
else if (user.email === req.body.email) throw new Error('email 已重複註冊!')


return bcrypt.hash(req.body.password, 10)
})
.then(hash => User.create({
account:req.body.account,
account: req.body.account,
name: req.body.name,
email: req.body.email,
role: 'user',
Expand Down Expand Up @@ -53,62 +53,41 @@ const userController = {
},
getUser: (req, res, next) => {
const userId = req.params.id
// let tweetsCount=0
// let likesCount=0
// let followerCount=0
// let followingCount=0

User.findByPk(req.params.id, {})
.then(user => {
if (!user) throw new Error("User didn't exist!")
return user
})
.then(user => {
Promise.all([
Tweet.findAll({where: {userId } }),
Like.findAll({ where: { userId } }),
Followship.findAll({ where: { followerId:userId } }),
Followship.findAll({ where: { followingId:userId } })
])
.then(([tweetAll, likeAll,followerAll,followingAll]) => {
const tweetsCount=Object.keys(tweetAll).length
const likesCount=Object.keys(likeAll).length
const followerCount=Object.keys(followerAll).length
const followingCount=Object.keys(followingAll).length
console.log("===///////==",user,tweetsCount)
//
user=user.toJSON()
delete user.password
console.log("///////",tweetsCount)
user["followersCount"] = followerCount
user["followingCount"] = followingCount
user["likesCount"] = likesCount
user["tweetsCount"] = tweetsCount
return res.json({
status: 'success',
message: '查詢成功!',
...user
})
//console.log("0000",likesCount,"0000")
//console.log("00000" ,typeof(tweetAll) ,tweetAll,"00000" )
//console.log("11111" ,typeof(likeAll) ,likeAll,"11111" )
//return tweetsCount,likesCount,followerCount,followingCount
Promise.all([
Tweet.findAll({ where: { userId } }),
Like.findAll({ where: { userId } }),
Followship.findAll({ where: { followerId: userId } }),
Followship.findAll({ where: { followingId: userId } })
])
.then(([tweetAll, likeAll, followerAll, followingAll]) => {
const tweetsCount = Object.keys(tweetAll).length
const likesCount = Object.keys(likeAll).length
const followerCount = Object.keys(followerAll).length
const followingCount = Object.keys(followingAll).length
//console.log("===///////==",user,tweetsCount)

user = user.toJSON()
delete user.password
//console.log("///////",tweetsCount)
user["followersCount"] = followerCount
user["followingCount"] = followingCount
user["likesCount"] = likesCount
user["tweetsCount"] = tweetsCount
return res.json({
status: 'success',
message: '查詢成功!',
...user
})
})
return user
return user
})
// .then(user => {
// user=user.toJSON()
// console.log("///////",tweetsCount)
// user["followersCount"] = followerCount
// user["followingCount"] = followingCount
// user["likesCount"] = likesCount
// user["tweetsCount"] = tweetsCount
// return res.json({
// status: 'success',
// message: '查詢成功!',
// ...user
// })
// })
.catch(err => next(err))
},

Expand Down
13 changes: 9 additions & 4 deletions middleware/api-auth.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
const passport = require('../config/passport') // 引入 passport
const helpers = require('../_helpers')
const authenticated = passport.authenticate('jwt', { session: false })
//const authenticated = passport.authenticate('jwt', { session: false })
const authenticated = (req, res, next) => {
passport.authenticate('jwt', { session: false }, (err, user) => {
if (err || !user) return res.status(401).json({ status: 'error', message: 'unauthorized' })
next()
})(req, res, next)
}
const authenticatedAdmin = (req, res, next) => {
//console.log("999999",helpers.getUser(req),"999999")
if (helpers.getUser(req).role==='admin' ) return next()
//if (helpers.getUser(req) ) return next()
if (helpers.getUser(req).role === 'admin') return next()
return res.status(403).json({ status: 'error', message: 'permission denied' })
}

module.exports = {
authenticated,
authenticatedAdmin
Expand Down
2 changes: 1 addition & 1 deletion routes/apis/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ const admin = require('./modules/admin')
const userController = require('../../controllers/apis/user-controller')
const { authenticated, authenticatedAdmin } = require('../../middleware/api-auth')
const { apiErrorHandler } = require('../../middleware/error-handler')
router.use('/admin', authenticated, authenticatedAdmin, admin)
router.use('/admin', authenticatedAdmin, admin)
router.post('/signin', passport.authenticate('local', { session: false }), userController.signIn)

router.get('/users/:id', authenticated, userController.getUser)
Expand Down
Loading

1 comment on commit 2bedfb4

@blade8128ch
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also feature : GET /api/users/:id

Please sign in to comment.