authn.service.ts 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. /*
  2. * Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import { HttpClient } from '@angular/common/http';
  17. import { Injectable, Inject } from '@angular/core';
  18. import { Router } from '@angular/router';
  19. import { StartupService } from '@core';
  20. import { ACLService } from '@delon/acl';
  21. import { DA_SERVICE_TOKEN, ITokenService } from '@delon/auth';
  22. import { SettingsService, _HttpClient, User } from '@delon/theme';
  23. import * as CryptoJS from 'crypto-js';
  24. import { CookieService } from 'ngx-cookie-service';
  25. import { CONSTS } from '../shared/consts';
  26. import { hostname } from 'os';
  27. @Injectable({
  28. providedIn: 'root'
  29. })
  30. export class AuthnService {
  31. redirect_uri: string = '';
  32. constructor(
  33. private router: Router,
  34. private settingsService: SettingsService,
  35. private cookieService: CookieService,
  36. private startupService: StartupService,
  37. private client: HttpClient,
  38. @Inject(DA_SERVICE_TOKEN) private tokenService: ITokenService,
  39. private http: _HttpClient
  40. ) {}
  41. setRedirectUri(redirect_uri: string) {
  42. this.redirect_uri = CryptoJS.enc.Base64url.parse(redirect_uri).toString(CryptoJS.enc.Utf8);
  43. console.log(`redirect_uri ${this.redirect_uri}`);
  44. localStorage.setItem(CONSTS.REDIRECT_URI, this.redirect_uri);
  45. }
  46. get(authParam: any) {
  47. return this.http.get('/login/get?_allow_anonymous=true', authParam);
  48. }
  49. produceOtp(authParam: any) {
  50. return this.http.get(`/login/sendotp/${authParam.mobile}?_allow_anonymous=true`, authParam);
  51. }
  52. login(authParam: any) {
  53. return this.http.post('/login/signin?_allow_anonymous=true', authParam);
  54. }
  55. bindSocialsUser(authParam: any) {
  56. return this.http.post('/login/signin/bindusersocials?_allow_anonymous=true', authParam);
  57. }
  58. //退出
  59. logout() {
  60. this.cookieService.delete(CONSTS.CONGRESS, '/');
  61. this.cookieService.delete(CONSTS.ONLINE_TICKET, '/', this.getSubHostName());
  62. return this.http.get('/logout');
  63. }
  64. congress(authParam: any) {
  65. return this.http.post('/login/congress?_allow_anonymous=true', authParam);
  66. }
  67. getSubHostName(): string {
  68. let hostnames = window.location.hostname.split('.');
  69. let subHostName = window.location.hostname;
  70. if (hostnames.length >= 2 && !CONSTS.IP_V4_REGEXEXP.test(subHostName)) {
  71. subHostName = `${hostnames[hostnames.length - 2]}.${hostnames[hostnames.length - 1]}`;
  72. }
  73. return subHostName;
  74. }
  75. clear() {
  76. this.tokenService.clear();
  77. localStorage.setItem(CONSTS.REMEMBER, '');
  78. }
  79. clearUser() {
  80. let user: User = {};
  81. this.settingsService.setUser(user);
  82. }
  83. auth(authJwt: any) {
  84. let user: User = {
  85. name: `${authJwt.displayName}(${authJwt.username})`,
  86. displayName: authJwt.displayName,
  87. username: authJwt.username,
  88. userId: authJwt.id,
  89. avatar: './assets/img/avatar.svg',
  90. email: authJwt.email,
  91. passwordSetType: authJwt.passwordSetType
  92. };
  93. this.cookieService.set(CONSTS.CONGRESS, authJwt.token, { path: '/' });
  94. this.cookieService.set(CONSTS.ONLINE_TICKET, authJwt.ticket, { domain: this.getSubHostName(), path: '/' });
  95. if (authJwt.remeberMe) {
  96. localStorage.setItem(CONSTS.REMEMBER, authJwt.remeberMe);
  97. }
  98. this.settingsService.setUser(user);
  99. this.tokenService.set(authJwt);
  100. this.tokenService.get()?.expired;
  101. }
  102. jwtAuth(authParam: any) {
  103. return this.http.get(`/login/jwt/trust?_allow_anonymous=true`, authParam);
  104. }
  105. setInst(inst: any, custom: boolean) {
  106. localStorage.setItem(
  107. CONSTS.INST,
  108. JSON.stringify({ custom: custom, id: inst.id, name: inst.name, title: inst.frontTitle, logo: inst.logo })
  109. );
  110. }
  111. getInst() {
  112. let strInst = `${localStorage.getItem(CONSTS.INST)}`;
  113. if (strInst == null || strInst === '') {
  114. return null;
  115. } else {
  116. return JSON.parse(strInst);
  117. }
  118. }
  119. initInst() {
  120. return this.http.get(`/inst/get?_allow_anonymous=true`);
  121. }
  122. setRoles(aclService: ACLService | null): string[] {
  123. let authorities: string[] = JSON.parse(localStorage.getItem(CONSTS.TOKEN) || '')?.authorities || [];
  124. if (aclService) {
  125. aclService.setRole(authorities);
  126. }
  127. return authorities;
  128. }
  129. hasRole(role: string): boolean {
  130. if (role) {
  131. let authorities: string[] = JSON.parse(localStorage.getItem(CONSTS.TOKEN) || '')?.authorities || [];
  132. for (let i = 0; i < authorities.length; i++) {
  133. if (role == authorities[i]) {
  134. return true;
  135. }
  136. }
  137. }
  138. return false;
  139. }
  140. navigate(authJwt: any) {
  141. // 重新获取 StartupService 内容,我们始终认为应用信息一般都会受当前用户授权范围而影响
  142. this.startupService.load().subscribe(() => {
  143. let url = this.tokenService.referrer!.url || '/';
  144. if (url.includes('/passport')) {
  145. url = '/';
  146. }
  147. if (localStorage.getItem(CONSTS.REDIRECT_URI) != null) {
  148. this.redirect_uri = `${localStorage.getItem(CONSTS.REDIRECT_URI)}`;
  149. localStorage.removeItem(CONSTS.REDIRECT_URI);
  150. }
  151. if (this.redirect_uri != '') {
  152. console.log(`redirect_uri ${this.redirect_uri}`);
  153. location.href = this.redirect_uri;
  154. }
  155. this.router.navigateByUrl(url);
  156. });
  157. }
  158. }