@@ -3,8 +3,8 @@ import Password, { hash, verify } from '../models/password'
33import { createSession , validateSession } from '../models/session'
44
55export 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 ) {
0 commit comments