-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAuth.java
More file actions
387 lines (283 loc) · 13.2 KB
/
Copy pathAuth.java
File metadata and controls
387 lines (283 loc) · 13.2 KB
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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
package javaxt.demo.express;
import java.util.*;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.ConcurrentHashMap;
import javaxt.http.servlet.*;
import javaxt.io.Directory;
import static javaxt.utils.Console.*;
import javaxt.express.*;
import static javaxt.demo.express.Utils.*;
//******************************************************************************
//** Auth
//******************************************************************************
/**
* Used to run authentication-related demos
*
******************************************************************************/
public class Auth {
private static String[] demos = new String[]{"BasicAuth","EmailLogin"};
//**************************************************************************
//** hasDemo
//**************************************************************************
public static boolean hasDemo(String demo){
for (String d : demos){
if (d.equalsIgnoreCase(demo)) return true;
}
return false;
}
//**************************************************************************
//** start
//**************************************************************************
public static void start(Directory demoDir, HashMap<String, String> args){
String demo = args.get("-demo");
if (demo.equalsIgnoreCase("BasicAuth")){
var webDir = new javaxt.io.Directory(demoDir + "auth/basic");
basicAuth(webDir, args);
}
else if (demo.equalsIgnoreCase("EmailLogin")){
var webDir = new javaxt.io.Directory(demoDir + "auth/email");
emailLogin(webDir, args);
}
else{
System.out.println("Unknown/unsupported -demo value. Given \"" + demo + "\"");
}
}
//**************************************************************************
//** basicAuth
//**************************************************************************
/** Used to demonstrate basic authentication using a simple username and
* password.
*/
private static void basicAuth(Directory web, HashMap<String, String> args){
//Prompt user to define a valid username and password
String username = getInput("Username: ");
String password = getPassword("Password: ");
//Create an approved/authorized User
var authorizedUser = new User(username, password);
System.out.println(username + " user created!");
//Create a simple Authenticator used to validate credentials associated
//with an HTTP Request. In this demo we only have one approved User.
//If the credentials match the username/password of the approved
//user, then the user is returned via the getPrinciple(). If the
//credentials are null or invalid, a null user is returned.
var basicAuthenticator = new javaxt.express.Authenticator(){
public java.security.Principal getPrinciple(){
User user = null;
try{
String[] credentials = getCredentials();
String username = credentials[0];
String password = credentials[1];
if (username!=null && password!=null){
if (username.equalsIgnoreCase(authorizedUser.username) &&
password.equals(authorizedUser.password)){
user = authorizedUser;
}
}
}
catch(Exception e){}
setUser(user);
return user;
}
};
//Create a custom HttpServlet
var servlet = new HttpServlet() {
//Instantiate FileManager
private FileManager fileManager = new FileManager(web);
//Assign authenticator to this servlet
{this.setAuthenticator(basicAuthenticator);}
//
public void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
if (request.isWebSocket()) return;
//Get path from url, excluding servlet path and leading "/" character
String path = request.getPathInfo();
if (path!=null) path = path.substring(1);
//Get first "directory" in the path
String service = path==null ? "" : path.toLowerCase();
if (service.contains("/")) service = service.substring(0, service.indexOf("/"));
//Pass the request to the authenticator. Return early if the
//authenticator handled the request.
javaxt.express.Authenticator authenticator = (javaxt.express.Authenticator) getAuthenticator(request);
if (authenticator.handleRequest(service, response)) return;
//Send static file if we can
if (service.length()==0){
//If the service is empty, send welcome file (e.g. index.html)
fileManager.sendFile(request, response);
}
else{
//Check if the service matches a file or folder in the web
//directory. If so, send the static file as requested.
for (Object obj : web.getChildren()){
String name;
if (obj instanceof javaxt.io.File){
name = ((javaxt.io.File) obj).getName();
}
else{
name = ((javaxt.io.Directory) obj).getName();
}
if (service.equalsIgnoreCase(name)){
fileManager.sendFile(path, request, response);
return;
}
}
}
}
};
//Start web server
startServer(args, servlet);
}
//**************************************************************************
//** emailLogin
//**************************************************************************
private static void emailLogin(Directory web, HashMap<String, String> args){
//Prompt user to provide SMPT connection info
String host = getInput("SMPT Host: ");
String username = getInput("Username: ");
String password = getPassword("Password: ");
Integer port = 465;
if (host.contains(":")){
int idx = host.indexOf(":");
port = Integer.parseInt(host.substring(idx+1));
host = host.substring(0, idx);
}
//Get email address that will be used to send messages
String emailFrom;
if (username.contains("@")){
emailFrom = username;
}
else{
emailFrom = getInput("Email: ");
}
//Instantiate email service
var emailService = new javaxt.express.email.EmailService(
host, port, username, password
);
//Get email template (html)
String emailTemplate = new javaxt.io.File(web, "email.html").getText();
var loginSessions = new ConcurrentHashMap<String, HashSet<String>>();
//Create a simple Authenticator used to validate credentials associated
//with an HTTP Request. In this demo we use BASIC authentication.
//However, instead of storing a username/password we use an email
//address and a temportary access code as the credentials.
var emailAuthenticator = new javaxt.express.Authenticator(){
public java.security.Principal getPrinciple(){
//Get user from cache
User user = (User) getUser();
if (user!=null) return user;
try{
String[] credentials = getCredentials();
String email = credentials[0];
String accessCode = credentials[1];
if (email!=null && accessCode!=null){
synchronized (loginSessions){
HashSet<String> codes = loginSessions.get(email);
if (codes!=null && codes.contains(accessCode)){
user = new User(email, accessCode);
}
}
}
}
catch(Exception e){
}
setUser(user);
return user;
}
};
//Create a custom HttpServlet
var servlet = new HttpServlet() {
//Instantiate FileManager
private FileManager fileManager = new FileManager(web);
//Assign authenticator to this servlet
{this.setAuthenticator(emailAuthenticator);}
//
public void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
if (request.isWebSocket()) return;
//Get path from url, excluding servlet path and leading "/" character
String path = request.getPathInfo();
if (path!=null) path = path.substring(1);
//Get first "directory" in the path
String service = path==null ? "" : path.toLowerCase();
if (service.contains("/")) service = service.substring(0, service.indexOf("/"));
//Pass the request to the authenticator. Return early if the
//authenticator handled the request.
javaxt.express.Authenticator authenticator = (javaxt.express.Authenticator) getAuthenticator(request);
if (authenticator.handleRequest(service, response)) return;
//Send static file if we can
if (service.length()==0){
//If the service is empty, send welcome file (e.g. index.html)
fileManager.sendFile(request, response);
return;
}
else{
//Check if the service matches a file or folder in the web
//directory. If so, send the static file as requested.
for (Object obj : web.getChildren()){
String name;
if (obj instanceof javaxt.io.File){
name = ((javaxt.io.File) obj).getName();
}
else{
name = ((javaxt.io.Directory) obj).getName();
}
if (service.equalsIgnoreCase(name)){
fileManager.sendFile(path, request, response);
return;
}
}
}
//
if (service.equalsIgnoreCase("sendCode")){
User user = (User) authenticator.getPrinciple();
if (user!=null){
response.sendError(400, "User already logged in");
return;
}
//Get email address from the body of the request
String emailAddress = new String(request.getBody());
if (emailAddress==null || !emailAddress.contains("@")){
response.sendError(400, "Invalid email address");
return;
}
//Generate access code
String accessCode = generateAccessCode();
//Generate email message
String html = emailTemplate.replace("<%=code%>", accessCode);
//Send email to user
try{
var email = emailService.createEmail();
email.setFrom(emailFrom, "JavaXT Express");
email.addRecipient(emailAddress);
email.setSubject("Your single-use code");
email.setContent(html, "text/html");
email.send();
synchronized (loginSessions){
HashSet<String> codes = loginSessions.get(emailAddress);
if (codes==null){
codes = new HashSet<>();
loginSessions.put(emailAddress, codes);
}
codes.add(accessCode);
}
}
catch(Exception e){
e.printStackTrace();
response.sendError(500);
}
}
}
};
//Start web server
startServer(args, servlet);
}
//**************************************************************************
//** generateAccessCode
//**************************************************************************
private static String generateAccessCode() {
//Generate random 6 digit number from 0 to 999999
Random rnd = new Random();
int number = rnd.nextInt(999999);
//Format the number into a 6 character string
return String.format("%06d", number);
}
}