Skip to content

Instantly share code, notes, and snippets.

@andref
Last active September 30, 2016 00:17
Show Gist options
  • Select an option

  • Save andref/8caf337ac4b020dad936250a6e1f6303 to your computer and use it in GitHub Desktop.

Select an option

Save andref/8caf337ac4b020dad936250a6e1f6303 to your computer and use it in GitHub Desktop.
Login e Logout usando Angular 1 + UI Router 1
* {
box-sizing: border-box;
}
:focus {
outline-color: #55bada;
}
body {
color: #333;
line-height: 1.5;
margin: 0;
padding: 1em;
font-family: sans-serif;
}
h1 {
font-size: 2rem;
line-height: 2rem;
margin: 1rem 0;
}
label {
font-weight: bold;
}
label,
input,
button {
font-size: 1rem;
line-height: 1.5rem;
}
input {
border: 1px solid #ccc;
padding: calc(0.5rem - 1px);
}
button {
background-color: #55bada;
color: #fff;
border: none;
padding: 0.5rem;
cursor: pointer;
}
button:active {
background-color: #3b8298;
}
#formLogin {
position: relative;
}
#formLogin label,
#formLogin input,
#formLogin button {
display: block;
width: 100%;
}
#formLogin input {
margin-bottom: 1rem;
}
#erro {
padding: 1rem;
margin: 1rem 0;
background-color: #ffa;
color: #a98;
}
#barraNavegacao {
min-height: 2.5rem;
background-color: #eee;
}
#barraNavegacao > nav {
padding: 0.5rem;
margin-bottom: 1rem;
display: flex;
}
#barraNavegacao > nav > a {
text-decoration: none;
color: #55bada;
min-width: 4rem;
text-align: center;
display: block;
}
#barraNavegacao > nav > a.ativo {
font-weight: bold;
background-color: #55bada;
color: white;
}
#btnSair {
position: absolute;
top: 1rem;
right: 1rem;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no">
<title>Angular — New UI Router</title>
<link rel="stylesheet" type="text/css" href="index.css">
</head>
<body ng-app="app">
<div id="barraNavegacao" ui-view="barraNavegacao">
</div>
<div id="conteudo" ui-view="conteudo">
</div>
<script src="http://npmcdn.com/[email protected]/angular.js"></script>
<script src="http://npmcdn.com/[email protected]/release/angular-ui-router.js"></script>
<script>
"use strict";
angular
.module('app', ['ui.router'])
.config(configurarRotas)
.config(controleDeAcesso)
.factory('LoginService', LoginServiceFactory)
function LoginServiceFactory ($q, $timeout) {
var usuario = null;
var emCache = false;
function refrescarCache() {
emCache = true;
$timeout(() => emCache = false, 10000);
}
return {
login: function (login, senha) {
return $q(function (resolve, reject) {
$timeout(function () {
if (login === 'andre' && senha === 'tiao') {
usuario = {
nome: 'André Fillipe',
admin: true
};
refrescarCache();
resolve(usuario);
} else {
reject(new Error('Credenciais incorretas'));
}
}, 1000);
});
},
usuario: function () {
return $q(function (resolve, reject) {
if (usuario && emCache) {
resolve(usuario);
return;
}
$timeout(function () {
if (usuario) {
refrescarCache();
resolve(usuario);
} else {
reject(new Error('Usuário não autenticado'));
}
}, 1000);
});
},
logout: function () {
return $q(function (resolve, reject) {
$timeout(function () {
if (usuario) {
usuario = null;
resolve();
} else {
reject(new Error('Usuário não autenticado'));
}
}, 1000);
});
}
}
}
function LoginController (LoginService, $state) {
this.login = 'andre';
this.senha = 'tiao';
this.entrar = function () {
this.erro = null;
LoginService
.login(this.login, this.senha)
.then(usuario => $state.go('loginContinuar'))
.catch(erro => this.erro = erro);
}
}
function HomeController (LoginService) {
LoginService.usuario()
.then(u => this.usuario = u)
.catch(() => this.usuario = null);
}
function BarraNavegacaoController (LoginService, $state, $log) {
LoginService
.usuario()
.then(u => this.usuario = u)
.catch(() => this.usuario = null);
this.sair = function () {
LoginService
.logout()
.catch(erro => $log.warn('Falhou logout: %s', erro.message))
.finally(() => $state.go('default'));
}
}
function controleDeAcesso($stateProvider, $transitionsProvider) {
console.info('Configurando controle de acesso');
var pendente = null;
$transitionsProvider.onBefore({}, function (transition) {
const LoginService = transition.injector().get('LoginService');
const target = transition.targetState().$state();
if (target.name === 'loginContinuar') {
if (pendente) {
console.log('✔︎ Seguindo para “%s” após login', pendente.name());
var p = pendente;
pendente = null;
return p;
} else {
console.log('✔︎ Seguindo para “home” após login');
transition.router.stateService.target('home');
}
}
if (!target.data || !target.data.autenticar) {
return true;
}
return LoginService
.usuario()
.then(usuario => {
pendente = null;
return true;
})
.catch(erro => {
pendente = transition.targetState();
console.log('✘ Acesso a “%s” impedido: %s', target.name, erro.message);
return transition.router.stateService.target('login');
});
});
}
function configurarRotas ($stateProvider, $urlRouterProvider) {
console.info('Configurando rotas');
$urlRouterProvider
.otherwise('/');
const barraNavegacao = {
controller: BarraNavegacaoController,
controllerAs: "$ctrl",
templateUrl: "barraNavegacao.html",
};
$stateProvider
.state({
name: 'home',
url: '/home',
views: {
conteudo: {
controller: HomeController,
controllerAs: '$ctrl',
templateUrl: 'home.html',
},
barraNavegacao: barraNavegacao
},
data: {
autenticar: true
}
})
.state({
name: 'sobre',
url: '/sobre',
views: {
conteudo: {
templateUrl: 'sobre.html',
},
barraNavegacao: barraNavegacao
},
data: {
autenticar: true
}
})
.state({
name: 'login',
views: {
conteudo: {
controller: LoginController,
controllerAs: '$ctrl',
templateUrl: 'login.html'
},
barraNavegacao: barraNavegacao
}
})
.state({
name: 'loginContinuar',
})
.state({
name: 'default',
url: '/',
views: {
conteudo: {
templateUrl: 'default.html'
},
barraNavegacao: barraNavegacao
}
});
}
</script>
<script type="text/ng-template" id="home.html">
<h1>Home</h1>
<p>Você entrou como {{ $ctrl.usuario.nome }}.</p>
</script>
<script type="text/ng-template" id="sobre.html">
<h1>Sobre</h1>
<p>
Este é um exemplo de autenticação usando Angular UI Router 1.0.
</p>
</script>
<script type="text/ng-template" id="login.html">
<h1>Identifique-se</h1>
<div id="erro" ng-if="$ctrl.erro">{{ $ctrl.erro.message }}</div>
<form id="formLogin" name="formLogin" ng-submit="$ctrl.entrar()">
<label for="login">Login</label>
<input type="text" name="login" id="login" ng-model="$ctrl.login" required autofocus>
<label for="senha">Senha</label>
<input type="password" name="senha" id="senha" ng-model="$ctrl.senha" required>
<button type="Submit">
Acessar
</button>
</form>
</script>
<script type="text/ng-template" id="default.html">
<h1>Bem vindo</h1>
<p>
Esta é uma demonstração do Angular UI Router 1.0. Para começar,
clique em algum item da barra de navegação.
</p>
</script>
<script type="text/ng-template" id="barraNavegacao.html">
<nav>
<a ui-sref-active="ativo" ui-sref="default">Início</a>
<a ui-sref-active="ativo" ui-sref="home">Home</a>
<a ui-sref-active="ativo" ui-sref="sobre">Sobre</a>
<button id="btnSair" ng-click="$ctrl.sair()" ng-if="$ctrl.usuario">Sair</button>
</nav>
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment