Add password-based auth with JWT and remember-me
This commit is contained in:
1 parent
89deb869ab
commit
0042e7150c
10 files changed
+281
-37
No files matched your search
@@ -0,0 +1,43 @@
|
||||
const jwt = require('jsonwebtoken');
|
||||
const configService = require('../services/configService');
|
||||
|
||||
class AuthController {
|
||||
login(req, res) {
|
||||
const { password, remember } = req.body;
|
||||
const settings = configService.getSettings();
|
||||
const authPassword = settings.authPassword;
|
||||
const jwtSecret = settings.jwtSecret || 'showy-default-secret';
|
||||
|
||||
if (!authPassword) {
|
||||
return res.status(500).json({ error: 'Auth password not configured' });
|
||||
}
|
||||
|
||||
if (password !== authPassword) {
|
||||
return res.status(401).json({ error: 'Invalid password' });
|
||||
}
|
||||
|
||||
const expiresIn = remember ? '3650d' : '24h';
|
||||
const token = jwt.sign({ authed: true }, jwtSecret, { expiresIn });
|
||||
|
||||
res.json({ token, expiresIn });
|
||||
}
|
||||
|
||||
verify(req, res) {
|
||||
const auth = req.headers.authorization;
|
||||
if (!auth || !auth.startsWith('Bearer ')) {
|
||||
return res.status(401).json({ valid: false });
|
||||
}
|
||||
|
||||
const settings = configService.getSettings();
|
||||
const jwtSecret = settings.jwtSecret || 'showy-default-secret';
|
||||
|
||||
try {
|
||||
jwt.verify(auth.slice(7), jwtSecret);
|
||||
res.json({ valid: true });
|
||||
} catch {
|
||||
res.status(401).json({ valid: false });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new AuthController();
|
||||
Reference in new issue
Block a user