Nuxt.js middleware redirect based on role - vue.js

On login I want to redirect to different page based on role using the nuxt.js middleware.
This is my notAuthenticated middleware
export default function({ store, redirect }) {
// If the user is authenticated redirect to home page
if (store.state.auth) {
debugger
if (store.state.auth.role === 'admin') {
return redirect('/admin')
} else {
return redirect('/')
}
}
}
Problem is it does not redirect to /admin and I don't know how to debug it. Debugger is not working here.

Seems middleware didn't redirect me after login, so I had to use the router and redirect based on the role after the login has completed.
EDIT: As asked I'm adding also the code solution.
In my login function, after logging in I check the role of the user (which in my case was saved in the JWT token).
login(data) {
const self = this
this.$axios.post('/auth/login', data).then(function(response) {
const tkData = self.parseJwt(response.data.Token)
const auth = {
accessToken: response.data.Token,
email: tkData.email,
role: tkData.role
}
self.$store.commit('setAuth', auth)
Cookie.set('auth', auth)
if (tkData.role === 'admin') {
self.$router.push('/admin')
} else {
self.$router.push('/')
}
})
}
PS: You can check out my code and test it in my GitHub

Related

redirecting to specified page, after login - keycloak

I'm clicking on url which is redirecting me to some page on my website. Everything works fine until user is not logged in. How to redirect someone to url which I clicked after login? is there way to store this url or something?
I've tried so hard and get so far but in the end it doesnt really matters
You can use .redirectUri to set the redirect URL. Make sure the URL is also set in Valid redirect URIs of client.
const Login = (onAuthenticatedCallback) => {
keycloakInstance
.init({
...
})
.then(function (authenticated) {
if (authenticated) {
...
keycloakInstance.redirectUri = window.location.origin + "/HomePage"
} else {
alert("non authenticated")
}
})
.catch((e) => {
console.log(`keycloak init exception: ${e}`);
});
};

How to redirect from GraphQL middleware resolver on authentication fail?

Introduction:
I am using GraphQL Mesh as a gateway between my app and an API. I use Apollo Client as the GraphQL client. When a user wants to visit the first screen after hitting the log-in button, I do a query to load data from a CMS. This query has to go through the gateway. In the gateway I do an auth check to see if the user has a valid JTW access token, if not, I want to redirect back to the sign-in page. If the user has a token, he is let through.
The gateway is-auth.ts resolver:
const header = context.headers.authorization;
if (typeof header === "undefined") {
return new Error("Unauthorized: no access token found.");
} else {
const token = header.split(" ")[1];
if (token) {
try {
const user = jwt.verify(token, process.env.JWT_SECRET as string);
} catch (error) {
return new Error("Unauthorized: " + error);
}
} else {
return new Error("Unauthorized: no access token found.");
}
}
return next(root, args, context, info);
},
Problem: Right now, I am returning Errors in the authentication resolver of the gateway, hoping that I could pick them up in the error object that is sent to Apollo Client and then redirect off of that. Unfortunately, I don't get that option, since the Errors are thrown immediately, resulting in an error screen for the user (not what I want). I was hoping this would work in order to redirect to the sign-in from the client-side, but it does not work:
const { data, error } = await apolloClient(accessToken).query({
query: gql`
query {
...where my query is.
}
`,
});
if (error) {
return {
redirect: {
permanent: false,
destination: `/sign-in`,
},
};
}
Does anyone perhaps have a solution to this problem?
This is the GraphQL Mesh documentation on the auth resolver, for anyone that wants to see it: https://www.graphql-mesh.com/docs/transforms/resolvers-composition. Unfortunately, it doesn't say anything about redirects.
Kind regards.

add exception to vue navigation gards

I have a project buit in laravel and vue I added forgot password reset system. the system sends email password reset link. but when I click the link it redirects to login page
the vue router navigation guard code is
router.beforeEach((to, _, next) => {
const isLoggedIn = isUserLoggedIn()
//console.log('can navigate', to, canNavigate(to))
if(to.name=='auth-reset-password'){
return {name:'auth-reset-password'}
}
if (!canNavigate(to)) {
// Redirect to login if not logged in
if (!isLoggedIn) return next({ name: 'auth-login' })
// If logged in => not authorized
return next({ name: 'misc-not-authorized' })
}
// Redirect if logged in
if (to.meta.redirectIfLoggedIn && isLoggedIn) {
const userData = getUserData()
next(getHomeRouteForLoggedInUser(userData ? userData.role : null))
}
return next()
})
how do I add exception to router.beforeEach of password reset

Auth0 login redirect to page keeps on loading when using Firefox as browser

I use an Auth0 login that handles the login for my platform after logging in it redirects you to the platform. With chrome, this works perfectly but in Firefox it keeps reloading the redirect page. I used the standard auth0 code to implement the logic into my page. I'm not sure what is going wrong and even where to start looking for a solution? Does anyone ever experienced the same bug and can help me fix the issue and also explain what is going wrong?
auth.ts file :
export class AuthService {
// Create an observable of Auth0 instance of client
auth0Client$ = (from(
createAuth0Client({
domain: authConfig.domain,
client_id: authConfig.clientId,
redirect_uri: `${window.location.origin}`,
audience: authConfig.audience,
})
) as Observable<Auth0Client>).pipe(
shareReplay(1), // Every subscription receives the same shared value
catchError(err => throwError(err))
);
// Manage Acces Token
// Observable method to retrieve access token and make it available for use in application
getTokenSilently$(options?): Observable<string> {
return this.auth0Client$.pipe(
concatMap((client: Auth0Client) => from(client.getTokenSilently(options)))
);
}
// Define observables for SDK methods that return promises by default
// For each Auth0 SDK method, first ensure the client instance is ready
// concatMap: Using the client instance, call SDK method; SDK returns a promise
// from: Convert that resulting promise into an observable
isAuthenticated$ = this.auth0Client$.pipe(
concatMap((client: Auth0Client) => from(client.isAuthenticated())),
tap(res => (this.loggedIn = res))
);
handleRedirectCallback$ = this.auth0Client$.pipe(
concatMap((client: Auth0Client) => from(client.handleRedirectCallback()))
);
// Create subject and public observable of user profile data
private userProfileSubject$ = new BehaviorSubject<any>(null);
userProfile$ = this.userProfileSubject$.asObservable();
// Create a local property for login status
loggedIn: boolean = null;
constructor(private router: Router) {
// On initial load, check authentication state with authorization server
// Set up local auth streams if user is already authenticated
this.localAuthSetup();
// Handle redirect from Auth0 login
this.handleAuthCallback();
}
// When calling, options can be passed if desired
// https://auth0.github.io/auth0-spa-js/classes/auth0client.html#getuser
getUser$(options?): Observable<any> {
return this.auth0Client$.pipe(
concatMap((client: Auth0Client) => from(client.getUser(options))),
tap(user => this.userProfileSubject$.next(user))
);
}
private localAuthSetup() {
// This should only be called on app initialization
// Set up local authentication streams
const checkAuth$ = this.isAuthenticated$.pipe(
concatMap((loggedIn: boolean) => {
if (loggedIn) {
// If authenticated, get user and set in app
// NOTE: you could pass options here if needed
return this.getUser$();
}
// If not authenticated, return stream that emits 'false'
return of(loggedIn);
})
);
checkAuth$.subscribe();
}
login(redirectPath: string = '/') {
// A desired redirect path can be passed to login method
// (e.g., from a route guard)
// Ensure Auth0 client instance exists
this.auth0Client$.subscribe((client: Auth0Client) => {
// Call method to log in
client.loginWithRedirect({
redirect_uri: `${window.location.origin}`,
appState: { target: redirectPath },
});
});
}
private handleAuthCallback() {
// Call when app reloads after user logs in with Auth0
const params = window.location.search;
if (params.includes('code=') && params.includes('state=')) {
let targetRoute: string; // Path to redirect to after login processsed
const authComplete$ = this.handleRedirectCallback$.pipe(
// Have client, now call method to handle auth callback redirect
tap(cbRes => {
// Get and set target redirect route from callback results
targetRoute = cbRes.appState && cbRes.appState.target ? cbRes.appState.target : '/';
}),
concatMap(() => {
// Redirect callback complete; get user and login status
return combineLatest([this.getUser$(), this.isAuthenticated$]);
})
);
// Subscribe to authentication completion observable
// Response will be an array of user and login status
authComplete$.subscribe(([user, loggedIn]) => {
// Redirect to target route after callback processing
this.router.navigate([targetRoute]);
});
}
}
logout() {
// Ensure Auth0 client instance exists
this.auth0Client$.subscribe((client: Auth0Client) => {
// Call method to log out
client.logout({
client_id: authConfig.clientId,
returnTo: window.location.origin,
});
});
}
}
auth-guard.ts
export class AuthGuard implements CanActivate {
constructor(private auth: AuthService) {}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean> | Promise<boolean | UrlTree> | boolean {
return this.auth.isAuthenticated$.pipe(
tap(loggedIn => {
if (!loggedIn) {
this.auth.login(state.url);
}
})
);
}
}
I had this issue and found that it was because my browser was blocking third party cookies.
So my app was running on my own domain (or on localhost in dev mode), but I was using an auth0.com subdomain to log in with Auth0 and the browser was blocking cookies from auth0.com, which sent the auth0 JS in my app into an infinite loop of trying to check the logged in status, failing, refreshing the page, trying to check the logged in status, failing, refreshing the page, and so on.
It could be your browser's cookie settings or an ad blocking or privacy extension.

How can I have a seperate login page using Durandal that has a different layout then the shell?

I've read through Durandal login page redirect pattern wow, lots of code to do what I'd think would be pretty simple.
I've also read through https://groups.google.com/forum/#!topic/durandaljs/RdGpwIm1oOU as I'd like the login page to have a simple logo with a login form, but I'd also like routing for a registration and about page as well. The rest of my site will have a menu, header, etc which I don't want to show until the user is logged in. Also, I'm not sure how this approach would update when the user logs in.
Another code example that almost does what I want to do: https://github.com/Useful-Software-Solutions-Ltd/Durandal451/blob/master/Durandal451v2/App/global/session.js
So, what should I do? Is there an official way to do this? There seems to be a mish mash of things out there that people have tried. I would think this would be a really common occurrence but couldn't find anything on the main docs.
I'm not sure this is the simplest way, but this is what I got
you will need to add some extra function after app.start() is triggered.
main.js
var auth = require('authentication'); // Authentication module
app.start().then(function()
{
// This function will wait for the promise
auth.init().then(function(data)
{
// When successfully authenticate, set the root to shell
app.setRoot('views/shell');
}
});
authentication.js
define(function(require)
{
var app = require('durandal/app');
return {
init: function()
{
// Initialize authentication...
return system.defer(function(dfd)
{
// Check if user is authenticate or if there has stored token
var isAuthenticate = someOtherFunctiontoCheck();
if (isAuthenticate)
{
dfd.resolve(true); // return promise
}
else
{
// When not authenticate, set root to login page
app.setRoot('views/login');
}
}
}
};
});
good luck! :)
UPDATE
login.js
define(function(require)
{
var ko = require('knockout');
var auth = require('authentication');
var username = ko.observable();
var password = ko.observable();
return {
username: username,
password: password,
submitForm: function()
{
// Do a login, if success, auth module will take care of it
// and here will take of the error
auth.login(username(), password()).error(function()
{
// notify user about the error (e.g invalid credentials)
});
}
};
});
Authentication.js
define(function(require)
{
var app = require('durandal/app');
return {
init: function()
{
// Initialize authentication...
return system.defer(function(dfd)
{
// Check if user is authenticate or if there has stored token
var isAuthenticate = someOtherFunctiontoCheck();
if (isAuthenticate)
{
dfd.resolve(true); // return promise
}
else
{
// When not authenticate, set root to login page
app.setRoot('views/login');
}
}
},
login: function(username, password)
{
// do authenticate for login credentials (e.g for retrieve auth token)
return $.ajax({
url : 'api/login',
type : 'POST',
data : {
username: username,
password: password
}
}).then(function(token){
// on success, stored token and set root to shell
functionToStoreToken(token);
// Set root to shell
app.setRoot('views/shell');
});
}
};
});