-
Notifications
You must be signed in to change notification settings - Fork 136
/
Copy pathauth.ts
263 lines (224 loc) · 9.11 KB
/
auth.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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
import debug from 'debug';
debug('app:auth')
import { Passport, Authenticator, AuthenticateOptions} from 'passport';
import { Strategy as LocalStrategy } from 'passport-local';
import { Strategy as GitHubStrategy } from 'passport-github2';
import { Strategy as OAuth2Strategy } from 'passport-oauth2';
import { Strategy as BearerStrategy } from 'passport-http-bearer';
import { Request, Response, NextFunction } from 'express';
import * as crypto from "crypto"
import axios from 'axios';
export type User = {
id: number,
method: string,
username: string,
apitoken?: string
}
export class Auth {
public passport;
public authmethods = {
local: false,
github: false,
oauth2: false,
}
public authentication: boolean;
private users = []
constructor() {
this.passport = new Passport();
(process.env.KUBERO_USERS) ? this.authmethods.local = true : this.authmethods.local = false;
(process.env.GITHUB_CLIENT_ID &&
process.env.GITHUB_CLIENT_SECRET &&
process.env.GITHUB_CLIENT_CALLBACKURL ) ? this.authmethods.github = true : this.authmethods.github = false;
(process.env.OAUTO2_CLIENT_NAME &&
process.env.OAUTO2_CLIENT_AUTH_URL &&
process.env.OAUTO2_CLIENT_TOKEN_URL &&
process.env.OAUTH2_CLIENT_ID &&
process.env.OAUTH2_CLIENT_SECRET &&
process.env.OAUTH2_CLIENT_CALLBACKURL ) ? this.authmethods.oauth2 = true : this.authmethods.oauth2 = false;
this.authentication = false;
if (this.authmethods.local || this.authmethods.github || this.authmethods.oauth2) {
this.authentication = true;
}
}
init() {
if (this.authmethods.local) {
//console.log("initialize Local Auth");
try {
const b = process.env.KUBERO_USERS as string
this.users = JSON.parse(b);
} catch (error) {
console.log("ERROR loading local Users");
debug.log(error);
}
debug.debug('loaded users: ' + JSON.stringify(this.users));
this.passport.use(
'local',
new LocalStrategy({
usernameField: "username",
passwordField: "password"
},
(username, password, done) => {
let profile: any = this.users.find((u: any) => {
if (u.insecure) {
return u.username === username && u.password === password
} else if (!u.insecure && process.env.KUBERO_SESSION_KEY) {
return u.username === username && u.password === crypto.createHmac('sha256', process.env.KUBERO_SESSION_KEY).update(password).digest('hex')
}
})
if (profile) {
const user: User = {
method: 'local',
id: profile.id,
username: profile.username,
}
done(null, user)
} else {
done(null, false, { message: 'Incorrect username or password'})
}
})
)
this.passport.use(
'bearer',
new BearerStrategy(
(apitoken, done) => {
let profile: any = this.users.find((u: any) => {
if (u.apitoken) {
return u.apitoken === apitoken
}
})
if (profile) {
const user: User = {
method: 'local',
id: profile.id,
username: profile.username,
}
done(null, user)
} else {
done(null, false)
}
}
)
);
}
if (this.authmethods.github) {
console.log("initialize Github Auth");
this.passport.use(
'github',
new GitHubStrategy({
clientID: process.env.GITHUB_CLIENT_ID as string,
clientSecret: process.env.GITHUB_CLIENT_SECRET as string,
callbackURL: process.env.GITHUB_CLIENT_CALLBACKURL as string
},
async function(accessToken: string, refreshToken: string, profile: any, done: any) {
debug.debug( JSON.stringify(profile));
const orgas = await axios.get(profile._json.organizations_url)
//console.log("orgas: "+JSON.stringify(orgas.data))
//const orgAllowed = process.env.GITHUB_ORG || false
const org = orgas.data.find((o: any) => {
return o.login === process.env.GITHUB_CLIENT_ORG
} )
if (org) {
const user: User = {
method: 'github',
id: profile.id,
username: profile.username,
}
done(null, user);
} else {
console.log(profile.username+' is not in allowed organisation '+process.env.GITHUB_CLIENT_ORG)
done(null, false, { message: 'Not in allowed organisation'})
}
})
);
}
if (this.authmethods.oauth2) {
let scope = [ 'user:email' ];
if(process.env.OAUTH2_CLIENT_SCOPE) {
scope = process.env.OAUTH2_CLIENT_SCOPE.split(' ');
}
this.passport.use(new OAuth2Strategy({
authorizationURL: process.env.OAUTO2_CLIENT_AUTH_URL as string,
tokenURL: process.env.OAUTO2_CLIENT_TOKEN_URL as string,
clientID: process.env.OAUTH2_CLIENT_ID as string,
clientSecret: process.env.OAUTH2_CLIENT_SECRET as string,
callbackURL: process.env.OAUTH2_CLIENT_CALLBACKURL as string,
scope
},
function(accessToken: string, refreshToken: string, profile: any, done: any) {
debug.debug( JSON.stringify(profile));
const user: User = {
method: 'oauth2',
id: profile.id,
username: profile.username,
}
/*
User.findOrCreate({ exampleId: profile.id }, function (err, user) {
return done(null, user);
});
*/
done(null, user);
}
));
}
this.passport.serializeUser((user: any, done: any) => {
debug.debug(JSON.stringify(user))
done(null, user)
})
this.passport.deserializeUser((authUser: any, done: any) => {
debug.debug(JSON.stringify(authUser))
// try to deserialize user from local environment
let user: User | undefined = undefined;
if (authUser.method === 'local') {
user = this.users.find((user: User) => {
return user.id === authUser.id
})
if (user) {
debug.debug("deserialize local user : "+ JSON.stringify(user));
done(null, user)
}
}
if (authUser.method === 'github') {
done(null, authUser);
}
if (authUser.method === 'oauth2') {
done(null, authUser);
}
})
}
public authMiddleware(req: Request, res: Response, next: NextFunction): void {
if (typeof(req.isAuthenticated) !== "function" || !req.isAuthenticated()) {
debug.debug("not authenticated")
res.status(401).send('You are not authenticated')
} else {
debug.debug("authenticated")
return next()
}
}
private noAuthMiddleware(req: Request, res: Response, next: NextFunction) {
return next()
}
public getAuthMiddleware(): any {
if (this.authentication === true) {
return this.authMiddleware;
} else {
// skip middleware if no users defined
return this.noAuthMiddleware;
}
}
public getBearerMiddleware() {
return this.passport.authenticate('bearer', { session: false })
}
public getUser(req: Request): User {
let user: User = {
id: 0,
method: '',
username: 'anonymous'
}
if (typeof(req.isAuthenticated) == "function" && req.isAuthenticated()) {
const sessionWithPassport = req.session as any & { passport: User };
user = sessionWithPassport.passport.user;
}
//console.log("extractUser: "+JSON.stringify(user))
return user;
}
}