/ src / services / users / users.hooks.ts
users.hooks.ts
 1  import * as feathersAuthentication from "@feathersjs/authentication";
 2  import * as local from "@feathersjs/authentication-local";
 3  import { Forbidden, NotAuthenticated } from "@feathersjs/errors";
 4  
 5  const { authenticate } = feathersAuthentication.hooks;
 6  const { hashPassword, protect } = local.hooks;
 7  
 8  export default {
 9  	before: {
10  		all: [],
11  		find: [authenticate("jwt")],
12  		get: [authenticate("jwt")],
13  		create: [hashPassword("password")],
14  		update: [hashPassword("password"), authenticate("jwt")],
15  		patch: [hashPassword("password"), authenticate("jwt")],
16  		remove: [authenticate("jwt")],
17  	},
18  
19  	after: {
20  		all: [
21  			// Make sure the password field is never sent to the client
22  			// Always must be the last hook
23  			protect("password"),
24  		],
25  		find: [],
26  		get: [],
27  		create: [],
28  		update: [],
29  		patch: [],
30  		remove: [],
31  	},
32  
33  	error: {
34  		all: [
35  			// biome-ignore lint/suspicious/noExplicitAny: <explanation>
36  			async (context: any) => {
37  				if (context.error instanceof NotAuthenticated) {
38  					// Return a custom response for NotAuthenticated error
39  					return {
40  						statusCode: 401,
41  						message: "You are not authenticated",
42  					};
43  					// biome-ignore lint/style/noUselessElse: <explanation>
44  				} else if (context.error.code === 403) {
45  					// Return a custom response for Forbidden error
46  					return {
47  						statusCode: 403,
48  						message: "You are not authorized to access this",
49  					};
50  				}
51  			},
52  		],
53  		find: [],
54  		get: [],
55  		create: [],
56  		update: [],
57  		patch: [],
58  		remove: [],
59  	},
60  };