My run block is as follows:
angular.module('app', [...]).run(['$transitions', '$state', 'EmployeeService', ($transitions, $state, EmployeeService) => {
$transitions.onBefore(
{ to: 'app.*' },
() => EmployeeService.checkAuth().then(() => {
console.log("run success");
},
() => {
console.log("run caught");
return $state.target('login');
}),
{priority: 10}
);
}])
And for some reason it executes for states 'app' and 'login' though they don't match 'app.*' match criteria, and thus it brings me to infinite loop when performing the logout. What is the right syntax to specify the match criteria ? I've already looked here:
https://ui-router.github.io/ng1/docs/latest/interfaces/transition.hookmatchcriteria.html
Edit: Posting routes configurations as requested
Routes for the main module (includes 'app' state which shouldn't fire the auth check):
export default mainPageRoutesConfig;
function mainPageRoutesConfig($stateProvider, $urlRouterProvider, $locationProvider) {
"ngInject";
$locationProvider.html5Mode(true).hashPrefix('!');
$urlRouterProvider.otherwise('/');
$stateProvider
.state('app', {
url: '/',
component: 'main'
})
.state('app.timesheet', {
url: 'timesheet',
component: 'timesheet'
})
.state('app.saveHours', {
url: 'saveTaskHours',
component: 'saveTaskHours',
params: {
timesheet:null
}
})
}
Routes for the employee module (includes 'login' state which shouldn't fire the auth check as well):
export default employeesRoutesConfig;
function employeesRoutesConfig($stateProvider, $urlRouterProvider, $locationProvider) {
"ngInject";
$locationProvider.html5Mode(true).hashPrefix('!');
$urlRouterProvider.otherwise('/');
$stateProvider
.state('login', {
url: 'login',
component: 'login'
})
.state('app.employeesList', {
url: 'employees',
component: 'employeesList'
})
.state('app.saveEmployee', {
url: 'employee/?Id',
component: 'saveEmployee'
})
.state('app.deleteEmployee', {
url: 'employee/:Id',
component: 'deleteEmployee'
})
.state('app.employeePage', {
url: 'profile/:Id',
component: 'employeePage'
})
}
The solution (though not really an answer) was to specify match criteria as a function:
{
to: function(state) {
return state.name !== 'app.login' && state.name !== 'app.error';
}
}
And the full code (after moving to separate file):
export default ($transitions, $state, EmployeeService) => {
$transitions.onBefore(
{
to: function(state) {
return state.name !== 'app.login' && state.name !== 'app.error';
}
},
() => EmployeeService.checkAuth().then(() => {
console.log("run block. Authorization check succeeded");
},
() => {
console.log("run block. Authorization check failed");
return $state.target('app.login');
}),
{priority: 10}
);
}])
Related
I want to redirect logged in user if the comeback to my app the will redirected to home not to log in page.
in my login function like this
login(){
this.googlePlus.login({
'webClientId' : '927898787134-spvfdmvm9apq0e1fo2efvvura8vqpid8.apps.googleusercontent.com',
'offile' : true
}).then(res=>{
firebase.auth().signInWithCredential(firebase.auth.GoogleAuthProvider.credential(res.idToken))
.then(suc=>{
// console.log('users', JSON.stringify(suc));
localStorage.setItem('user', JSON.stringify(suc));
this.router.navigate(["/tabs/home"]);
}).catch(ns=>{
alert('Unsucessful');
})
})
}
i have user data in my localStorage, i think i can check whether the user token is exist on localStorage or not. but when i try this in my login page
ionViewWillEnter() {
firebase.auth().onAuthStateChanged(function(user) {
if (!user) {
console.log("user is not logged in");
} else {
console.log("user is logged in");
this.router.navigateByUrl('/tabs/home');
return;
}
});
}
it doesn't redirected to home, did anyone know exactly how to do that?
after trying to insert to app.component.ts my code like this
initializeApp() {
this.platform.ready().then(() => {
this.statusBar.overlaysWebView(true);
this.statusBar.show();
firebase.auth().onAuthStateChanged(function(user) {
if (!user) {
console.log("user is not logged in");
} else {
console.log("user is logged in");
this.router.navigateByUrl('/home');
return;
}
});
});
}
above code give me this error
heres my app-routing.module
const routes: Routes = [
{
path: '',
loadChildren: () => import('./tabs/tabs.module').then(m => m.TabsPageModule)
},
{ path: 'login', loadChildren: './login/login.module#LoginPageModule' },
{ path: 'welcome', loadChildren: './welcome/welcome.module#WelcomePageModule' },
{ path: 'settings', loadChildren: './settings/settings.module#SettingsPageModule' }
];
#NgModule({
imports: [
RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
],
exports: [RouterModule]
})
export class AppRoutingModule {}
try to put it in app.component.ts after constractor() { here your code }
I want to intercept request headers for my application globally for all the requests and routes including html,js ,css
Tried below code but didn't work
tried cy.server
cy.route
code that i tried for intercepting.
'use strict'
describe(`TodoMVC using Cypress`, function () {
it('passing request header', () => {
cy.server({
whitelist: (xhr) => {
return xhr.method === 'GET' && /\.(jsx?|html|css)(\?.*)?$/.test(xhr.url)
},
onAnyRequest: (route, proxy) => {
proxy.xhr.setRequestHeader('Referer', '***'),
proxy.xhr.setRequestHeader('Authorization','***')
}
})
var options = {
url: 'http://localhost:8080',
headers: {'Referer': '***','Authorization' :'**='}
};
cy.visit(options);
})
})
I'm unable to login with front-end might be problem with Angular-ui-Router. When I click on login button first I got an error as 'Possibly unhandled rejection' then I injected '$qProvider' in config file after adding $qProvider I don't see any error in console but the page is not changing it state whereas in the network tab i can see the Token is sent from the server. Can some one please help me.
App.config.js
angular.module('myApp', ['ui.router', 'myAppModel'])
.config(function($qProvider, $stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/');
$qProvider.errorOnUnhandledRejections(false);
$stateProvider
.state('base', {
abstract: true,
views: {
'nav#': {
template: '<navigation1></navigation1>'
}
}
})
.state('base.login', {
parent: 'base',
url: '/',
views: {
'main#': {
template: '<login></login>'
}
}
})
.state('base.register', {
parent: 'base',
url: '/register',
views: {
'main#': {
template: '<register></register>'
}
}
})
.state('base.dashboard', {
parent: 'base',
url: '/dashboard',
views: {
'main#': {
template: '<dashboard></dashboard>'
}
}
})
});
login.js
angular.module('myAppModel')
.component('login', {
templateUrl: '/components/login/login.html',
controller: function loginCtrl(Authentication, $state) {
var ctrl = this;
ctrl.pageHeader = 'Login';
ctrl.credentials = {
email: '',
password: ''
};
ctrl.onSubmit = function () {
ctrl.formError = '';
if(!ctrl.credentials.email || !ctrl.credentials.password) {
ctrl.formError = 'All fields required, please try again';
return false;
}else {
ctrl.doLogin();
}
};
ctrl.doLogin = function () {
ctrl.formError = '';
Authentication.login(ctrl.credentials).then(function(status) {
console.log(status);
$state.go('base.dashboard');
});
};
}
});
Authentication-service.js
angular.module('myAppModel')
.service('Authentication', function ($window, $http) { //Register new service with application and inject $window service
var saveToken = function (token) { //create a saveToken method to save a value to localStorage
$window.localStorage['app-token'] = token;
};
var getToken = function () { //Create a getToken method to read a value from localStorage
return $window.localStorage['app-token'];
}
var register = function (user) {
return $http.post('/api/users/register', user).then(function(data){
saveToken(data.token);
});
};
var login = function (user) {
return $http.post('/api/users/login', user).then(function (data) {
saveToken(data.token);
});
};
var logout = function () {
$window.localStorage.removeItem('app-token');
};
var isLoggedIn = function () {
var token = getToken(); //Get token from storage
if(token) { //If token exists get payload decode it, and parse it to JSON
var payload = JSON.parse($window.atob(token.split('.')[1]));
return payload.exp > Date.now() / 1000; //validate whether expiry date has passed
}else {
return false;
}
};
//Getting User Information from the JWT
var currentUser = function () {
if (isLoggedIn()) {
var token = getToken();
var payload = JSON.parse($window.atob(token.split('.')[1]));
return {
email: payload.email,
name: payload.name
};
}
};
return {
saveToken: saveToken, //Expose methods to application
getToken: getToken,
register: register,
login: login,
logout: logout,
isLoggedIn: isLoggedIn,
currentUser: currentUser
};
});
I am trying to use the React Router Async API to achieve some code splitting.
I have Currently a main route file and a subroute:
// routes/index.js
export const createRoutes = (store) => ({
path: '/',
component: AppView,
indexRoute: {
onEnter: (nextState, transition) => {
transition('/login')
},
},
childRoutes: [
LoginRoute(store),
]
})
And then my Login Route looks like this:
//routes/Login/index.js
export default (store) => ({
path: 'login',
/* Async getComponent is only invoked when route matches */
getComponent (nextState, cb) {
/* Webpack - use 'require.ensure' to create a split point
and embed an async module loader (jsonp) when bundling */
require.ensure([], (require) => {
/* Webpack - use require callback to define
dependencies for bundling */
const requireUnauthentication = require('containers/UnauthenticatedComponent').default;
const LoginModalContainer = require('components/Login/LoginModalContainer').default;
/* Return getComponent */
cb(null, requireUnauthentication(LoginModalContainer))
/* Webpack named bundle */
}, 'login')
},
indexRoute: {
getComponent(nextState, cb){
require.ensure([], (require) => {
const LoginStart = require('components/Login/LoginStart').default;
cb(null, LoginStart);
}, 'login')
}
},
getChildRoutes: (location, cb) => {
require.ensure([], (require) => {
const routes = [
{ path: 'login-start', component: require('components/Login/LoginStart').default },
{ path: 'login-prompt', component: require('containers/LoginContainer').default },
{ path: 'phone-number', component: require('components/Register/PhonenumberSet').default }
];
cb(null, routes);
}, 'login');
}
})
The problem is when directly navigating to /login I am getting errors:
DOMLazyTree.js:62 Uncaught TypeError: Cannot read property 'replaceChild' of null
ReactDOMComponentTree.js:105 Uncaught TypeError: Cannot read property '__reactInternalInstance$nva6m7qemb9ackp2ti2ro1or' of null
I think this is related to the asynchronous route configuration, since as soon as I change something and hot reloading kicks in, everything loads fine.
I'm trying to authenticate the user before the view, in this case dashboard, gets rendered.
If the user is logged in, then your good to go, but if not, redirect to login state.
This is my controller:
import angular from 'angular';
import angularMeteor from 'angular-meteor';
import uiRouter from 'angular-ui-router';
import angularMeteorAuth from 'angular-meteor-auth';
import { Meteor } from 'meteor/meteor';
import { Accounts } from 'meteor/accounts-base';
import { name as navBar } from '../navBar/navBar';
import './dashboard.html';
class dashboardCtrl {
constructor($scope) {
'ngInject';
if (Meteor.user()) {
console.log('logged in ', Meteor.user());
} else {
console.log('not logged in or error');
}
}
}
const name = 'dashboard';
export default angular.module(name, [
angularMeteor,
uiRouter,
navBar,
angularMeteorAuth
])
.component(name, {
templateUrl: `imports/ui/components/${name}/${name}.html`,
controller: dashboardCtrl,
})
.config(function($stateProvider, $urlRouterProvider) {
'ngInject';
$stateProvider
.state('dashboard', {
url: '/dashboard',
template: '<dashboard></dashboard>',
resolve: {
user: function($auth, $state){
return $auth.requireUser().then(function(){
return true;
}, function(err){
$state.go('login');
});
}
}
})
})
This works fine if the user is not logged in, it will redirect to login normally, but when the user is indeed logged in and you try to refresh in dashboard it returns a blank screen/page with no console logs or errors or anything.
How can I solve this?
Thanks!