Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <div class="container-fluid" ng-controller="AuthCtrl as auth">
- <input type="text" ng-model="auth.user.username">
- <input type="text" ng-model="auth.user.password">
- <button ng-click="auth.login(auth.user)">LOGIN</button>
- <button ng-click="auth.profile()">PROFILE</button>
- </div>
- const authenticate = expressJwt({
- secret: SECRET
- });
- app.get('/me', authenticate, function(req, res) {
- res.status(200).json(req.user);
- });
- function loginService($http) {
- this.login = function(user) {
- return $http.post('/auth', user).then(
- function(response) {
- return response.data;
- },
- function(response) {
- return response;
- });
- };
- this.profile = function() {
- return $http.get('/me').then(
- function(response) {
- return response.data;
- },
- function(response) {
- return response;
- });
- };
- }
- angular
- .module('app')
- .service('loginService', loginService);
- function AuthCtrl($window, $http, loginService) {
- this.user = {username: "", password: ""};
- this.login = function(user) {
- loginService.login(user).then(function(data) {
- $window.sessionStorage.token = data.token;
- });
- };
- this.profile = function() {
- loginService.profile().then(function(data) {
- console.log(data);
- });
- };
- }
- function config($httpProvider, $windowProvider) {
- var window = $windowProvider.$get();
- if(window.sessionStorage.token) {
- var token = window.sessionStorage.token;
- $httpProvider.defaults.headers.common.Authorization = 'Bearer ' + token;
- }
- };
- angular
- .module('app')
- .config(config)
- .controller('AuthCtrl', AuthCtrl);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement