Guest User

Untitled

a guest
Nov 21st, 2017
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.64 KB | None | 0 0
  1. @Injectable()
  2. export class AuthGuard implements CanActivate {
  3.  
  4. constructor(
  5. private router: Router,
  6. @Inject(PLATFORM_ID) private platformId: Object,
  7. private authService: AuthenticationService
  8. ) { }
  9.  
  10. canActivate() {
  11. if (isPlatformBrowser(this.platformId)) {
  12. if(this.authService.auth2) {
  13. if (this.authService.loggedIn()) {
  14. return true;
  15. } else {
  16. this.router.navigate(['/login']);
  17. return false;
  18. }
  19. }
  20. }
  21. }
  22. }
  23.  
  24. @Injectable()
  25. export class AuthenticationService {
  26. token = new Subject<String>();
  27. auth2;
  28. auth2access;
  29.  
  30.  
  31. constructor(
  32. private router: Router,
  33. @Inject(PLATFORM_ID) private platformId: Object
  34. ) {
  35. if (isPlatformBrowser(this.platformId)) {
  36. try {
  37. this.token.next(sessionStorage.getItem('token'));
  38. gapi.load('auth2', () => {
  39. this.auth2 = gapi.auth2.init({
  40. client_id: '*.apps.googleusercontent.com'
  41. }).then( () =>
  42. {
  43. //var googleAuthTest = gapi.auth2.getAuthInstance();
  44. console.log(gapi.auth2.getAuthInstance().isSignedIn.get());
  45. if(gapi.auth2.getAuthInstance().isSignedIn.get() == false) {
  46. this.revoke();
  47. }else{
  48. this.auth2access = gapi.auth2.getAuthInstance();
  49. }
  50. });
  51. });
  52. } catch (ex) { }
  53. }
  54. }
  55.  
  56. public backendAuth(id_token ,action) {
  57. var result = new BehaviorSubject<string>('');
  58. var xhr = new XMLHttpRequest();
  59. xhr.open('POST', 'https://callum.tech/auth/verify.php');
  60. xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  61. xhr.onload = function() {
  62. result.next(xhr.responseText);
  63. };
  64. xhr.send('id_token=' + id_token + "&action=" + action);
  65. return result.map(x => x);
  66. }
  67.  
  68. public loggedIn(): boolean {
  69. if (isPlatformBrowser(this.platformId)) {
  70. if(this.auth2) {
  71. return gapi.auth2.getAuthInstance().isSignedIn.get();
  72. }
  73. }
  74. /*if (isPlatformBrowser(this.platformId)) {
  75. if(this.auth2) {
  76. return gapi.auth2.getAuthInstance().isSignedIn.get();
  77. }
  78. }*/
  79. }
  80.  
  81. public revoke() {
  82. if (isPlatformBrowser(this.platformId)) {
  83. gapi.auth2.getAuthInstance().signOut();
  84. }
  85. }
  86. }
Add Comment
Please, Sign In to add comment