summaryrefslogtreecommitdiffstats
path: root/dozentenmodul/src/main/java/org/openslx/dozmod/gui/window/LoginWindow.java
blob: 2f1271c9ed38aa23aff9e414702076c1059e8985 (plain) (blame)
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
388
package org.openslx.dozmod.gui.window;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.apache.log4j.Logger;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Shell;
import org.openslx.bwlp.thrift.iface.Organization;
import org.openslx.bwlp.thrift.iface.TAuthenticationException;
import org.openslx.bwlp.thrift.iface.UserInfo;
import org.openslx.dozmod.Config;
import org.openslx.dozmod.authentication.Authenticator;
import org.openslx.dozmod.authentication.Authenticator.AuthenticatorCallback;
import org.openslx.dozmod.authentication.EcpAuthenticator;
import org.openslx.dozmod.authentication.ShibbolethEcp;
import org.openslx.dozmod.authentication.ShibbolethEcp.ReturnCode;
import org.openslx.dozmod.authentication.TestAccountAuthenticator;
import org.openslx.dozmod.gui.MainWindow;
import org.openslx.dozmod.gui.helper.Gui;
import org.openslx.dozmod.gui.helper.MessageType;
import org.openslx.dozmod.gui.window.layout.LoginWindowLayout;
import org.openslx.dozmod.thrift.OrganizationCache;
import org.openslx.thrifthelper.ThriftManager;
import org.openslx.util.QuickTimer;
import org.openslx.util.QuickTimer.Task;

import edu.kit.scc.dei.ecplean.ECPAuthenticationException;

/**
 * @author Jonathan Bauer
 * 
 */
public class LoginWindow extends LoginWindowLayout {

	private final static Logger LOGGER = Logger.getLogger(LoginWindow.class);

	// text constants
	private final String NO_USERNAME = "Kein Benutzername angegeben!";
	private final String NO_PASSWORD = "Kein Passwort angegeben!";

	/**
	 * Constructor doing the setup of the logical GUI functions
	 * Fetches the organization list for BWIDM logins and
	 * adds mouse/keyboard event listeners to various widgets.
	 * 
	 * @param mainShell
	 */
	public LoginWindow(final Shell mainShell) {
		// call the constructor of the superclass
		super(mainShell);

		// fetch the list of the identity providers as an async Thread
		// else the GUI is blocked until this is done.
		idpCombo.add("Initialisiere...");
		idpCombo.select(0);
		idpCombo.setEnabled(false);
		QuickTimer.scheduleOnce(new Task() {
			List<Organization> orgs = null;

			@Override
			public void fire() {
				try {
					orgs = OrganizationCache.getAll();
				} catch (Exception e) {
					LoginWindow.LOGGER.error("Error during execution: ", e);
				}
				// now send the organisations back to the LoginWindow
				// through populateIdpCombo()
				Gui.display.asyncExec(new Runnable() {
					@Override
					public void run() {
						populateIdpCombo(orgs);
					}
				});
			}
		});

		// check if we had saved an authentication method
		String savedAuthMethod = Config.getAuthenticationMethod();
		if (savedAuthMethod != null && !savedAuthMethod.isEmpty()) {
			LOGIN_TYPE savedLoginType = LOGIN_TYPE.getEnum(savedAuthMethod);
			// if no valid LOGIN_TYPE was saved, just enable the BWIDM button
			if (savedLoginType == null) {
				authButtons[LOGIN_TYPE.BWIDM.getId()].setSelection(true);
				loginType = LOGIN_TYPE.BWIDM;
				idpText.setVisible(true);
				idpCombo.setVisible(true);
			} else {
				authButtons[savedLoginType.getId()].setSelection(true);
				loginType = savedLoginType;
				// enable the IDP combo only if we actually have items in it
				idpText.setVisible(savedLoginType == LOGIN_TYPE.BWIDM);
				idpCombo.setVisible(savedLoginType == LOGIN_TYPE.BWIDM);
			}
		} else {
			// default value for LOGIN_TYPE is BWIDM
			authButtons[LOGIN_TYPE.BWIDM.getId()].setSelection(true);
			loginType = LOGIN_TYPE.BWIDM;
		}

		// finally check if we had a saved username
		String savedUsername = Config.getUsername();
		if (savedUsername != null && !savedUsername.isEmpty()) {
			usernameText.setText(savedUsername);
			saveUsernameCheck.setSelection(true);
			passwordText.setFocus();
		} else
			usernameText.setFocus();

		// actions of the login button
		loginButton.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				doSaveConfig();
				doLogin();
			}
		});

		// for save username checkbox.
		saveUsernameCheck.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				// clickedSaveUsernameCheck();
			}
		});

		// selecting the "Authentifizierung über bwIDM" radio button
		authButtons[0].addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				idpText.setVisible(true);
				idpCombo.setVisible(true);
				loginType = LOGIN_TYPE.BWIDM;
			}
		});

		// selecting the "Test-Zugang mit festem Benutzer" radio button
		authButtons[1].addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				idpText.setVisible(false);
				idpCombo.setVisible(false);
				loginType = LOGIN_TYPE.BWLP;
			}
		});

		authButtons[2].setEnabled(false);
		// selecting the "Direkte Verbindung zum Satteliten" radio button
		authButtons[2].addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				idpText.setVisible(false);
				idpCombo.setVisible(false);
				loginType = LOGIN_TYPE.SAT;
			}
		});

		// add a key listener to the password field to trigger login
		// when the user presses the ENTER key.
		passwordText.addKeyListener(new KeyListener() {

			@Override
			public void keyReleased(KeyEvent e) {
				if (e.keyCode == SWT.CR || e.keyCode == SWT.KEYPAD_CR) {
					doSaveConfig();
					doLogin();
				}
			}

			@Override
			public void keyPressed(KeyEvent e) {
			}
		});
	}

	public void populateIdpCombo(List<Organization> orgs) {

		// safety check to see if the login window still exists
		// when this function gets called by the other thread
		if (this.isDisposed())
			return;
		// always clearup the list first
		idpCombo.removeAll();

		// sanity checks on orgs
		if (orgs == null) {
			LOGGER.error("No organizations received from the cache.");
			idpCombo.add("No entries");
			return;
		}

		// all fine, lets sort it
		Collections.sort(orgs, new Comparator<Organization>() {
			public int compare(Organization o1, Organization o2) {
				return o1.getDisplayName().compareTo(o2.getDisplayName());
			}
		});

		// now check if we had a saved identity provider
		String savedOrganizationId = Config.getIdentityProvider();
		// add only organizations which have an ECP URL to the combobox
		for (Organization o : orgs) {
			if (o.getEcpUrl() == null | o.getEcpUrl().isEmpty())
				continue;
			LOGGER.debug("Adding: " + o.toString());
			idpCombo.add(o.displayName);
			idpCombo.setData(o.displayName, o);
			if (savedOrganizationId != null && !savedOrganizationId.isEmpty()
					&& savedOrganizationId.equals(o.getOrganizationId()))
				// select the organization we just added, this seems kinda bad - is there a better way?
				idpCombo.select(idpCombo.getItemCount() - 1);
			//idpCombo.select(idpCombo.indexOf(savedOrganizationId)); this is probably not optimal... but safer
		}
		// if no organization was saved, none is selected, so select the first one in the combobox
		if (idpCombo.getSelectionIndex() == -1)
			idpCombo.select(0);
		// finally re-enable it
		if (idpCombo.isVisible())
			idpCombo.setEnabled(true);
	}

	/**
	 * Saves various user choices to the config file.
	 * This gets triggered when the login button is activated.
	 */
	private void doSaveConfig() {
		// first we need to check if the "Remember me" button is active
		if (saveUsernameCheck.isEnabled()) {
			// save username
			String username = usernameText.getText();
			if (username != null && !username.isEmpty()) {
				// all good, save it
				if (!Config.setUsername(username))
					LOGGER.error("Could not save username '" + username + "' to '" + Config.getPath() + "'.");
			}
		}
		// always save the authentication method and potentially the identity provider
		if (!Config.setAuthenticationMethod(loginType.getTag()))
			LOGGER.error("Could not save authentication method '" + loginType.getTag() + "' to '"
					+ Config.getPath() + "'.");
		// check if we are doing bwIDM authentication
		if (loginType == LOGIN_TYPE.BWIDM) {
			// save the selected identity provider
			Organization selectedOrg = getSelectedOrganization();
			if (!Config.setIdentityProvider(selectedOrg.organizationId))
				LOGGER.error("Could not save the identity provider '" + selectedOrg.organizationId + "'!");
		}
		// finalize by actually storing the config file
		if (!Config.store())
			LOGGER.error("Could not save '" + Config.getPath() + "'!");
	}

	/**
	 * Actually do the login using the username/password in the field using the
	 * authentication mechanism corresponding to the selected authButton
	 * 
	 * @throws ECPAuthenticationException
	 */
	private void doLogin() {
		// sanity check on loginType.
		if (loginType == null) {
			MainWindow.showMessageBox(this.getShell(),
					"No login type set, a default should be set! Ignoring...", MessageType.ERROR, LOGGER,
					null);
			return;
		}
		// here we only check for the fields
		String username = usernameText.getText();
		String password = passwordText.getText();
		// login clicked, lets first read the fields
		if (username.isEmpty()) {
			MainWindow.showMessageBox(this.getShell(), NO_USERNAME, MessageType.ERROR, null, null);
			return;
		}
		if (password.isEmpty()) {
			MainWindow.showMessageBox(this.getShell(), NO_PASSWORD, MessageType.ERROR, null, null);
			return;
		}

		// determine which organization was selected by the user.
		// TODO: Needed for test accounts?
		Organization selectedOrg = getSelectedOrganization();

		// Setup login callback
		final LoginWindow me = this;
		AuthenticatorCallback authenticatorCallback = new AuthenticatorCallback() {
			@Override
			public void postLogin(ReturnCode returnCode, UserInfo user, Throwable t) {
				// TODO finish this
				if (user == null) {
					MainWindow.showMessageBox(me.getShell(),
							"User information received from the masterserver is corrupt!", MessageType.ERROR,
							LOGGER, null);
					return;
				}
				switch (returnCode) {
				case NO_ERROR:
					postSuccessfulLogin();
					break;
				case IDENTITY_PROVIDER_ERROR:
					MainWindow.showMessageBox(me.getShell(), "IdP Error", MessageType.ERROR, null, null);
					break;
				case SERVICE_PROVIDER_ERROR:
					// here if we have t != null then we have not received a token
					// if we have t, then the token is invalid.
					MainWindow.showMessageBox(me.getShell(), "Invalid token from the service provider!",
							MessageType.ERROR, LOGGER, t);
					break;
				case UNREGISTERED_ERROR:
					MainWindow.showMessageBox(
							me.getShell(),
							"You are not registered to bwLehrpool. Please visit "
									+ ShibbolethEcp.getRegistrationUrl() + " and register first.",
							MessageType.ERROR, LOGGER, t);
					break;
				default:
					MainWindow.showMessageBox(me.getShell(), "Internal error!", MessageType.ERROR, null, null);
					break;
				}
			}
		};

		// now switch over the login types.
		Authenticator authenticator;
		switch (loginType) {
		case BWIDM:
			authenticator = new EcpAuthenticator(selectedOrg.getEcpUrl());
			break;
		case BWLP:
			authenticator = new TestAccountAuthenticator();
			break;
		case SAT:
			MainWindow.showMessageBox(this.getShell(), "Not yet implemented", MessageType.ERROR, null, null);
			return;
		default:
			MainWindow.showMessageBox(this.getShell(), "No login type selected!", MessageType.ERROR, null,
					null);
			return;
		}

		// Excute login
		try {
			authenticator.login(username, password, authenticatorCallback);
		} catch (TAuthenticationException e) {
			MainWindow.showMessageBox(me.getShell(), "Authentication failed: " + e.getMessage(),
					MessageType.ERROR, LOGGER, null);
			return;
		}
	}

	/**
	 * Functions called by doLogin is the login process succeeded.
	 */
	private void postSuccessfulLogin() {
		LOGGER.info(loginType.getTag() + " succeeded.");

		// TODO HACK HACK
		ThriftManager.setSatelliteAddress("132.230.8.113");

		// now read the config to see if the user already agreed to the disclaimer
		if (!Config.getDisclaimerAgreement())
			MainWindow.openPopup(DisclaimerWindow.class, true);
		if (!Config.getVmwareLicenseAgreement())
			MainWindow.openPopup(VirtualizerNoticeWindow.class, true);

		getShell().dispose();
	}

	/**
	 * @return the organization currently selected in the combobox for identity
	 *         providers
	 */
	private final Organization getSelectedOrganization() {
		// get the index of the selected item in the combobox
		int selectionIndex = idpCombo.getSelectionIndex();
		if (selectionIndex == -1) {
			LOGGER.error("No identity provider is selected in the combobox. There should be a default value!");
			return null;
		}
		return (Organization) idpCombo.getData(idpCombo.getItem(selectionIndex));
	}
}