Skip to content

Commit 64f5f8c

Browse files
committed
feat: setup global auth hooks
1 parent a9678b7 commit 64f5f8c

File tree

4 files changed

+25
-2
lines changed

4 files changed

+25
-2
lines changed

hooks/requireAuth.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
import { HookContext } from '@feathersjs/feathers';
2+
3+
export default async (context: HookContext): Promise<HookContext> => {
4+
if (!context.params.user) throw new Error('This endpoint requires auth!');
5+
return context;
6+
};
7+

hooks/tryAuthenticate.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
import { HookContext } from '@feathersjs/feathers';
2+
import { authenticate } from '@feathersjs/authentication';
3+
4+
5+
export default async (context: HookContext): Promise<HookContext> => {
6+
return authenticate('jwt')(context).catch(() => context);
7+
};
8+

services/index.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,19 @@ import Profiles from './profiles/profiles.service';
55
import Votes from './votes/votes.service';
66
import Auth from './auth/auth.service';
77

8+
import tryAuthenticate from '../hooks/tryAuthenticate';
9+
810
export default (app: Application): void => {
911
app.configure(Auth);
1012
app.configure(Users);
1113
app.configure(Polls);
1214
app.configure(Profiles);
1315
app.configure(Votes);
16+
17+
app.hooks({
18+
before: {
19+
all: tryAuthenticate
20+
}
21+
})
1422
};
1523

services/votes/votes.hooks.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { HookContext } from '@feathersjs/feathers';
2-
import { authenticate } from '@feathersjs/authentication';
2+
import requireAuth from '../../hooks/requireAuth';
33

44
const addUserId = async (context: HookContext): Promise<HookContext> => {
55
const { params: { user} } = context;
@@ -9,7 +9,7 @@ const addUserId = async (context: HookContext): Promise<HookContext> => {
99

1010
export default {
1111
before: {
12-
create: [authenticate('jwt'), addUserId]
12+
create: [requireAuth, addUserId]
1313
}
1414
};
1515

0 commit comments

Comments
 (0)