-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMicrosoftAuthenticationMain.ts
176 lines (152 loc) · 6 KB
/
MicrosoftAuthenticationMain.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
import { BrowserWindow, ipcMain, session } from "electron";
import { mainWindow } from "../index";
import { CustomError } from "./../helper/CustomError";
let accessToken: string = null;
/**
* Gets the accesstoken
*
* @returns the accestokenb
*/
export const getAccessToken = () => {
return accessToken;
}
/**
*Sets the accesstoken
*
* @param {string} token the new accesstoken
*/
export const setAccessToken = (token: string) => {
accessToken = token;
}
/**
* The necesarry user authenication information
*
* @export
* @interface UserAuthenticaton
*/
export interface UserAuthenticaton {
/**
* The accesstoken of the user
*
* @type {string}
* @memberof UserAuthenticaton
*/
accessToken: string;
/**
* The exporation time of the accesstoken (in seconds)
*
* @type {number}
* @memberof UserAuthenticaton
*/
expirationTime: number;
}
/**
* A function to authenticate the current user
*
* @returns {UserAuthenticaton} A Promise containing the user Authentication or a Custom Error.
*/
export const authenticateUser: () => Promise<UserAuthenticaton> = () => {
return new Promise<UserAuthenticaton>((resolve, reject) => {
let authenticated: boolean = false;
let authWindow = new BrowserWindow(
{
alwaysOnTop: true,
modal: true,
autoHideMenuBar: true,
parent: mainWindow,
frame: true,
show: false,
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
devTools: false
}
}
);
authWindow.on('closed', () => {
if (!authenticated) {
reject(new CustomError("Authentication aborted by the user", "export const authenticateUser: () => Promise<UserAuthenticaton>", new Error("Authentication aborted by the user")));
}
authWindow = null;
});
authWindow.setMenu(null);
let filter = { urls: [process.env.REDIRECT_URL] };
authWindow.webContents.on('did-finish-load', () => {
authWindow.show();
});
if (process.env.TENANT_ID && process.env.CLIENT_ID && process.env.RESOURCE && process.env.REDIRECT_URL) {
authWindow.loadURL(`https://login.microsoftonline.com/${process.env.TENANT_ID}/oauth2/authorize?client_id=${process.env.CLIENT_ID}&response_type=token&scope=openid&redirect_uri=${process.env.REDIRECT_URL}&response_mode=fragment&nonce=&state=45&resource=${encodeURIComponent(process.env.RESOURCE)}`)
} else {
reject(new CustomError("One or more enviroment variables are undefined. Please adjust production or developement eviroment and try running microsoft authentication again", "export const authenticateUser: () => Promise<UserAuthenticaton>", new Error("Enviroment variables are undefined")));
}
session.defaultSession.webRequest.onCompleted(filter, (details: Electron.OnCompletedListenerDetails) => {
var url = details.url;
let accessToken = url.match(/\#(?:access_token)\=([\S\s]*?)\&/)[1];
let expirationTime = Number(url.match(/expires_in=\d*&/)[0].replace(/expires_in=/, "").replace(/&/, ""));
authenticated = true;
authWindow.close();
resolve({ accessToken, expirationTime });
});
});
}
ipcMain.on("get-access-token", (event: Electron.IpcMainEvent, guid: string) => {
if (getAccessToken() != null) {
event.sender.send(guid, getAccessToken());
} else {
authenticateUser()
.then(UserAuthentication => {
setAccessToken(UserAuthentication.accessToken);
setTimeout(() => { setAccessToken(null) }, (UserAuthentication.expirationTime - 1) * 1000)
event.sender.send(guid, UserAuthentication.accessToken);
}).catch((err) => {
event.sender.send(guid, err);
});
}
});
/**
* Logs the user off
*
* @returns a Promise which gets resolve when the user logoff was successfull and rejected if the action was not successfull
*/
export const logoutUser: () => Promise<null> = () => {
return new Promise<null>((resolve, reject) => {
let logoutWindow = new BrowserWindow(
{
alwaysOnTop: true, // keeps this window on top of others
modal: true,
autoHideMenuBar: true,
parent: mainWindow,
frame: true,
show: false,
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
devTools: false
},
}
);
logoutWindow.on('closed', () => {
logoutWindow = null;
});
logoutWindow.setMenu(null);
let filter = { urls: [process.env.REDIRECT_URL] };
logoutWindow.webContents.on('did-finish-load', () => {
// logoutWindow.show();
});
if (process.env.CLIENT_ID && process.env.REDIRECT_URL) {
logoutWindow.loadURL(`https://login.microsoftonline.com/common/oauth2/logout?client_id=${process.env.CLIENT_ID}&response_mode=form_post&post_logout_redirect_uri=${process.env.REDIRECT_URL}`)
} else {
reject(new CustomError("One or more enviroment variables are undefined. Please adjust production or developement eviroment and try running microsoft logout again", "export const logoutUser: () => Promise<null>", new Error("Enviroment variables are undefined")));
}
session.defaultSession.webRequest.onCompleted(filter, (details: Electron.OnCompletedListenerDetails) => {
logoutWindow.close();
resolve(null);
});
});
}
ipcMain.on("logout", (event: Electron.IpcMainEvent, guid: string) => {
setAccessToken(null);
logoutUser()
.then((_) => { event.sender.send(guid, null) })
.catch(err => { event.sender.send(guid, err) });
});