@dflat-core/web 1.0.47 → 1.0.49

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -8,7 +8,7 @@ import * as i0 from "@angular/core";
8
8
  import { EventEmitter, Inject, Injectable, InjectionToken, NgModule, Optional, SkipSelf } from "@angular/core";
9
9
  import jwt_decode from "jwt-decode";
10
10
  import { BehaviorSubject, ReplaySubject, Subject, empty, throwError, timer } from "rxjs";
11
- import { catchError, filter, finalize, map } from "rxjs/operators";
11
+ import { catchError, filter, finalize, map, shareReplay } from "rxjs/operators";
12
12
  import * as i4 from "@angular/router";
13
13
  import * as i1 from "@angular/platform-browser";
14
14
  import * as signalR from "@microsoft/signalr";
@@ -120,6 +120,12 @@ var ServerUrl = class ServerUrl {
120
120
  static {
121
121
  this.connectPath = "/Account/Connect";
122
122
  }
123
+ static {
124
+ this.connectExternalPath = "/Account/ConnectExternal";
125
+ }
126
+ static {
127
+ this.loginProvidersPath = "/Account/GetLoginProviders";
128
+ }
123
129
  static {
124
130
  this.registerPath = "/Account/Register";
125
131
  }
@@ -702,6 +708,27 @@ var AuthService = class AuthService {
702
708
  }
703
709
  }));
704
710
  }
711
+ getLoginProviders() {
712
+ return this.httpClient.get(this.baseUrl + ServerUrl.loginProvidersPath, { headers: this.headersService.jsonHeaders() });
713
+ }
714
+ loginExternal(provider, idToken, rememberMe, firstName, lastName) {
715
+ let body = JSON.stringify({
716
+ "Provider": provider,
717
+ "IdToken": idToken,
718
+ "FirstName": firstName,
719
+ "LastName": lastName
720
+ });
721
+ let _url = this.baseUrl + ServerUrl.connectExternalPath;
722
+ return this.httpClient.post(_url, body, { headers: this.headersService.authJsonHeaders() }).pipe(map((resp) => {
723
+ let user = resp;
724
+ if (user && user.AccessToken) {
725
+ this.saveUserInfos(user, JSON.stringify(user), rememberMe);
726
+ this.busMsg.publish(new UserUpdatedMessage(user.AccessToken));
727
+ this.scheduleRefreshToken(true, true);
728
+ return user;
729
+ }
730
+ }));
731
+ }
705
732
  register(captchaToken, firstName, lastName, email, password, rememberMe) {
706
733
  let body = JSON.stringify({
707
734
  "CaptchaToken": captchaToken,
@@ -859,7 +886,7 @@ var AuthService = class AuthService {
859
886
  updateToken() {
860
887
  console.log(`Entering updateToken()`);
861
888
  const headers = new HttpHeaders({ "Content-Type": "application/json" });
862
- const model = { refreshToken: this.refreshToken };
889
+ const model = JSON.stringify(this.refreshToken);
863
890
  return this.httpClient.post(`${this.baseUrl}${ServerUrl.refreshPath}`, model, { headers }).pipe(map((response) => response || {}), catchError((error) => throwError(() => new Error(error.error)))).subscribe((resp) => {
864
891
  let user = resp;
865
892
  if (user && user.AccessToken) {
@@ -1037,6 +1064,174 @@ i0.ɵɵngDeclareClassMetadata({
1037
1064
  { type: i4.Router }
1038
1065
  ]
1039
1066
  });
1067
+ var ExternalLoginService = class ExternalLoginService {
1068
+ static {
1069
+ this.google = "Google";
1070
+ }
1071
+ static {
1072
+ this.microsoft = "Microsoft";
1073
+ }
1074
+ static {
1075
+ this.apple = "Apple";
1076
+ }
1077
+ static {
1078
+ this.googleScript = "https://accounts.google.com/gsi/client";
1079
+ }
1080
+ static {
1081
+ this.appleScript = "https://appleid.cdn-apple.com/appleauth/static/jsapi/appleid/1/fr_FR/appleid.auth.js";
1082
+ }
1083
+ constructor(zone) {
1084
+ this.zone = zone;
1085
+ this.scripts = {};
1086
+ }
1087
+ renderGoogleButton(container, provider, onToken) {
1088
+ return this.loadScript(ExternalLoginService.googleScript).then(() => {
1089
+ google.accounts.id.initialize({
1090
+ client_id: provider.ClientId,
1091
+ callback: (response) => this.zone.run(() => onToken({
1092
+ provider: ExternalLoginService.google,
1093
+ idToken: response.credential
1094
+ }))
1095
+ });
1096
+ google.accounts.id.renderButton(container, {
1097
+ type: "standard",
1098
+ theme: "outline",
1099
+ size: "large",
1100
+ text: "continue_with",
1101
+ shape: "rectangular",
1102
+ logo_alignment: "center",
1103
+ locale: "fr",
1104
+ width: Math.min(400, Math.max(200, container.offsetWidth || 300))
1105
+ });
1106
+ });
1107
+ }
1108
+ signInWithMicrosoft(provider) {
1109
+ const nonce = this.random();
1110
+ const state = this.random();
1111
+ const url = `https://login.microsoftonline.com/${encodeURIComponent(provider.TenantId || "common")}/oauth2/v2.0/authorize?client_id=${encodeURIComponent(provider.ClientId)}&response_type=id_token&response_mode=fragment&scope=${encodeURIComponent("openid profile email")}&redirect_uri=${encodeURIComponent(this.redirectUri)}&nonce=${nonce}&state=${state}&prompt=select_account`;
1112
+ return this.openPopup(url).then((params) => {
1113
+ if (params.get("error")) throw new Error(params.get("error_description") || params.get("error"));
1114
+ const idToken = params.get("id_token");
1115
+ if (!idToken || params.get("state") !== state || this.readPayload(idToken).nonce !== nonce) throw new Error("Réponse de Microsoft inattendue.");
1116
+ return {
1117
+ provider: ExternalLoginService.microsoft,
1118
+ idToken
1119
+ };
1120
+ });
1121
+ }
1122
+ signInWithApple(provider) {
1123
+ return this.loadScript(ExternalLoginService.appleScript).then(() => {
1124
+ AppleID.auth.init({
1125
+ clientId: provider.ClientId,
1126
+ scope: "name email",
1127
+ redirectURI: this.redirectUri,
1128
+ state: this.random(),
1129
+ usePopup: true
1130
+ });
1131
+ return AppleID.auth.signIn();
1132
+ }).then((response) => {
1133
+ const idToken = response && response.authorization && response.authorization.id_token;
1134
+ if (!idToken) throw new Error("Réponse d'Apple inattendue.");
1135
+ const name = response.user && response.user.name || {};
1136
+ return {
1137
+ provider: ExternalLoginService.apple,
1138
+ idToken,
1139
+ firstName: name.firstName,
1140
+ lastName: name.lastName
1141
+ };
1142
+ });
1143
+ }
1144
+ isCancellation(error) {
1145
+ const code = error && (error.error || error.message);
1146
+ return code === "popup_closed" || code === "popup_closed_by_user" || code === "user_cancelled_authorize";
1147
+ }
1148
+ get redirectUri() {
1149
+ return window.location.origin;
1150
+ }
1151
+ openPopup(url) {
1152
+ const width = 500, height = 650;
1153
+ const left = window.screenX + Math.max(0, (window.outerWidth - width) / 2);
1154
+ const top = window.screenY + Math.max(0, (window.outerHeight - height) / 2);
1155
+ const popup = window.open(url, "dflat-external-login", `width=${width},height=${height},left=${left},top=${top}`);
1156
+ return new Promise((resolve, reject) => {
1157
+ if (!popup) {
1158
+ reject(/* @__PURE__ */ new Error("La fenêtre de connexion a été bloquée par le navigateur."));
1159
+ return;
1160
+ }
1161
+ this.zone.runOutsideAngular(() => {
1162
+ const timer = window.setInterval(() => {
1163
+ if (popup.closed) {
1164
+ window.clearInterval(timer);
1165
+ this.zone.run(() => reject(/* @__PURE__ */ new Error("popup_closed")));
1166
+ return;
1167
+ }
1168
+ let hash = null;
1169
+ try {
1170
+ if (popup.location.origin === window.location.origin) hash = popup.location.hash;
1171
+ } catch {}
1172
+ if (hash && (hash.indexOf("id_token=") >= 0 || hash.indexOf("error=") >= 0)) {
1173
+ window.clearInterval(timer);
1174
+ popup.close();
1175
+ this.zone.run(() => resolve(new URLSearchParams(hash.replace(/^#\/?/, ""))));
1176
+ }
1177
+ }, 200);
1178
+ });
1179
+ });
1180
+ }
1181
+ loadScript(src) {
1182
+ if (!this.scripts[src]) this.scripts[src] = new Promise((resolve, reject) => {
1183
+ const script = document.createElement("script");
1184
+ script.src = src;
1185
+ script.async = true;
1186
+ script.onload = () => resolve();
1187
+ script.onerror = () => {
1188
+ delete this.scripts[src];
1189
+ reject(/* @__PURE__ */ new Error("Le service de connexion est injoignable."));
1190
+ };
1191
+ document.head.appendChild(script);
1192
+ });
1193
+ return this.scripts[src];
1194
+ }
1195
+ random() {
1196
+ const bytes = /* @__PURE__ */ new Uint8Array(16);
1197
+ window.crypto.getRandomValues(bytes);
1198
+ return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
1199
+ }
1200
+ readPayload(token) {
1201
+ try {
1202
+ const part = token.split(".")[1].replace(/-/g, "+").replace(/_/g, "/");
1203
+ return JSON.parse(decodeURIComponent(atob(part).split("").map((c) => "%" + c.charCodeAt(0).toString(16).padStart(2, "0")).join("")));
1204
+ } catch {
1205
+ return {};
1206
+ }
1207
+ }
1208
+ static {
1209
+ this.ɵfac = i0.ɵɵngDeclareFactory({
1210
+ minVersion: "12.0.0",
1211
+ version: "22.2.1",
1212
+ ngImport: i0,
1213
+ type: ExternalLoginService,
1214
+ deps: [{ token: i0.NgZone }],
1215
+ target: i0.ɵɵFactoryTarget.Injectable
1216
+ });
1217
+ }
1218
+ static {
1219
+ this.ɵprov = i0.ɵɵngDeclareInjectable({
1220
+ minVersion: "12.0.0",
1221
+ version: "22.2.1",
1222
+ ngImport: i0,
1223
+ type: ExternalLoginService
1224
+ });
1225
+ }
1226
+ };
1227
+ i0.ɵɵngDeclareClassMetadata({
1228
+ minVersion: "12.0.0",
1229
+ version: "22.2.1",
1230
+ ngImport: i0,
1231
+ type: ExternalLoginService,
1232
+ decorators: [{ type: Injectable }],
1233
+ ctorParameters: () => [{ type: i0.NgZone }]
1234
+ });
1040
1235
  var BreadcrumbService = class BreadcrumbService {
1041
1236
  constructor(title) {
1042
1237
  this.title = title;
@@ -1397,6 +1592,79 @@ i0.ɵɵngDeclareClassMetadata({
1397
1592
  { type: i7.EnvironmentBase }
1398
1593
  ]
1399
1594
  });
1595
+ var InitCacheService = class InitCacheService {
1596
+ static {
1597
+ this.CACHE_STAMP = "cachestamp";
1598
+ }
1599
+ static {
1600
+ this.USER_ACCOUNT_ID = "id";
1601
+ }
1602
+ constructor(busMsg, localStorage) {
1603
+ this.entries = /* @__PURE__ */ new Map();
1604
+ this.stamp = this.readStamp(localStorage.getDataObject(AppKeys.ACCESS_TOKEN));
1605
+ busMsg.of(UserUpdatedMessage).subscribe((message) => this.onTokenChanged(message.userKey));
1606
+ }
1607
+ get(key, factory) {
1608
+ let entry = this.entries.get(key);
1609
+ if (!entry) {
1610
+ entry = factory().pipe(catchError((error) => {
1611
+ if (this.entries.get(key) === entry) this.entries.delete(key);
1612
+ return throwError(() => error);
1613
+ }), shareReplay(1));
1614
+ this.entries.set(key, entry);
1615
+ }
1616
+ return entry.pipe(map((value) => Utilities.deepCopy(value)));
1617
+ }
1618
+ clear(prefix) {
1619
+ if (Utilities.IsNil(prefix)) {
1620
+ this.entries.clear();
1621
+ return;
1622
+ }
1623
+ Array.from(this.entries.keys()).filter((key) => key.startsWith(prefix)).forEach((key) => this.entries.delete(key));
1624
+ }
1625
+ onTokenChanged(token) {
1626
+ const stamp = this.readStamp(token);
1627
+ if (stamp !== this.stamp) {
1628
+ this.stamp = stamp;
1629
+ this.clear();
1630
+ }
1631
+ }
1632
+ readStamp(token) {
1633
+ if (!token) return null;
1634
+ try {
1635
+ const decoded = jwt_decode(token);
1636
+ return `${decoded[InitCacheService.CACHE_STAMP]}|${decoded[InitCacheService.USER_ACCOUNT_ID]}`;
1637
+ } catch {
1638
+ return null;
1639
+ }
1640
+ }
1641
+ static {
1642
+ this.ɵfac = i0.ɵɵngDeclareFactory({
1643
+ minVersion: "12.0.0",
1644
+ version: "22.2.1",
1645
+ ngImport: i0,
1646
+ type: InitCacheService,
1647
+ deps: [{ token: BusMessageService }, { token: LocalStoreManager }],
1648
+ target: i0.ɵɵFactoryTarget.Injectable
1649
+ });
1650
+ }
1651
+ static {
1652
+ this.ɵprov = i0.ɵɵngDeclareInjectable({
1653
+ minVersion: "12.0.0",
1654
+ version: "22.2.1",
1655
+ ngImport: i0,
1656
+ type: InitCacheService
1657
+ });
1658
+ }
1659
+ };
1660
+ i0.ɵɵngDeclareClassMetadata({
1661
+ minVersion: "12.0.0",
1662
+ version: "22.2.1",
1663
+ ngImport: i0,
1664
+ type: InitCacheService,
1665
+ decorators: [{ type: Injectable }],
1666
+ ctorParameters: () => [{ type: BusMessageService }, { type: LocalStoreManager }]
1667
+ });
1400
1668
  var MessagesService = class MessagesService {
1401
1669
  constructor() {
1402
1670
  this.messagesList = [];
@@ -1591,12 +1859,14 @@ var CoreServicesModule = class CoreServicesModule extends EnsureModuleLoadedOnce
1591
1859
  UserService,
1592
1860
  AuthGuard,
1593
1861
  AuthService,
1862
+ ExternalLoginService,
1594
1863
  HeadersService,
1595
1864
  BusMessageService,
1596
1865
  BreadcrumbService,
1597
1866
  ScreenService,
1598
1867
  AppConfiguration,
1599
1868
  HubService,
1869
+ InitCacheService,
1600
1870
  NotificationMqService,
1601
1871
  FilterService,
1602
1872
  provideHttpClient(withXhr(), withInterceptorsFromDi())
@@ -1625,12 +1895,14 @@ i0.ɵɵngDeclareClassMetadata({
1625
1895
  UserService,
1626
1896
  AuthGuard,
1627
1897
  AuthService,
1898
+ ExternalLoginService,
1628
1899
  HeadersService,
1629
1900
  BusMessageService,
1630
1901
  BreadcrumbService,
1631
1902
  ScreenService,
1632
1903
  AppConfiguration,
1633
1904
  HubService,
1905
+ InitCacheService,
1634
1906
  NotificationMqService,
1635
1907
  FilterService,
1636
1908
  provideHttpClient(withXhr(), withInterceptorsFromDi())
@@ -1842,6 +2114,6 @@ i0.ɵɵngDeclareClassMetadata({
1842
2114
  }]
1843
2115
  }]
1844
2116
  });
1845
- export { AppConfiguration, AppKeys, ApplicationMenuService, AuthGuard, AuthInterceptor, AuthService, AuthTokenType, BreadcrumbService, BusMessageService, CanActivateGuard, CoreServicesModule, FilterService, GeolocationService, HeadersService, HubService, LocalStoreManager, MODULE_MENU_SERVICES, MenuItem, MenuService, MessagesService, NotificationMqService, NotificationsService, PermissionService, ScreenService, ServerUrl, UserService, trimChar };
2117
+ export { AppConfiguration, AppKeys, ApplicationMenuService, AuthGuard, AuthInterceptor, AuthService, AuthTokenType, BreadcrumbService, BusMessageService, CanActivateGuard, CoreServicesModule, ExternalLoginService, FilterService, GeolocationService, HeadersService, HubService, InitCacheService, LocalStoreManager, MODULE_MENU_SERVICES, MenuItem, MenuService, MessagesService, NotificationMqService, NotificationsService, PermissionService, ScreenService, ServerUrl, UserService, trimChar };
1846
2118
 
1847
2119
  //# sourceMappingURL=dflat-core-web-core-services.mjs.map