Broker System for Supercredit
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

194 satır
5.7KB

  1. import {EventEmitter, Injectable, OnInit} from '@angular/core';
  2. import {AppConfig} from '../app.config';
  3. import {ApiV1LoginResponse} from '../models/api-v1-login-response';
  4. import {PeopleModel} from '../models/people.model';
  5. import {HttpClient} from '@angular/common/http';
  6. import {Router} from '@angular/router';
  7. import {NotificationService} from '@progress/kendo-angular-notification';
  8. import {debounce} from 'ts-debounce';
  9. import {UserExtraModel} from '../models/user-extra.model';
  10. import {WebSocketService} from '../websocket';
  11. @Injectable()
  12. export class SessionService {
  13. public loggedIn = new ApiV1LoginResponse({});
  14. loginResult = new EventEmitter <ApiV1LoginResponse>();
  15. logoutEvent = new EventEmitter <ApiV1LoginResponse>();
  16. private machineId = localStorage.getItem('mid') || '';
  17. debouncedLocalStorageMonitor = debounce( this.localStorageChange, 1000); // to avoid to frequent local storage changes
  18. constructor(private config: AppConfig, private http: HttpClient,
  19. private router: Router, private ns: NotificationService,
  20. private ws: WebSocketService){
  21. //
  22. const self = this;
  23. this.AutoLogin();
  24. window.addEventListener('storage', event => {
  25. if (event.storageArea === localStorage && event.key === this.config.storageKey) {
  26. // It's local storage
  27. self.debouncedLocalStorageMonitor(event).then( r => {});
  28. }
  29. }, false);
  30. }
  31. private AutoLogin(): void {
  32. const sfm: ApiV1LoginResponse = JSON.parse(localStorage.getItem(this.config.storageKey));
  33. if (!sfm) {
  34. return;
  35. }
  36. this.login(sfm);
  37. }
  38. public login( resp: ApiV1LoginResponse): void{
  39. this.loggedIn = new ApiV1LoginResponse(resp);
  40. if ( this.MachineId !== '' && resp.machineId !== '' && this.MachineId !== resp.machineId ) {
  41. this.MachineId = resp.machineId; // update machine id
  42. }
  43. if (this.loggedIn.session !== ''){
  44. this.ws.SessionId = this.loggedIn.session;
  45. }
  46. if ( resp.UserExtra !== undefined ) {
  47. this.loggedIn.UserExtra = new UserExtraModel(resp.UserExtra);
  48. }
  49. this.loginResult.emit(this.loggedIn);
  50. }
  51. private localStorageChange(event: StorageEvent): void {
  52. console.log('local storage change', event);
  53. const sfm: ApiV1LoginResponse = JSON.parse(localStorage.getItem(this.config.storageKey));
  54. if ( sfm && sfm.session && sfm.User && sfm.User.Id && this.loggedIn.User.Id) {
  55. if ( sfm.session === this.loggedIn.session && sfm.User.Id !== this.loggedIn.User.Id){
  56. this.logoutWithoutPersistingStorage(); // silently logout without touching any storage
  57. }
  58. }
  59. }
  60. public saveSessionInfo(): void {
  61. localStorage.setItem(this.config.storageKey, JSON.stringify(this.loggedIn));
  62. }
  63. public isAdmin(): boolean {
  64. return this.loggedIn.role === 'admin';
  65. }
  66. public isBroker(): boolean {
  67. return this.loggedIn.role === 'broker';
  68. }
  69. public isUser(): boolean {
  70. return this.loggedIn.login === true;
  71. }
  72. public get CurrentUser(): PeopleModel {
  73. if (this.isLoggedIn() ) {
  74. return this.loggedIn.User;
  75. }else{
  76. return new PeopleModel({});
  77. }
  78. }
  79. public isCurrentUser(id: string): boolean {
  80. return id !== '' && this.loggedIn.login === true && this.loggedIn.User !== undefined && this.loggedIn.User.Id === id;
  81. }
  82. public UpdatePeopleInfo(people: PeopleModel): void{
  83. this.loggedIn.User.Display = people.Display;
  84. this.loggedIn.User.First = people.First;
  85. this.loggedIn.User.Last = people.Last;
  86. this.saveSessionInfo();
  87. }
  88. logout(): void {
  89. if ( ! this.isLoggedIn() ){
  90. return;
  91. }
  92. this.http.post(`${this.config.apiUrl}logout`, '').subscribe(
  93. resp => {
  94. this.ToastMessage();
  95. },
  96. event => {
  97. this.ToastMessage('logout from server (with warnings)');
  98. this.reLogin();
  99. }, () => {
  100. this.reLogin();
  101. }
  102. );
  103. }
  104. public isLoggedIn(): boolean{
  105. if ( this.loggedIn.login !== undefined &&
  106. this.loggedIn.login &&
  107. this.machineId !== '' &&
  108. this.loggedIn.session !== '' ) {
  109. return true;
  110. }
  111. return false;
  112. }
  113. private reLogin(): void {
  114. this.loggedIn = new ApiV1LoginResponse({});
  115. localStorage.removeItem(this.config.storageKey);
  116. this.router.navigate(['/login']).then( () => {
  117. this.logoutEvent.emit(this.loggedIn);
  118. });
  119. }
  120. logoutWithoutPersistingStorage(): void {
  121. if ( !this.isLoggedIn() ){
  122. return;
  123. }
  124. console.log('logout without storate');
  125. this.loggedIn = new ApiV1LoginResponse({});
  126. this.logoutEvent.emit(this.loggedIn);
  127. this.router.navigate(['/login']).then(r => {
  128. this.ToastMessage();
  129. } );
  130. }
  131. logoutAndClearLocalStorage(): void {
  132. if ( !this.isLoggedIn() ){
  133. return;
  134. }
  135. console.log('logout ++++++++++++++ storate');
  136. localStorage.removeItem(this.config.storageKey);
  137. this.loggedIn = new ApiV1LoginResponse({});
  138. this.logoutEvent.emit(this.loggedIn);
  139. this.router.navigate(['/login']).then(r => {
  140. this.ToastMessage();
  141. } );
  142. }
  143. public ToastMessage(msg: string = 'Successfully logged out'): void {
  144. this.ns.show({
  145. content: msg,
  146. cssClass: 'button-notification',
  147. animation: { type: 'slide', duration: 400 },
  148. position: { horizontal: 'right', vertical: 'top' },
  149. type: { style: 'info', icon: true },
  150. hideAfter : 2000
  151. });
  152. }
  153. public get MachineId(): string {
  154. return this.machineId || '';
  155. }
  156. public set MachineId(mid) {
  157. if ( this.machineId === '' || this.machineId !== mid ){
  158. this.machineId = mid;
  159. localStorage.setItem('mid', mid);
  160. }
  161. }
  162. public get SessionId(): string{
  163. return this.loggedIn.session || '';
  164. }
  165. }