Broker System for Supercredit
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

211 行
6.2KB

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