If you use a route system such as the ui-router, You can do this check in many ways. But before proceeding, I must inform you that 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
proper - although it is also possible.
Ways you can check:
- When accessing the page;
- When changing state;
By declaring a .state
, you must define a name, example:
.state('inicio', {
//configurações aqui
})
This way you can check which state it is in, which state it is going to, whether there are parameters, etc.. To make this interception, you must 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 the .run()
thus prevents any other process from being initiated prior to the checks.
Practical example
Say you own 2 .state()
:
- One with free access ->
.state('inicio')
- One with restricted access ->
.state('usuario')
Inside the run, you do the checks:
- It’s going to state('user')?
- If so, he has permission?
- If not, redirect to start;
What the code would 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 make the validations and prevent it from accessing the page.
Edited as requested in comments.
Your goal is actually to authenticate the user to allow or not to access the page. Still using the ui-router
you can make a statement of data
within the .state()
and, whenever status changes, check if the date requires login and then authenticate. But don’t do this inside the controller. If the user has arrived at the controller, that means that it has probably already loaded the other files, it is not always a good practice.
Example of state with date:
.state('inicio', {
url: 'Inicio',
data: {
requireLogin: false
}
})
.state('usuario', {
url: 'MeusDados',
data: {
requireLogin: true
}
})
And now into the 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.
}
}
});
Screenshot?... do you mean page (url)? Or controller? Or maybe route?
– OnoSendai
Ibotinelly, I need the url, I checked here on the internet, but I have not yet tested if I will succeed or at the end, I will have to test, but I found the following option to test and try to indicate in which controller it should fetch the function depending on the url: - $Location.url() - this function returns me in which location of the system I am, so I think it will be easier to treat the check, I will test here and let you know if it worked
– Tales Born