@@ -2,6 +2,7 @@ import { z } from "zod";
2
2
import { RequestHandler } from "express" ;
3
3
import { OAuthRegisteredClientsStore } from "../clients.js" ;
4
4
import { OAuthClientInformationFull } from "../../../shared/auth.js" ;
5
+ import { InvalidRequestError , InvalidClientError } from "../errors.js" ;
5
6
6
7
export type ClientAuthenticationMiddlewareOptions = {
7
8
/**
@@ -26,38 +27,34 @@ declare module "express-serve-static-core" {
26
27
27
28
export function authenticateClient ( { clientsStore } : ClientAuthenticationMiddlewareOptions ) : RequestHandler {
28
29
return async ( req , res , next ) => {
29
- let client_id , client_secret ;
30
30
try {
31
- const result = ClientAuthenticatedRequestSchema . parse ( req . body ) ;
32
- client_id = result . client_id ;
33
- client_secret = result . client_secret ;
34
- } catch ( error ) {
35
- res . status ( 400 ) . json ( {
36
- error : "invalid_request" ,
37
- error_description : String ( error ) ,
38
- } ) ;
39
- return ;
40
- }
31
+ let client_id , client_secret ;
32
+ try {
33
+ const result = ClientAuthenticatedRequestSchema . parse ( req . body ) ;
34
+ client_id = result . client_id ;
35
+ client_secret = result . client_secret ;
36
+ } catch ( error ) {
37
+ throw new InvalidRequestError ( String ( error ) ) ;
38
+ }
41
39
42
- const client = await clientsStore . getClient ( client_id ) ;
43
- if ( ! client ) {
44
- // TODO: Return 401 with WWW-Authenticate if Authorization header was used
45
- res . status ( 400 ) . json ( {
46
- error : "invalid_client" ,
47
- error_description : "Invalid client_id" ,
48
- } ) ;
49
- return ;
50
- }
40
+ const client = await clientsStore . getClient ( client_id ) ;
41
+ if ( ! client ) {
42
+ throw new InvalidClientError ( "Invalid client_id" ) ;
43
+ }
51
44
52
- if ( client . client_secret !== client_secret ) {
53
- res . status ( 400 ) . json ( {
54
- error : "invalid_client" ,
55
- error_description : "Invalid client_secret" ,
56
- } ) ;
57
- return ;
58
- }
45
+ if ( client . client_secret !== client_secret ) {
46
+ throw new InvalidClientError ( "Invalid client_secret" ) ;
47
+ }
59
48
60
- req . client = client ;
61
- next ( ) ;
49
+ req . client = client ;
50
+ next ( ) ;
51
+ } catch ( error ) {
52
+ if ( error instanceof InvalidRequestError || error instanceof InvalidClientError ) {
53
+ res . status ( 400 ) . json ( error . toResponseObject ( ) ) ;
54
+ } else {
55
+ console . error ( "Unexpected error authenticating client:" , error ) ;
56
+ res . status ( 500 ) . end ( "Internal Server Error" ) ;
57
+ }
58
+ }
62
59
}
63
60
}
0 commit comments