Skip to content

Commit 952700c

Browse files
Tony BRIETpi0
authored andcommitted
fix: ssr and code reduction
1 parent 0ca4169 commit 952700c

File tree

1 file changed

+25
-23
lines changed

1 file changed

+25
-23
lines changed

lib/templates/auth.middleware.js

Lines changed: 25 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,31 @@
11
import middleware from './middleware'
22

3-
middleware.auth = function authMiddleware ({ route, redirect, store }) {
4-
route.matched.some((currentRoute) => {
5-
// Retriving Auth Guard status through route's component options.
6-
const options = currentRoute.components.default.options
7-
const guarded = options.guarded
3+
const isRouteGuarded = ({ route: { matched: m } }) =>
4+
m.some(({ components: c }) => process.server
5+
? Object.values(c).some(({ _Ctor: _c }) =>
6+
Object.values(_c).some(({ options: o }) => o && o.guarded)
7+
)
8+
: Object.values(c).some(o => o.options.guarded)
9+
)
810

9-
// Only apply the middleware to guarded routes
10-
if (guarded) {
11-
// Checking if guest redirection middleware is enabled
12-
<% if (options.redirect.guest) { %>
13-
// Guest is redirected back to login page
14-
// and excluding redirected paths from hitting the middleware again.
15-
if (!store.getters['auth/loggedIn'] && route.path !== '<%= options.redirect.notLoggedIn %>') {
16-
return redirect('<%= options.redirect.notLoggedIn %>')
17-
}
1811

19-
// Checking if user redirection middleware is enabled
20-
<% } if (options.redirect.user) { %>
21-
// Guest is redirected back to login page
22-
// and excluding redirected paths from hitting the middleware again.
23-
if (store.getters['auth/loggedIn'] && route.path !== '<%= options.redirect.loggedIn %>') {
24-
return redirect('<%= options.redirect.loggedIn %>')
25-
}
26-
<% } %>
12+
middleware.auth = function(context) {
13+
const { route: {path: p}, redirect: r, store: s } = context
14+
15+
// Registering guest and auth routes.
16+
let guestRoute = '<%= options.redirect.notLoggedIn %>'
17+
let authRoute = '<%= options.redirect.loggedIn %>'
18+
19+
// Retriving Auth Guard status through route's component options.
20+
let g = isRouteGuarded(context)
21+
// Apply the middleware to guarded routes
22+
if (g) {
23+
if (<%= options.redirect.guest %> && !s.getters['auth/loggedIn'] && guestRoute !== p) {
24+
return r(guestRoute)
25+
}
26+
27+
if (<% options.redirect.user %> && s.getters['auth/loggedIn'] && authRoute !== p) {
28+
return r(authRoute)
2729
}
28-
});
30+
}
2931
}

0 commit comments

Comments
 (0)