Skip to content

Commit

Permalink
feat: add ws auth (#177)
Browse files Browse the repository at this point in the history
* feat(client): ws auth initial setup

* feat(server): ws auth initial setup

* chore(server): remove redundant console log

* feat(client): update ws auth logic

* update ws auth logic

* remove redundant code

* Fix lint error

* Fix types properly
  • Loading branch information
Akirtovskis committed Oct 8, 2020
1 parent 1c1a216 commit 0ad5ff7
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 1 deletion.
5 changes: 5 additions & 0 deletions client/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,11 @@ const wsLink = new WebSocketLink({
uri: `${config.serverWsUrl}/graphql`,
options: {
reconnect: true,
connectionParams: () => {
return {
token: localStorage.getItem('accessToken'),
};
},
},
});

Expand Down
9 changes: 8 additions & 1 deletion client/src/modules/auth/AuthContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,14 @@ const AuthProvider = ({ children }: AuthProviderProps) => {
user?: JwtUser;
}>(() => {
const token = localStorage.getItem('accessToken');
const decodedToken = token ? jwtDecode<JwtUser>(token) : undefined;
let decodedToken;
if (token) {
try {
decodedToken = jwtDecode<JwtUser>(token);
} catch (e) {
//Invalid token
}
}
return {
loggedIn: Boolean(token),
user: decodedToken
Expand Down
18 changes: 18 additions & 0 deletions server/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -223,12 +223,30 @@ const resolvers: Resolvers<{ userId?: string }> = {
...customResolvers,
};

interface SubscriptionContext {
token?: string;
}

const apolloServer = new ApolloServer({
typeDefs,
resolvers: {
...resolvers,
DateTime: DateTimeResolver,
},
subscriptions: {
onConnect: (context: SubscriptionContext) => {
if (!context.token) {
throw new Error('Missing auth token');
}
try {
jsonwebtoken.verify(context.token, config.jwtSecret);
// TODO ARTURS : FIND USER FN FOR EXTRA LAYER OF SECURITY
} catch (e) {
throw new Error('Invalid token');
}
},
},

context: ({ req, connection }) => {
if (connection) {
return connection.context;
Expand Down

0 comments on commit 0ad5ff7

Please sign in to comment.