mirror of
https://github.com/linux-odyssey/linux-odyssey.git
synced 2026-11-06 03:20:13 +08:00
feat: add password login
This commit is contained in:
1 parent
a5dbcd7db4
commit
bcdd04715d
8 files changed
+390
-12
No files matched your search
@@ -0,0 +1,46 @@
|
||||
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)
|
||||
}
|
||||
})
|
||||
)
|
||||
|
||||
const router = Router()
|
||||
|
||||
async function issueToken(req, res) {
|
||||
const token = await genUserJWT(req.user)
|
||||
res.json({
|
||||
token,
|
||||
})
|
||||
}
|
||||
|
||||
router.post(
|
||||
'/login/password',
|
||||
passport.authenticate('local', { session: false }),
|
||||
issueToken
|
||||
)
|
||||
|
||||
export default router
|
||||
Reference in new issue
Block a user