@@ -24,10 +24,11 @@ const userExists = async (
2424 res : Response ,
2525 next : NextFunction ,
2626) : Promise < MiddlewareUser > => {
27- const { username } = req . body ;
27+ const { username } = req . body as { username : string } ;
28+ const sanitizedUsername = username . toString ( ) ;
2829
2930 try {
30- const user = await User . findOne ( { username : { $eq : username } } ) ;
31+ const user = await User . findOne ( { username : { $eq : sanitizedUsername } } ) ;
3132
3233 if ( user ) {
3334 return res . status ( 409 ) . json ( { error : 'User already exists' } ) ;
@@ -52,10 +53,23 @@ const validateUser = async (
5253 next : NextFunction ,
5354) : Promise < MiddlewareUser > => {
5455 try {
55- const { username, password } = req . body ;
56- const user = await User . findOne ( { username : { $eq : username } } ) ;
56+ const { username, password } = req . body as {
57+ username : string ;
58+ password : string ;
59+ } ;
60+ const [ sanitizedUsername , sanitizedPassword ] = [
61+ username . toString ( ) ,
62+ password . toString ( ) ,
63+ ] ;
5764
58- if ( user ?. password && ( await bcrypt . compare ( password , user . password ) ) ) {
65+ const user = await User . findOne ( {
66+ $expr : { $eq : [ '$username' , sanitizedUsername ] } ,
67+ } ) ;
68+
69+ if (
70+ user ?. password &&
71+ ( await bcrypt . compare ( sanitizedPassword , user . password ) )
72+ ) {
5973 return next ( ) ;
6074 }
6175
@@ -75,10 +89,13 @@ const isAdmin = async (
7589 res : Response ,
7690 next : NextFunction ,
7791) : Promise < MiddlewareUser > => {
78- const { username } = req . body ;
92+ const { username } = req . body as { username : string } ;
93+ const sanitizedUsername = username . toString ( ) ;
7994
8095 try {
81- const user = await User . findOne ( { username : { $eq : username } } ) ;
96+ const user = await User . findOne ( {
97+ $expr : { $eq : [ '$username' , sanitizedUsername ] } ,
98+ } ) ;
8299
83100 if ( user ?. isAdmin ) {
84101 return next ( ) ;
@@ -104,9 +121,10 @@ const validateToken = async (
104121 try {
105122 const { authorization } = req . headers ;
106123 const token = authorization ?. replace ( 'Bearer ' , '' ) ;
124+ if ( ! token ) return res . status ( 401 ) . json ( boom . unauthorized ( ) ) ;
107125 if ( secret ) {
108- const decoded = jwt . verify ( token as string , secret ) ;
109- return decoded ? next ( ) : res . json ( boom . unauthorized ( ) ) ;
126+ const decoded = jwt . verify ( token , secret ) ;
127+ return decoded ? next ( ) : res . status ( 401 ) . json ( boom . unauthorized ( ) ) ;
110128 }
111129 } catch ( error ) {
112130 return res . status ( 401 ) . json ( boom . unauthorized ( ) ) ;
0 commit comments