@@ -3,8 +3,7 @@ import '@fastify/jwt';
33import {
44 FastifyInstance ,
55 FastifyPluginAsync ,
6- FastifyReply ,
7- FastifyRequest ,
6+ preHandlerHookHandler ,
87} from 'fastify' ;
98import fastifyAuth0Verify , { Authenticate } from 'fastify-auth0-verify' ;
109import fp from 'fastify-plugin' ;
@@ -54,67 +53,57 @@ export default fp<{authProvider?: FastifyPluginAsync}>(
5453 } ) ;
5554 }
5655
57- async function authorize (
58- req : FastifyRequest ,
59- reply : FastifyReply ,
60- options : AuthorizeOptions = {
61- mustBeAuthenticated : true ,
62- } ,
63- ) {
64- try {
65- await fastify . authenticate ( req , reply ) ;
66- } catch ( e ) {
67- if ( options . mustBeAuthenticated ) {
68- throw fastify . httpErrors . unauthorized ( ) ;
56+ const authorize : ( options : AuthorizeOptions ) => preHandlerHookHandler =
57+ ( options = { mustBeAuthenticated : true } ) =>
58+ async ( req , reply ) => {
59+ try {
60+ await fastify . authenticate ( req , reply ) ;
61+ } catch ( e ) {
62+ if ( options . mustBeAuthenticated ) {
63+ throw fastify . httpErrors . unauthorized ( ) ;
64+ }
6965 }
70- }
7166
72- const emailClaim = `${ fastify . config . AUTH0_CLIENT_CLAIMS } /email` ;
67+ const emailClaim = `${ fastify . config . AUTH0_CLIENT_CLAIMS } /email` ;
7368
74- if ( ! req . user ) {
75- req . appUserOptional = null ;
76- return ;
77- }
78-
79- const email = req . user [ emailClaim ] as string ;
69+ if ( ! req . user ) {
70+ req . appUserOptional = null ;
71+ return ;
72+ }
8073
81- if ( ! email ) {
82- throw fastify . httpErrors . badRequest ( 'No valid user data' ) ;
83- }
74+ const email = req . user [ emailClaim ] as string ;
8475
85- const user = await fastify . prisma . user . findFirst ( {
86- where : {
87- email,
88- } ,
89- } ) ;
76+ if ( ! email ) {
77+ throw fastify . httpErrors . badRequest ( 'No valid user data' ) ;
78+ }
9079
91- if ( ! user ) {
92- req . appUser = await fastify . prisma . user . create ( {
93- data : {
80+ const user = await fastify . prisma . user . findFirst ( {
81+ where : {
9482 email,
9583 } ,
9684 } ) ;
97- } else {
98- req . appUser = user ;
99- }
10085
101- req . appUserOptional = req . appUser ;
102- }
86+ if ( ! user ) {
87+ req . appUser = await fastify . prisma . user . create ( {
88+ data : {
89+ email,
90+ } ,
91+ } ) ;
92+ } else {
93+ req . appUser = user ;
94+ }
95+
96+ req . appUserOptional = req . appUser ;
97+ } ;
10398
104- fastify . decorateRequest ( 'appUser' , null ) ;
105- fastify . decorate ( 'authorize' , authorize ) ;
99+ fastify . decorate ( 'verifyAuth0' , authorize ) ;
106100 } ,
107101) ;
108102
109103declare module 'fastify' {
110104 interface FastifyInstance {
111- authorize : (
112- req : FastifyRequest ,
113- reply : FastifyReply ,
114- options ?: AuthorizeOptions ,
115- ) => void ;
105+ verifyAuth0 : ( options ?: AuthorizeOptions ) => preHandlerHookHandler ;
116106 }
117-
118107 interface FastifyRequest {
119108 appUser : User ;
120109 appUserOptional : User | null ;
0 commit comments