msal-vue-poc 0.1.0

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.
package/README.md ADDED
@@ -0,0 +1,36 @@
1
+ # MSAL Vue PoC
2
+
3
+ A Vue.js library for Microsoft Authentication Library (MSAL) integration.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install msal-vue-poc
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ```typescript
14
+ import { msalService, useUserStore } from 'msal-vue-poc'
15
+
16
+ // Initialize MSAL
17
+ const { initialize, login, logout } = msalService()
18
+ await initialize()
19
+
20
+ // Use the user store
21
+ const userStore = useUserStore()
22
+ ```
23
+
24
+ ## Dependencies
25
+
26
+ This library requires the following peer dependencies:
27
+
28
+ - vue
29
+ - @azure/msal-browser
30
+ - axios
31
+ - pinia
32
+ - vue-router
33
+
34
+ ## License
35
+
36
+ MIT
Binary file
@@ -0,0 +1 @@
1
+ export {}
@@ -0,0 +1 @@
1
+ .el-scrollbar{background-color:bisque}.el-checkbox__input.is-checked+.el-checkbox__label{color:#000}
@@ -0,0 +1,228 @@
1
+ import { reactive as y, ref as p, defineComponent as v, useModel as L, resolveComponent as d, createElementBlock as w, openBlock as g, createVNode as h, withCtx as m, Fragment as R, renderList as z, createBlock as C } from "vue";
2
+ import S from "axios";
3
+ import { PublicClientApplication as E } from "@azure/msal-browser";
4
+ import { defineStore as U } from "pinia";
5
+ const M = {
6
+ auth: {
7
+ clientId: "ae51bfba-500c-472c-88b1-9cd36b982efe",
8
+ authority: "https://login.microsoftonline.com/0922c7a7-1dd1-4058-b146-c62ef3e8cfb4",
9
+ redirectUri: "http://localhost:5173/",
10
+ // Must be registered as a SPA redirectURI
11
+ postLogoutRedirectUri: window.location.origin
12
+ // Must be registered as a SPA redirectURI
13
+ },
14
+ cache: {
15
+ cacheLocation: "localStorage",
16
+ // This configures where your cache will be stored
17
+ storeAuthStateInCookie: !0
18
+ // Required for SSO to work across browser tabs and sessions
19
+ }
20
+ }, V = {
21
+ scopes: ["user.read", "openid", "profile"]
22
+ }, i = y({
23
+ isAuthenticated: !1,
24
+ user: null
25
+ }), s = new E(M);
26
+ function k() {
27
+ return {
28
+ initialize: async () => {
29
+ try {
30
+ await s.initialize();
31
+ } catch (n) {
32
+ console.log("Initialization error", n);
33
+ }
34
+ },
35
+ login: async () => {
36
+ try {
37
+ if (!s)
38
+ throw new Error("MSAL not initialized. Call initializeMsal() before using MSAL API.");
39
+ await s.loginRedirect({
40
+ scopes: [
41
+ "api://b9dffec3-e297-4d57-9c5b-1f7fd682b74f/access_as_user",
42
+ "User.Read",
43
+ "openid",
44
+ "profile"
45
+ ]
46
+ }), i.isAuthenticated = !0;
47
+ } catch (n) {
48
+ console.log(i), console.error("Login error:", n);
49
+ }
50
+ },
51
+ logout: () => {
52
+ if (!s)
53
+ throw new Error("MSAL not initialized. Call initializeMsal() before using MSAL API.");
54
+ s.logoutRedirect(), i.isAuthenticated = !1, i.user = null;
55
+ },
56
+ handleRedirect: async () => {
57
+ try {
58
+ const n = await s.handleRedirectPromise(), a = s.getAllAccounts();
59
+ return i.isAuthenticated = a.length > 0, i.user = a.length > 0 ? a[0] : null, console.log("handleRedirect"), n && console.log("Login successful via redirect"), n;
60
+ } catch (n) {
61
+ throw console.error("Redirect error:", n), n;
62
+ }
63
+ },
64
+ silentLogin: async () => {
65
+ try {
66
+ const n = s.getAllAccounts();
67
+ return n.length > 0 ? (i.isAuthenticated = !0, i.user = n[0] || null, console.log("Using cached account"), !0) : (console.log("No cached account found, interactive login required"), !1);
68
+ } catch (n) {
69
+ return console.log("Silent login failed:", n), !1;
70
+ }
71
+ },
72
+ getToken: async (n) => {
73
+ if (!s)
74
+ throw new Error("MSAL not initialized. Call initializeMsal() before using MSAL API.");
75
+ try {
76
+ const a = s.getAllAccounts();
77
+ if (a.length === 0)
78
+ throw new Error("No accounts found. Please login first.");
79
+ const u = n || ["User.Read"], c = {
80
+ scopes: u,
81
+ account: a[0]
82
+ };
83
+ console.log("Requesting token with scopes:", u);
84
+ const f = await s.acquireTokenSilent(c);
85
+ return console.log("Token acquired successfully"), f.accessToken;
86
+ } catch (a) {
87
+ throw console.error("Silent token acquisition error:", a), a;
88
+ }
89
+ }
90
+ };
91
+ }
92
+ const b = S.create({
93
+ baseURL: "https://graph.microsoft.com/v1.0",
94
+ headers: {
95
+ "Content-Type": "application/json"
96
+ }
97
+ });
98
+ b.interceptors.request.use(async (o) => {
99
+ try {
100
+ const { getToken: e, login: r } = k();
101
+ if (!i.isAuthenticated)
102
+ throw console.warn("Utilisateur non authentifié, déclenchement du login MSAL"), await r(), new Error("Authentification requise, login déclenché");
103
+ const t = await e(["User.Read"]);
104
+ console.log("Token MSAL pour Graph:", t), t && (o.headers.Authorization = `Bearer ${t}`);
105
+ } catch (e) {
106
+ throw console.error("Erreur lors de la récupération du token Graph:", e), e;
107
+ }
108
+ return o;
109
+ });
110
+ function I() {
111
+ const o = p(!1), e = p(null);
112
+ return {
113
+ loading: o,
114
+ error: e,
115
+ getUserProfile: async () => {
116
+ o.value = !0, e.value = null;
117
+ try {
118
+ return (await b.get("/me")).data;
119
+ } catch (t) {
120
+ const l = t;
121
+ return e.value = l.response?.data?.error?.message || l.message || "Erreur lors de la récupération du profil", console.error("Erreur Graph API:", t), null;
122
+ } finally {
123
+ o.value = !1;
124
+ }
125
+ }
126
+ };
127
+ }
128
+ const A = S.create({
129
+ baseURL: "http://127.0.0.1:8000/Api_carto",
130
+ headers: {
131
+ "Content-Type": "application/json",
132
+ "Access-Control-Allow-Origin": "*"
133
+ }
134
+ });
135
+ A.interceptors.request.use(async (o) => {
136
+ try {
137
+ const { getToken: e, login: r } = k();
138
+ if (!i.isAuthenticated)
139
+ throw console.warn("Utilisateur non authentifié, déclenchement du login MSAL"), await r(), new Error("Authentification requise, login déclenché");
140
+ const t = await e(["User.Read"]);
141
+ t && (o.headers["X-Azure-Token"] = `Bearer ${t}`), o.headers.Authorization = "Bearer n3XK~CW9u0m2.r=Z&24w", console.log("cartoApiClient headers:", o.headers);
142
+ } catch (e) {
143
+ throw console.error("Erreur lors de la récupération du token Azure:", e), e;
144
+ }
145
+ return o;
146
+ });
147
+ class T {
148
+ async getAllWorksites(e) {
149
+ const r = this.getAllParameters(e);
150
+ return (await A.get(`/infrastructures?${r.join("&")}`)).data;
151
+ }
152
+ getAllParameters(e) {
153
+ const r = [];
154
+ return e.company_id && e.company_id.forEach((t) => {
155
+ r.push(`id_company=${t}`);
156
+ }), e.of_stage_id && e.of_stage_id.forEach((t) => {
157
+ r.push(`stage_ids=${t}`);
158
+ }), e.power && r.push(`minVal=${e.power[0]}&maxVal=${e.power[1]}`), e.of_structure_type_ids && e.of_structure_type_ids.forEach((t) => {
159
+ r.push(`infra_type=${t}`);
160
+ }), e.partner_id && e.partner_id.forEach((t) => {
161
+ r.push(`partner_id=${t}`);
162
+ }), e.of_start_date && r.push(
163
+ `start_date=${e.of_start_date[0]}&end_date=${e.of_start_date[1]}`
164
+ ), r;
165
+ }
166
+ async getWorksiteStageFilter() {
167
+ return (await A.get("/stage")).data;
168
+ }
169
+ }
170
+ const B = new T(), G = U("user", () => {
171
+ const o = p(null);
172
+ function e(r) {
173
+ o.value = r;
174
+ }
175
+ return console.log(o.value), { user: o, updateUser: e };
176
+ }), j = /* @__PURE__ */ v({
177
+ __name: "StepSelector",
178
+ props: {
179
+ modelValue: { default: [] },
180
+ modelModifiers: {}
181
+ },
182
+ emits: ["update:modelValue"],
183
+ setup(o) {
184
+ const e = L(o, "modelValue"), r = p([]);
185
+ return (t, l) => {
186
+ const _ = d("el-checkbox"), n = d("el-row"), a = d("el-checkbox-group"), u = d("el-scrollbar");
187
+ return g(), w("div", null, [
188
+ h(u, { height: "200px" }, {
189
+ default: m(() => [
190
+ h(a, {
191
+ modelValue: e.value,
192
+ "onUpdate:modelValue": l[0] || (l[0] = (c) => e.value = c),
193
+ "data-test": "steps"
194
+ }, {
195
+ default: m(() => [
196
+ (g(!0), w(R, null, z(r.value, (c, f) => (g(), C(n, { key: f }, {
197
+ default: m(() => [
198
+ h(_, {
199
+ value: c.name,
200
+ label: c.name,
201
+ size: "large"
202
+ }, null, 8, ["value", "label"])
203
+ ]),
204
+ _: 2
205
+ }, 1024))), 128))
206
+ ]),
207
+ _: 1
208
+ }, 8, ["modelValue"])
209
+ ]),
210
+ _: 1
211
+ })
212
+ ]);
213
+ };
214
+ }
215
+ });
216
+ export {
217
+ B as ApiHttpService,
218
+ j as StepSelector,
219
+ A as cartoApi,
220
+ b as graphApi,
221
+ V as graphScopes,
222
+ M as msalConfig,
223
+ s as msalInstance,
224
+ k as msalService,
225
+ i as state,
226
+ I as useGraphApi,
227
+ G as useUserStore
228
+ };
@@ -0,0 +1 @@
1
+ (function(r,t){typeof exports=="object"&&typeof module<"u"?t(exports,require("vue"),require("axios"),require("@azure/msal-browser"),require("pinia")):typeof define=="function"&&define.amd?define(["exports","vue","axios","@azure/msal-browser","pinia"],t):(r=typeof globalThis<"u"?globalThis:r||self,t(r.MsalVuePoc={},r.Vue,r.axios,r.MsalBrowser,r.Pinia))})(this,(function(r,t,A,S,k){"use strict";const _={auth:{clientId:"ae51bfba-500c-472c-88b1-9cd36b982efe",authority:"https://login.microsoftonline.com/0922c7a7-1dd1-4058-b146-c62ef3e8cfb4",redirectUri:"http://localhost:5173/",postLogoutRedirectUri:window.location.origin},cache:{cacheLocation:"localStorage",storeAuthStateInCookie:!0}},b={scopes:["user.read","openid","profile"]},l=t.reactive({isAuthenticated:!1,user:null}),s=new S.PublicClientApplication(_);function h(){return{initialize:async()=>{try{await s.initialize()}catch(a){console.log("Initialization error",a)}},login:async()=>{try{if(!s)throw new Error("MSAL not initialized. Call initializeMsal() before using MSAL API.");await s.loginRedirect({scopes:["api://b9dffec3-e297-4d57-9c5b-1f7fd682b74f/access_as_user","User.Read","openid","profile"]}),l.isAuthenticated=!0}catch(a){console.log(l),console.error("Login error:",a)}},logout:()=>{if(!s)throw new Error("MSAL not initialized. Call initializeMsal() before using MSAL API.");s.logoutRedirect(),l.isAuthenticated=!1,l.user=null},handleRedirect:async()=>{try{const a=await s.handleRedirectPromise(),c=s.getAllAccounts();return l.isAuthenticated=c.length>0,l.user=c.length>0?c[0]:null,console.log("handleRedirect"),a&&console.log("Login successful via redirect"),a}catch(a){throw console.error("Redirect error:",a),a}},silentLogin:async()=>{try{const a=s.getAllAccounts();return a.length>0?(l.isAuthenticated=!0,l.user=a[0]||null,console.log("Using cached account"),!0):(console.log("No cached account found, interactive login required"),!1)}catch(a){return console.log("Silent login failed:",a),!1}},getToken:async a=>{if(!s)throw new Error("MSAL not initialized. Call initializeMsal() before using MSAL API.");try{const c=s.getAllAccounts();if(c.length===0)throw new Error("No accounts found. Please login first.");const f=a||["User.Read"],d={scopes:f,account:c[0]};console.log("Requesting token with scopes:",f);const m=await s.acquireTokenSilent(d);return console.log("Token acquired successfully"),m.accessToken}catch(c){throw console.error("Silent token acquisition error:",c),c}}}}const g=A.create({baseURL:"https://graph.microsoft.com/v1.0",headers:{"Content-Type":"application/json"}});g.interceptors.request.use(async n=>{try{const{getToken:e,login:i}=h();if(!l.isAuthenticated)throw console.warn("Utilisateur non authentifié, déclenchement du login MSAL"),await i(),new Error("Authentification requise, login déclenché");const o=await e(["User.Read"]);console.log("Token MSAL pour Graph:",o),o&&(n.headers.Authorization=`Bearer ${o}`)}catch(e){throw console.error("Erreur lors de la récupération du token Graph:",e),e}return n});function y(){const n=t.ref(!1),e=t.ref(null);return{loading:n,error:e,getUserProfile:async()=>{n.value=!0,e.value=null;try{return(await g.get("/me")).data}catch(o){const u=o;return e.value=u.response?.data?.error?.message||u.message||"Erreur lors de la récupération du profil",console.error("Erreur Graph API:",o),null}finally{n.value=!1}}}}const p=A.create({baseURL:"http://127.0.0.1:8000/Api_carto",headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":"*"}});p.interceptors.request.use(async n=>{try{const{getToken:e,login:i}=h();if(!l.isAuthenticated)throw console.warn("Utilisateur non authentifié, déclenchement du login MSAL"),await i(),new Error("Authentification requise, login déclenché");const o=await e(["User.Read"]);o&&(n.headers["X-Azure-Token"]=`Bearer ${o}`),n.headers.Authorization="Bearer n3XK~CW9u0m2.r=Z&24w",console.log("cartoApiClient headers:",n.headers)}catch(e){throw console.error("Erreur lors de la récupération du token Azure:",e),e}return n});class C{async getAllWorksites(e){const i=this.getAllParameters(e);return(await p.get(`/infrastructures?${i.join("&")}`)).data}getAllParameters(e){const i=[];return e.company_id&&e.company_id.forEach(o=>{i.push(`id_company=${o}`)}),e.of_stage_id&&e.of_stage_id.forEach(o=>{i.push(`stage_ids=${o}`)}),e.power&&i.push(`minVal=${e.power[0]}&maxVal=${e.power[1]}`),e.of_structure_type_ids&&e.of_structure_type_ids.forEach(o=>{i.push(`infra_type=${o}`)}),e.partner_id&&e.partner_id.forEach(o=>{i.push(`partner_id=${o}`)}),e.of_start_date&&i.push(`start_date=${e.of_start_date[0]}&end_date=${e.of_start_date[1]}`),i}async getWorksiteStageFilter(){return(await p.get("/stage")).data}}const z=new C,L=k.defineStore("user",()=>{const n=t.ref(null);function e(i){n.value=i}return console.log(n.value),{user:n,updateUser:e}}),M=t.defineComponent({__name:"StepSelector",props:{modelValue:{default:[]},modelModifiers:{}},emits:["update:modelValue"],setup(n){const e=t.useModel(n,"modelValue"),i=t.ref([]);return(o,u)=>{const w=t.resolveComponent("el-checkbox"),a=t.resolveComponent("el-row"),c=t.resolveComponent("el-checkbox-group"),f=t.resolveComponent("el-scrollbar");return t.openBlock(),t.createElementBlock("div",null,[t.createVNode(f,{height:"200px"},{default:t.withCtx(()=>[t.createVNode(c,{modelValue:e.value,"onUpdate:modelValue":u[0]||(u[0]=d=>e.value=d),"data-test":"steps"},{default:t.withCtx(()=>[(t.openBlock(!0),t.createElementBlock(t.Fragment,null,t.renderList(i.value,(d,m)=>(t.openBlock(),t.createBlock(a,{key:m},{default:t.withCtx(()=>[t.createVNode(w,{value:d.name,label:d.name,size:"large"},null,8,["value","label"])]),_:2},1024))),128))]),_:1},8,["modelValue"])]),_:1})])}}});r.ApiHttpService=z,r.StepSelector=M,r.cartoApi=p,r.graphApi=g,r.graphScopes=b,r.msalConfig=_,r.msalInstance=s,r.msalService=h,r.state=l,r.useGraphApi=y,r.useUserStore=L,Object.defineProperty(r,Symbol.toStringTag,{value:"Module"})}));
package/package.json ADDED
@@ -0,0 +1,67 @@
1
+ {
2
+ "name": "msal-vue-poc",
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "engines": {
6
+ "node": "^20.19.0 || >=22.12.0"
7
+ },
8
+ "scripts": {
9
+ "dev": "vite",
10
+ "build": "run-p type-check \"build-only {@}\" --",
11
+ "preview": "vite preview",
12
+ "build-only": "vite build",
13
+ "type-check": "vue-tsc --build",
14
+ "lint": "eslint . --fix --cache",
15
+ "format": "prettier --write src/"
16
+ },
17
+ "main": "./dist/msal-vue-poc.umd.js",
18
+ "module": "./dist/msal-vue-poc.es.js",
19
+ "types": "./dist/index.d.ts",
20
+ "exports": {
21
+ ".": {
22
+ "types": "./dist/index.d.ts",
23
+ "import": "./dist/msal-vue-poc.es.js",
24
+ "require": "./dist/msal-vue-poc.umd.js"
25
+ }
26
+ },
27
+ "files": [
28
+ "dist"
29
+ ],
30
+ "dependencies": {
31
+ "@azure/msal-browser": "^4.26.0",
32
+ "axios": "^1.13.2",
33
+ "pinia": "^3.0.4",
34
+ "vue": "^3.5.22",
35
+ "vue-router": "^4.6.3",
36
+ "vue3-msal-plugin": "^1.0.5"
37
+ },
38
+ "devDependencies": {
39
+ "@tsconfig/node22": "^22.0.2",
40
+ "@types/node": "^22.18.11",
41
+ "@vitejs/plugin-vue": "^6.0.1",
42
+ "@vue/eslint-config-prettier": "^10.2.0",
43
+ "@vue/eslint-config-typescript": "^14.6.0",
44
+ "@vue/tsconfig": "^0.8.1",
45
+ "eslint": "^9.37.0",
46
+ "eslint-plugin-vue": "~10.5.0",
47
+ "jiti": "^2.6.1",
48
+ "npm-run-all2": "^8.0.4",
49
+ "prettier": "3.6.2",
50
+ "typescript": "~5.9.0",
51
+ "vite": "^7.1.11",
52
+ "vite-plugin-dts": "^4.5.4",
53
+ "vite-plugin-vue-devtools": "^8.0.3",
54
+ "vue-tsc": "^3.1.1"
55
+ },
56
+ "description": "poc de l'auth msal front vue",
57
+ "repository": {
58
+ "type": "git",
59
+ "url": "git+https://github.com/See-You-Sun/package-vue-msal.git"
60
+ },
61
+ "author": "lise",
62
+ "license": "MIT",
63
+ "bugs": {
64
+ "url": "https://github.com/See-You-Sun/package-vue-msal/issues"
65
+ },
66
+ "homepage": "https://github.com/See-You-Sun/package-vue-msal#readme"
67
+ }