Advertisement
Guest User

Untitled

a guest
Jul 6th, 2016
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.77 KB | None | 0 0
  1. <div class="container-fluid" ng-controller="AuthCtrl as auth">
  2. <input type="text" ng-model="auth.user.username">
  3. <input type="text" ng-model="auth.user.password">
  4. <button ng-click="auth.login(auth.user)">LOGIN</button>
  5. <button ng-click="auth.profile()">PROFILE</button>
  6. </div>
  7.  
  8. const authenticate = expressJwt({
  9. secret: SECRET
  10. });
  11. app.get('/me', authenticate, function(req, res) {
  12. res.status(200).json(req.user);
  13. });
  14.  
  15. function loginService($http) {
  16. this.login = function(user) {
  17. return $http.post('/auth', user).then(
  18. function(response) {
  19. return response.data;
  20. },
  21. function(response) {
  22. return response;
  23. });
  24. };
  25. this.profile = function() {
  26. return $http.get('/me').then(
  27. function(response) {
  28. return response.data;
  29. },
  30. function(response) {
  31. return response;
  32. });
  33. };
  34. }
  35.  
  36. angular
  37. .module('app')
  38. .service('loginService', loginService);
  39.  
  40. function AuthCtrl($window, $http, loginService) {
  41. this.user = {username: "", password: ""};
  42. this.login = function(user) {
  43. loginService.login(user).then(function(data) {
  44. $window.sessionStorage.token = data.token;
  45. });
  46. };
  47. this.profile = function() {
  48. loginService.profile().then(function(data) {
  49. console.log(data);
  50. });
  51. };
  52. }
  53.  
  54. function config($httpProvider, $windowProvider) {
  55. var window = $windowProvider.$get();
  56. if(window.sessionStorage.token) {
  57. var token = window.sessionStorage.token;
  58. $httpProvider.defaults.headers.common.Authorization = 'Bearer ' + token;
  59. }
  60. };
  61.  
  62. angular
  63. .module('app')
  64. .config(config)
  65. .controller('AuthCtrl', AuthCtrl);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement