If you use a route system, such as ui-router , you can do this check for several modes. But before proceeding, I must inform you what you will be doing, if you choose this alternative, is to check the status ( .state
) that the user is trying to access and not the URL
itself - although it is also possible. / p>
Modes you can check:
- Accessing the page;
- When changing state;
When declaring a .state
, you must define a name, for example:
.state('inicio', {
//configurações aqui
})
This way you can check what state it is, what state it is going to, if there are any parameters, etc. To do this interception, you should use the following function:
$rootScope.$on('$stateChangeStart', function(event, toState, toParam, fromState, fromParam) {
//Intercepta a mudança antes que ela ocorra
});
$rootScope.$on('$stateChangeSuccess', function(event, toState, toParam, fromState, fromParam) {
//Intercepta uma mudança com successo
});
$rootScope.$on('$stateChangeError', function(event, toState, toParam, fromState, fromParam) {
//Intercepta uma mudança com erro
});
Preferably, this code is best used within .run()
, thus preventing any other process from being started before the checks.
Practical example
Let's say you have 2 .state()
:
- One with liberated access - >
.state('inicio')
- One with restricted access - >
.state('usuario')
Inside the run, you do the checks:
- Is it going to state ('user')?
- If yes, does he have permission?
- If you do not, redirect to the start;
How would the code look like:
$rootScope.$on('$stateChangeStart', function(event, toState, toParam, fromState, fromParam) {
/*
Precisa ser no $stateChangeStart para evitar que o state seja carregado
antes de verificar se ele possui permissão
*/
if(toState == 'usuario') { //Identifica se ele está acessando o 'usuario'
/*
Sua função de autenticação vai aqui
Exemplo:
val = 1; -> usuario autenticado;
val = 2; -> usuario não autenticado;
*/
if(val == 2) {
//Usuario não está autenticado
event.preventDefault(); //Evita que o state continue o serviço
return $state.go('inicio'); //Redireciona para o inicio
}
}
});
This way you can do the validations and prevent them from accessing the page.
Edited as requested in comments.
Your goal is actually to authenticate the user to allow access to the page or not. Still using ui-router
you can make a statement of data
within .state()
and, whenever there is a state change, check if the date requires login and then do the authentication. But do not do it inside the controller. If the user has reached the controller, it probably has already loaded the other files, it is not always a good practice.
State with data example:
.state('inicio', {
url: 'Inicio',
data: {
requireLogin: false
}
})
.state('usuario', {
url: 'MeusDados',
data: {
requireLogin: true
}
})
And now inside run ():
$rootScope.$on('$stateChangeStart', function(event, toState, toParam, fromState, fromParam) {
if(toState.data.requireLogin) {
function validarAutenticacao() {
//...
};
/*
Sua validação de autenticação
Ela pode ser a mesma para todos os .state()
que possuirem requireLogin: true;
Não precisa mais usar dentro do controller
*/
if (validaAutenticacao == false) { //Se a autenticação for falsa
event.preventDefault(); //Impede que a página inicie o carregamento
//Redirecione o usuario ou faça outra manipulação aqui - como exibir um alerta ou redirecionar para a página anterior.
}
}
});