Advertisement
Guest User

session service ng2

a guest
Feb 18th, 2016
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.43 KB | None | 0 0
  1. import { Router } from "angular2/router";
  2. import { status, json, fetch } from "../utils/fetch";
  3.  
  4. import User from "./user";
  5.  
  6. var instance = null;
  7.  
  8. export default class Session {
  9.  
  10. router: Router;
  11. currentUser: User;
  12.  
  13. constructor(router: Router) {
  14. instance = this;
  15. this.router = router;
  16. }
  17.  
  18. login({ login, password }: { login: string, password: string }) {
  19. console.log(`Logging as ${login} with password ${password}`);
  20.  
  21. fetch("user/" + login, {
  22. method: "GET",
  23. headers: {
  24. "Accept": "application/json",
  25. "Content-Type": "application/json",
  26. "Authorization": "Basic " + btoa(login + ":" + password)
  27. }
  28. })
  29. .then(status)
  30. .then(json)
  31. .then(function(response) {
  32.  
  33. console.log("LOGIN OK", response);
  34. this.authenticated = true;
  35. this.currentUser = new User(response);
  36.  
  37. // and then we redirect the user
  38. this.router.navigate(this.getHomeRoute());
  39. }.bind(this))
  40. .catch((error) => {
  41. console.error(error);
  42. });
  43. }
  44.  
  45. logout() {
  46. this.authenticated = false;
  47. this.currentUser = null;
  48. this.router.navigate([ "Login" ]);
  49. }
  50.  
  51. getHomeRoute() {
  52. switch (this.currentUser.roles[ 0 ]) {
  53. case "MOA":
  54. return [ "DashboardMOA" ];
  55. case "EXPL":
  56. return [ "DashboardExploitant" ];
  57. default:
  58. return [ "Hello" ];
  59. }
  60. }
  61.  
  62. }
  63.  
  64. Session.hasRole = function(role: string) {
  65. return instance && instance.currentUser && instance.currentUser.hasRole(role);
  66. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement