refactor: put passport to auth folder

This commit is contained in:
wancat committed 2023-09-11 23:38:29 +08:00
1 parent 41111f5036
commit 030dc95e24
8 files changed
+58 -76

No files matched your search

+7 -29
View File
@@ -1,40 +1,18 @@
import { Router } from 'express'
import passport from 'passport'
import LocalStrategy from 'passport-local'
import bcrypt from 'bcrypt'
import User from '../../models/user.js'
import { genUserJWT } from '../../utils/auth.js'
passport.use(
new LocalStrategy(async function verify(username, password, done) {
try {
const user = await User.findOne({ username })
if (!user) {
return done(null, false, { message: 'Incorrect username.' })
}
const isPasswordValid = await bcrypt.compare(
password,
user.hashedPassword
)
if (!isPasswordValid) {
return done(null, false, { message: 'Incorrect username or password.' })
}
return done(null, user)
} catch (err) {
return done(err)
}
})
)
import { genJwt } from '../../utils/auth.js'
const router = Router()
async function issueToken(req, res) {
const token = await genUserJWT(req.user)
res.json({
token,
const { user } = req
const token = await genJwt({
_id: user.id,
username: user.username,
email: user.email,
})
res.json({ token })
}
router.post(
+6 -16
View File
@@ -1,23 +1,9 @@
import { Router } from 'express'
import passport from 'passport'
import { Strategy as JwtStrategy, ExtractJwt } from 'passport-jwt'
import sessions from './sessions.js'
import quests from './quests.js'
import commands from './commands.js'
import authRouter from './auth.js'
import config from '../../config.js'
const jwtOptions = {
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: config.jwtSecret,
issuer: 'linuxodyssey.xyz',
}
passport.use(
new JwtStrategy(jwtOptions, function verifyJwt(jwtPayload, done) {
return done(null, jwtPayload)
})
)
const router = Router()
@@ -26,12 +12,16 @@ router.get('/', (req, res) => {
})
router.use(authRouter)
router.use('/quests', quests)
router.use(
'/sessions',
passport.authenticate('jwt', { session: false }),
sessions
)
router.use('/quests', quests)
router.use('/commands', commands)
router.use(
'/commands',
passport.authenticate('jwt', { session: false }),
commands
)
export default router