@@ -24,16 +24,23 @@ struct QuoteServiceImpl: APIProtocol, OpenAPILambdaHttpApi {
24
24
25
25
let logger : Logger
26
26
27
- func register( transport: OpenAPILambdaTransport , middlewares: [ ServerMiddleware ] ) throws {
27
+ func register( transport: OpenAPILambdaTransport ) throws {
28
+
28
29
// you have a chance here to customize the routes, for example
29
30
try transport. router. get ( " /health " ) { _, _ in
30
31
" OK "
31
32
}
33
+ logger. trace ( " Available Routes \n \( transport. router) " ) // print the router tree (for debugging purposes)
32
34
35
+ // to log all request and their response, add a logging middleware
33
36
let loggingMiddleware = LoggingMiddleware ( logger: logger)
34
- try self . registerHandlers ( on: transport, middlewares: middlewares + [ loggingMiddleware] )
35
37
36
- logger. trace ( " Available Routes \n \( transport. router) " ) // print the router tree (for debugging purposes)
38
+ // This app includes a sample authorization middleware
39
+ // It transforms the bearer token into a username.
40
+ // The user can be access through a TaskLocal variable.
41
+ let authenticationMiddleware = self . authenticationMiddleware ( )
42
+
43
+ try self . registerHandlers ( on: transport, middlewares: [ loggingMiddleware, authenticationMiddleware] )
37
44
}
38
45
39
46
static func main( ) async throws {
@@ -93,6 +100,10 @@ struct QuoteServiceImpl: APIProtocol, OpenAPILambdaHttpApi {
93
100
94
101
func getQuote( _ input: Operations . getQuote . Input ) async throws -> Operations . getQuote . Output {
95
102
103
+ // You can log events to the AWS Lambda logs here
104
+ guard let user = AuthenticationServerMiddleware . User. current else { return . unauthorized( . init( ) ) }
105
+ logger. trace ( " GetQuote for \( user) - Started " )
106
+
96
107
let symbol = input. path. symbol
97
108
98
109
var date : Date = Date ( )
@@ -111,6 +122,31 @@ struct QuoteServiceImpl: APIProtocol, OpenAPILambdaHttpApi {
111
122
timestamp: date
112
123
)
113
124
125
+ logger. trace ( " GetQuote - Returning " )
126
+
114
127
return . ok( . init( body: . json( price) ) )
115
128
}
129
+
130
+ func authenticationMiddleware( ) -> AuthenticationServerMiddleware {
131
+ AuthenticationServerMiddleware ( authenticate: { stringValue in
132
+ // Warning: this is an overly simplified authentication strategy, checking
133
+ // for well-known tokens.
134
+ //
135
+ // In your project, here you would likely call out to a library that performs
136
+ // a cryptographic validation, or similar.
137
+ //
138
+ // The code is for illustrative purposes only and should not be used directly.
139
+ switch stringValue {
140
+ case " 123 " :
141
+ // A known user authenticated.
142
+ return . init( name: " Seb " )
143
+ case " 456 " :
144
+ // A known user authenticated.
145
+ return . init( name: " Nata " )
146
+ default :
147
+ // Unknown credentials, no authenticated user.
148
+ return nil
149
+ }
150
+ } )
151
+ }
116
152
}
0 commit comments