/** * Filters out any login handler that doesn't support passive authentication if the login context * indicates passive authentication is required. * * @param idpSession user's current IdP session * @param loginContext current login context * @param loginHandlers login handlers to filter * @throws PassiveAuthenticationException thrown if no handlers remain after filtering */ protected void filterByPassiveAuthentication( Session idpSession, LoginContext loginContext, Map<String, LoginHandler> loginHandlers) throws PassiveAuthenticationException { LOG.debug( "Passive authentication is required, filtering poassible login handlers accordingly."); if (idpSession == null) { loginHandlers.remove(AuthnContext.PREVIOUS_SESSION_AUTHN_CTX); } LoginHandler loginHandler; Iterator<Entry<String, LoginHandler>> authnMethodItr = loginHandlers.entrySet().iterator(); while (authnMethodItr.hasNext()) { loginHandler = authnMethodItr.next().getValue(); if (!loginHandler.supportsPassive()) { authnMethodItr.remove(); } } LOG.debug( "Authentication handlers remaining after passive authentication requirement filtering: {}", loginHandlers); if (loginHandlers.isEmpty()) { LOG.warn("Passive authentication required but no login handlers available to support it"); throw new PassiveAuthenticationException(); } }
/** * Filters out any login handler based on the requirement for forced authentication. * * <p>During forced authentication any handler that has not previously been used to authenticate * the user or any handlers that have been and support force re-authentication may be used. Filter * out any of the other ones. * * @param idpSession user's current IdP session * @param loginContext current login context * @param loginHandlers login handlers to filter * @throws ForceAuthenticationException thrown if no handlers remain after filtering */ protected void filterByForceAuthentication( Session idpSession, LoginContext loginContext, Map<String, LoginHandler> loginHandlers) throws ForceAuthenticationException { LOG.debug("Forced authentication is required, filtering possible login handlers accordingly"); ArrayList<AuthenticationMethodInformation> activeMethods = new ArrayList<AuthenticationMethodInformation>(); if (idpSession != null) { activeMethods.addAll(idpSession.getAuthenticationMethods().values()); } loginHandlers.remove(AuthnContext.PREVIOUS_SESSION_AUTHN_CTX); LoginHandler loginHandler; for (AuthenticationMethodInformation activeMethod : activeMethods) { loginHandler = loginHandlers.get(activeMethod.getAuthenticationMethod()); if (loginHandler != null && !loginHandler.supportsForceAuthentication()) { for (String handlerSupportedMethods : loginHandler.getSupportedAuthenticationMethods()) { LOG.debug( "Removing LoginHandler {}, it does not support forced re-authentication", loginHandler.getClass().getName()); loginHandlers.remove(handlerSupportedMethods); } } } LOG.debug( "Authentication handlers remaining after forced authentication requirement filtering: {}", loginHandlers); if (loginHandlers.isEmpty()) { LOG.info("Force authentication requested but no login handlers available to support it"); throw new ForceAuthenticationException(); } }
/** * Updates the user's Shibboleth session with authentication information. If no session exists a * new one will be created. * * @param loginContext current login context * @param authenticationSubject subject created from the authentication method * @param authenticationMethod the method used to authenticate the subject * @param authenticationInstant the time of authentication * @param httpRequest current HTTP request * @param httpResponse current HTTP response */ protected void updateUserSession( LoginContext loginContext, Subject authenticationSubject, String authenticationMethod, DateTime authenticationInstant, HttpServletRequest httpRequest, HttpServletResponse httpResponse) { Principal authenticationPrincipal = authenticationSubject.getPrincipals().iterator().next(); LOG.debug("Updating session information for principal {}", authenticationPrincipal.getName()); Session idpSession = (Session) httpRequest.getAttribute(Session.HTTP_SESSION_BINDING_ATTRIBUTE); if (idpSession == null) { LOG.debug("Creating shibboleth session for principal {}", authenticationPrincipal.getName()); idpSession = (Session) sessionManager.createSession(); loginContext.setSessionID(idpSession.getSessionID()); addSessionCookie(httpRequest, httpResponse, idpSession); } // Merge the information in the current session subject with the information from the // login handler subject idpSession.setSubject(mergeSubjects(idpSession.getSubject(), authenticationSubject)); // Check if an existing authentication method with no updated timestamp was used (i.e. SSO // occurred); // if not record the new information AuthenticationMethodInformation authnMethodInfo = idpSession.getAuthenticationMethods().get(authenticationMethod); if (authnMethodInfo == null || authenticationInstant != null) { LOG.debug( "Recording authentication and service information in Shibboleth session for principal: {}", authenticationPrincipal.getName()); LoginHandler loginHandler = handlerManager.getLoginHandlers().get(loginContext.getAttemptedAuthnMethod()); DateTime authnInstant = authenticationInstant; if (authnInstant == null) { authnInstant = new DateTime(); } authnMethodInfo = new AuthenticationMethodInformationImpl( idpSession.getSubject(), authenticationPrincipal, authenticationMethod, authnInstant, loginHandler.getAuthenticationDuration()); } loginContext.setAuthenticationMethodInformation(authnMethodInfo); idpSession .getAuthenticationMethods() .put(authnMethodInfo.getAuthenticationMethod(), authnMethodInfo); sessionManager.indexSession(idpSession, idpSession.getPrincipalName()); ServiceInformation serviceInfo = new ServiceInformationImpl( loginContext.getRelyingPartyId(), new DateTime(), authnMethodInfo); idpSession.getServicesInformation().put(serviceInfo.getEntityID(), serviceInfo); }
@Override protected void onPause() { super.onPause(); mProgress.dismiss(); mHandler.removeCallbacks(mStopRunnable); mHandler.removeCallbacks(mStartRunnable); if (mBluetoothAdapter != null) { mBluetoothAdapter.stopLeScan(this); // mBluetoothAdapter.disable(); } }
/* * Send an enable command to each sensor by writing a configuration * characteristic. This is specific to the SensorTag to keep power * low by disabling sensors you aren't using. */ private void enableNextSensor(BluetoothGatt gatt) { BluetoothGattCharacteristic characteristic; gatt2 = gatt; Log.wtf("mState is", mState + ""); switch (mState) { case 0: Log.wtf(TAG, "Renaming"); characteristic = gatt.getService(MAIN_SERVICE).getCharacteristic(ERROR_CHAR); gatt.readCharacteristic(characteristic); break; case 1: Log.d(TAG, "Enabling pressure cal"); characteristic = gatt.getService(MAIN_SERVICE).getCharacteristic(CONFIG_CHAR); characteristic.setValue(new byte[] {0x01}); gatt.writeCharacteristic(characteristic); break; default: mHandler.sendEmptyMessage(MSG_DISMISS); Log.i(TAG, "All Sensors Enabled"); return; } }
/** * Selects a login handler from a list of possible login handlers that could be used for the * request. * * @param possibleLoginHandlers list of possible login handlers that could be used for the request * @param loginContext current login context * @param idpSession current IdP session, if one exists * @return the login handler to use for this request * @throws AuthenticationException thrown if no handler can be used for this request */ protected LoginHandler selectLoginHandler( Map<String, LoginHandler> possibleLoginHandlers, LoginContext loginContext, Session idpSession) throws AuthenticationException { LOG.debug("Selecting appropriate login handler from filtered set {}", possibleLoginHandlers); LoginHandler loginHandler; if (idpSession != null && possibleLoginHandlers.containsKey(AuthnContext.PREVIOUS_SESSION_AUTHN_CTX)) { LOG.debug("Authenticating user with previous session LoginHandler"); loginHandler = possibleLoginHandlers.get(AuthnContext.PREVIOUS_SESSION_AUTHN_CTX); for (AuthenticationMethodInformation authnMethod : idpSession.getAuthenticationMethods().values()) { if (authnMethod.isExpired()) { continue; } if (loginContext.getRequestedAuthenticationMethods().isEmpty() || loginContext .getRequestedAuthenticationMethods() .contains(authnMethod.getAuthenticationMethod())) { LOG.debug( "Basing previous session authentication on active authentication method {}", authnMethod.getAuthenticationMethod()); loginContext.setAttemptedAuthnMethod(authnMethod.getAuthenticationMethod()); loginContext.setAuthenticationMethodInformation(authnMethod); return loginHandler; } } } if (loginContext.getDefaultAuthenticationMethod() != null && possibleLoginHandlers.containsKey(loginContext.getDefaultAuthenticationMethod())) { loginHandler = possibleLoginHandlers.get(loginContext.getDefaultAuthenticationMethod()); loginContext.setAttemptedAuthnMethod(loginContext.getDefaultAuthenticationMethod()); } else { Entry<String, LoginHandler> chosenLoginHandler = possibleLoginHandlers.entrySet().iterator().next(); loginContext.setAttemptedAuthnMethod(chosenLoginHandler.getKey()); loginHandler = chosenLoginHandler.getValue(); } LOG.debug( "Authenticating user with login handler of type {}", loginHandler.getClass().getName()); return loginHandler; }
private void setButtonEnable(final boolean b) { handler.post( new Runnable() { public void run() { login.setEnabled(b); } }); }
void setHint(final String text) { handler.post( new Runnable() { public void run() { FacebookLoginActivity.this.setTitle(text); facebook_info.setText(text); } }); }
public void newData(BluetoothGattCharacteristic characteristic) { if (DATA_CHAR.equals(characteristic.getUuid())) { // Log.wtf(TAG, "still running: " + stillRunning); if ((sicAct.stillRunning)) { mHandler.sendMessage(Message.obtain(null, MSG_HUMIDITY, characteristic)); } else { } } }
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { Log.d("checked", "is checked=" + isChecked); if (isChecked == true) { checkbox_sync_phonebook.setOnCheckedChangeListener(null); Message msg = handler.obtainMessage(EBABLE_CHECK); msg.getData().putBoolean("fromlogin", true); checkbox_sync_phonebook.setChecked(false); SyncAddressBookHelper.processSyncAddressBook( FacebookLoginActivity.this, isChecked, null, msg); } else { orm.EnableSyncPhonebook(false); } }
/** * Begins the authentication process. Determines if forced re-authentication is required or if an * existing, active, authentication method is sufficient. Also determines, when authentication is * required, which handler to use depending on whether passive authentication is required. * * @param loginContext current login context * @param httpRequest current HTTP request * @param httpResponse current HTTP response */ protected void startUserAuthentication( LoginContext loginContext, HttpServletRequest httpRequest, HttpServletResponse httpResponse) { LOG.debug("Beginning user authentication process."); try { Session idpSession = (Session) httpRequest.getAttribute(Session.HTTP_SESSION_BINDING_ATTRIBUTE); if (idpSession != null) { LOG.debug("Existing IdP session available for principal {}", idpSession.getPrincipalName()); } Map<String, LoginHandler> possibleLoginHandlers = determinePossibleLoginHandlers(idpSession, loginContext); // Filter out possible candidate login handlers by forced and passive authentication // requirements if (loginContext.isForceAuthRequired()) { filterByForceAuthentication(idpSession, loginContext, possibleLoginHandlers); } if (loginContext.isPassiveAuthRequired()) { filterByPassiveAuthentication(idpSession, loginContext, possibleLoginHandlers); } LoginHandler loginHandler = selectLoginHandler(possibleLoginHandlers, loginContext, idpSession); loginContext.setAuthenticationAttempted(); loginContext.setAuthenticationEngineURL(HttpHelper.getRequestUriWithoutContext(httpRequest)); // Send the request to the login handler HttpServletHelper.bindLoginContext( loginContext, storageService, getServletContext(), httpRequest, httpResponse); loginHandler.login(httpRequest, httpResponse); } catch (AuthenticationException e) { loginContext.setAuthenticationFailure(e); returnToProfileHandler(httpRequest, httpResponse); } }
/** * * generate password scheme either a) during initialization or b) after successful login * * @param hpwd * @param positions * @param password */ private static void generateScheme(BigInteger hpwd, Position[] positions, String password) { /* generate new random polynomial */ Polynomial newPoly = Polynomial.getRandomPolynomial(Constants.M - 1, hpwd); /* generate new R value and persist */ Generator.R = Generator.getRandomInteger(Generator.BIT_LENGTH); LoginHandler.getPreferences().put(Constants.PREF_R, Generator.R.toString()); /* reinitialize P and G functions with new R value */ initFunctions(password); /* generate new Instruction Table and write to file */ InstructionTable iTable = InstructionTable.generateInstructionTable(positions, newPoly); iTable.writeToFile(Constants.INSTRUCTION_TABLE_FILE_PATH); }
void launchLoginActivity() { try { setTitle(R.string.facebook_request_token_title); facebook_info.setText(R.string.facebook_request_token_title); isInProcess = true; token = loghelper.getDesktopApp().requestToken(); isInProcess = false; getToken = true; loginURL = loghelper.getDesktopApp().getLoginUrl(token); if (getToken == false) { Toast.makeText( FacebookLoginActivity.this, R.string.facebook_get_accesstoken_failed, Toast.LENGTH_LONG) .show(); FacebookLoginActivity.this.setTitle(R.string.sns_network_unavailable); facebook_info.setText(R.string.facebook_login_failed_message); } else { Log.d(TAG, "after get token=" + token); mHandler.obtainMessage(QUIT_THREAD).sendToTarget(); Intent intent = new Intent(FacebookLoginActivity.this, FacebookLoginWebViewActivity.class); intent.putExtra("facebook_loginURL", loginURL); startActivityForResult(intent, LOGIN_WEBVIEW); } } catch (FacebookException ne) { isInProcess = false; Log.d(TAG, "fail to request the token=" + ne.getMessage()); sendMessageToService(false); count--; if (count >= 0) { Log.d(TAG, "get token again"); Message msd = mHandler.obtainMessage(LOAD_LOGIN_PAGE); mHandler.sendMessageDelayed(msd, 5 * 1000); } } if (getToken == false) { handler.obtainMessage(NETWORK_UNAVAL).sendToTarget(); } Log.d(TAG, "continue"); if (getToken == true || count <= 0) { mHandler.obtainMessage(QUIT_THREAD).sendToTarget(); } }
/** * * Initializes the scheme * * @param password user given password * @return */ public static boolean initScheme(String password, long[] features) { Position[] positions = new Position[Constants.M]; Arrays.fill( positions, Position .BOTH); /* Initially both Alpha and Beta positions are filled with correct entries */ BigInteger hpwd = Generator.getHPWD(Constants.Q); /* generate a random hardened password */ initFunctions(password); HistoryData histData = new HistoryData(features); histData.persist(new File(Constants.HISTORY_FILE_PATH), hpwd); generateScheme(hpwd, positions, password); LoginHandler.getPreferences().put(Constants.PREF_INITIALIZED, "true"); return true; }
/** * ************************************* Handles a successful authentication by invoking the login * method {@link LoginHandler#loginSuccessful(DataElementList)}. * * @param rUserData The user data instance returned by the service */ protected void handleLoginSuccess(DataElementList rUserData) { String sSessionID = rUserData.getProperty(AuthenticatedService.SESSION_ID, null); if (sSessionID == null) { throw new IllegalArgumentException("No Session ID in user data"); } if (aPasswordField != null) { aPasswordField.setText(""); aFailureMessage.setVisible(false); aUserField = null; aPasswordField = null; } Cookies.setCookie(sSessionCookie, sSessionID); rLoginHandler.loginSuccessful(rUserData); }
@Test public void testLoginHandler() { LoginHandler lh = new LoginHandler(users); assertEquals(0, lh.getTimes()); assertSame(users, lh.getValidUsers()); }
/** * reset the scheme by clearing the initialization flag and R value */ public static void reset() { LoginHandler.getPreferences().put(Constants.PREF_INITIALIZED, "false"); LoginHandler.getPreferences().put(Constants.PREF_R, Generator.ZERO); }
/** * * Checks if scheme is initialized * * @return true is scheme is initialized */ public static boolean isSchemeInitialized() { return Boolean.valueOf(LoginHandler.getPreferences().get(Constants.PREF_INITIALIZED, "false")); }
void auth_login() { isInProcess = true; setButtonEnable(false); Log.d(TAG, "reconstrcut the facebook session"); final FacebookSession tmps; boolean persm = false; try { setHint(getString(R.string.verify_account_hint)); tmps = loghelper.getDesktopApp().AuthLoginNoSession(loghelper.getEmail(), loghelper.getPwd()); } catch (FacebookException e) { Log.e(TAG, "fail to get facebook session=" + e.getMessage()); handler.post( new Runnable() { public void run() { facebook_info.setText(R.string.facebook_fail_to_get_session); // FacebookLoginActivity.this.setResult(200); // sendMessageToService(false); // quitLooperAndFinish(); } }); mHandler.obtainMessage(QUIT_THREAD).sendToTarget(); isInProcess = false; setButtonEnable(true); return; } try { persm = tmps.AuthLogin( tmps.getSessionKey(), FacebookLoginHelper.SECRET_KEY, loghelper.getEmail(), loghelper.getPwd()); } catch (FacebookException e) { Log.e(TAG, "Fail to get permanant session, ignore this step."); } setHint(getString(R.string.verify_account_suc_hint)); // get login info in background // save into database String Sessionkey = tmps.getSessionKey(); String secretKey = tmps.getSecretKey(); long userId = tmps.getLogerInUserID(); loghelper.recordTmpSession(Sessionkey, secretKey, userId); SocialORM orm = SocialORM.instance(FacebookLoginActivity.this); if (true == persm) { recordPermSession(tmps, orm); } else { Log.d(TAG, "fail to get permnant session"); if (orm.isUsePermanentSeesion() == false) { Log.d(TAG, "fail to get permnant session, use tmp session"); recordPermSession(tmps, orm); } else { handler.post( new Runnable() { public void run() { Toast.makeText( FacebookLoginActivity.this, R.string.facebook_get_permanent_session_failed, Toast.LENGTH_LONG) .show(); } }); } } // reset the session and async in activity AccountManager.login(); handler.post( new Runnable() { public void run() { FacebookLoginActivity.this.setResult(100); sendMessageToService(true); } }); handler.post( new Runnable() { public void run() { quitLooperAndFinish(); } }); isInProcess = false; setButtonEnable(true); }
/** * ************************************* Handles login failures. There are two ways this method * can be invoked. This class first tries to connect to the server with user name and password set * to NULL to check for an existing authentication. If that call fails the internal container * builder reference will not be NULL and will be used to create the login components to query for * the user login. The builder reference will then be set to NULL. * * @param rCaught The exception that occurred */ protected void handleLoginFailure(Throwable rCaught) { aLoginButton.setEnabled(true); aFailureMessage.setVisible(true); rLoginHandler.loginFailed((Exception) rCaught); }
@Test public void testResetHandler() { LoginHandler lh = new LoginHandler(users); lh.resetHandler(); assertEquals(0, lh.getTimes()); }
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); View decorView = getWindow().getDecorView(); int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY; decorView.setSystemUiVisibility(uiOptions); setContentView(R.layout.activity_sic); setProgressBarIndeterminate(true); SICRunning = true; wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE); wifiManager.setWifiEnabled(false); instance = this; getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); xBar = (SeekBar) findViewById(R.id.xBar); yBar = (SeekBar) findViewById(R.id.yBar); zBar = (SeekBar) findViewById(R.id.zBar); dName = (TextView) findViewById(R.id.label); firmwareIV = (ImageView) findViewById(R.id.firmware); bluetoothIV = (ImageView) findViewById(R.id.bluetooth); tvFirmware = (TextView) findViewById(R.id.tvFirmRev); tvBluetooth = (TextView) findViewById(R.id.tvBlueRev); battLevel = (TextView) findViewById(R.id.batteryLevelTV); attachOnClickListeners(); leManager = new BLEManager(this); BluetoothManager manager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE); mBluetoothAdapter = manager.getAdapter(); mDevices = new ArrayList<>(); mProgress = new ProgressDialog(this); mProgress.setIndeterminate(true); mProgress.setCancelable(false); p1graph = new GraphView(this); p2graph = new GraphView(this); vgraph = new GraphView(this); p1Graph(); Intent startIntent = getIntent(); deviceName = startIntent.getExtras().getString("DEVICE"); dName.setText(deviceName); int mode = startIntent.getExtras().getInt("MODE"); if (mode == 1) { logging = false; } else if (mode == 2) { logging = true; } label = (TextView) findViewById(R.id.label); if (logging) { label.setText("Research and Development"); } else { label.setText(deviceName); } stillRunning = true; if (mHandler == null) mHandler = new LoginHandler(this); else { mHandler.setTarget(this); } Calendar now = Calendar.getInstance(); filer = now.get(Calendar.DAY_OF_MONTH) + "-" + (now.get(Calendar.MONTH) + 1) + "-" + now.get(Calendar.YEAR) + "_" + now.get(Calendar.HOUR_OF_DAY) + "-" + now.get(Calendar.MINUTE) + "-" + now.get(Calendar.SECOND) + "-" + now.get(Calendar.MILLISECOND); mProgress = ProgressDialog.show(this, "Scanning...", "Please Wait", true); // fillDB(); usl = (TextView) findViewById(R.id.tvUSL); lsl = (TextView) findViewById(R.id.tvLSL); vref = (TextView) findViewById(R.id.tvRef); if (!isScanRunning) { runOnUiThread(mStartRunnable); } }
@Test(expected = LoginAttemptsExceededException.class) public void testAuthenticate3Times() throws Exception { LoginHandler lh = new LoginHandler(users); assertFalse(lh.authenticate("username", "psword")); // ID PW 틀릴때 assertEquals(1, lh.getTimes()); assertFalse(lh.authenticate("username", "password")); // ID PW 틀릴때 assertEquals(2, lh.getTimes()); assertFalse(lh.authenticate("admin", "p ")); // ID PW 틀릴때 assertEquals(3, lh.getTimes()); assertFalse(lh.authenticate("admin", "p ")); // ID PW 틀릴때 assertEquals(4, lh.getTimes()); assertFalse(lh.authenticate("admin", "p ")); // ID PW 틀릴때 assertEquals(5, lh.getTimes()); }
@Test public void testAuthenticateTTCase() throws Exception { LoginHandler lh = new LoginHandler(users); assertTrue(lh.authenticate("admin", "password")); // ID PW 틀릴때 assertEquals(0, lh.getTimes()); }
@Test public void testAuthenticateFTCase() throws Exception { LoginHandler lh = new LoginHandler(users); assertFalse(lh.authenticate("username", "password")); // ID PW 틀릴때 assertEquals(1, lh.getTimes()); }