Skip to content

Commit c35db02

Browse files
committed
🔒 Refactor password handling: improve environment variable checks #37
1 parent d38b2a4 commit c35db02

File tree

2 files changed

+17
-4
lines changed

2 files changed

+17
-4
lines changed

server/src/controllers/password.ts

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,8 @@ import Password, { hash, verify } from '../models/password'
33
import { createSession, validateSession } from '../models/session'
44

55
export const checkPassword = async (request: FastifyRequest) => {
6-
const canBeReset: boolean = !!process.env.CAN_BE_RESET || false
7-
const allowPassword: boolean = !!process.env.ALLOW_PASSWORD || false
6+
const canBeReset = process.env.CAN_BE_RESET === 'true'
7+
const allowPassword = process.env.ALLOW_PASSWORD === 'true'
88

99
const havePassword = !!(await Password.findOne({ where: {} }))
1010
const sessionId = request.cookies.sessionId
@@ -18,9 +18,22 @@ export const checkPassword = async (request: FastifyRequest) => {
1818
return { allowPassword, needPassword: havePassword, havePassword, canBeReset }
1919
}
2020

21-
export const setPassword = async (request: FastifyRequest) => {
21+
export const setPassword = async (request: FastifyRequest, reply: FastifyReply) => {
2222
const { password } = request.body as { password: string }
2323
const existingPassword = await Password.findOne({ where: {} })
24+
25+
if (typeof password !== 'string' || !password.trim()) {
26+
return reply.code(400).send({ message: 'Password is required' })
27+
}
28+
29+
// If password already exists, only authenticated session can update it.
30+
if (existingPassword) {
31+
const sessionId = request.cookies.sessionId
32+
if (!sessionId || !(await validateSession(sessionId))) {
33+
return reply.code(401).send({ message: 'Unauthorized' })
34+
}
35+
}
36+
2437
const hashStr = await hash(password)
2538

2639
if (existingPassword) {

server/src/middleware/auth.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { FastifyRequest, FastifyReply } from 'fastify'
22
import fp from 'fastify-plugin'
33
import { checkPassword } from '../controllers/password'
44

5-
const whiteList = ['/api/heart', '/api/password/check', '/api/password/verify', '/api/password/set']
5+
const whiteList = ['/api/heart', '/api/password/check', '/api/password/verify']
66

77
export default fp(async (fastify) => {
88
fastify.addHook('preHandler', async (request: FastifyRequest, reply: FastifyReply) => {

0 commit comments

Comments
 (0)