@Test
  public void testCRUDAccount() {
    // Create
    Account account = new Account();
    account.setGivenName("Anthony");
    account.setSurname("Wolski");
    account.setEmail("*****@*****.**");
    account.setPassword("password");
    account.setUsername("awolski");
    accountService.createAccount(account);
    assertEquals(new Long(0), account.getVersion());

    // Read
    Account found = accountService.getAccount(account.getId());
    assertEquals("Anthony", found.getGivenName());
    assertEquals("Wolski", found.getSurname());
    assertEquals("*****@*****.**", found.getEmail());
    assertEquals("password", found.getPassword());
    assertEquals("awolski", found.getUsername());
    assertEquals(new Long(0), account.getVersion());

    // Update
    account.setMiddleName("Keith");
    accountService.saveAccount(account);
    account = accountService.getAccount(account.getId());
    assertEquals(new Long(1), account.getVersion());

    // Delete
    String accountId = account.getId();
    accountService.deleteAccountById(accountId);
    account = accountService.getAccount(accountId);
    assertNull(account);
  }
  public void updateProfile(String key, Account pAccount)
      throws SQLException, ConnectionException, MissingDataException, NullAccountException,
          ProfileException, PasswordException, EmailException {
    try (Connection connect = DBConnection.getConnection()) {
      pAccount = testAccount(pAccount);

      String sql =
          "UPDATE account"
              + "set name = '"
              + Utility.Replace(testProfileData(pAccount.getName()))
              + "', surname = '"
              + Utility.Replace(testProfileData(pAccount.getSurname()))
              + "', password = '******', secondaryEmail = '"
              + testEmail(pAccount.getSecondaryEmail())
              + "WHERE email = '"
              + key
              + "'";

      String sql2 = "UPDATE " + pAccount.getTypeAccount();

      if (pAccount instanceof PhdStudent) {
        sql2 +=
            " set telephone = '"
                + testProfileData(((PhdStudent) pAccount).getTelephone())
                + "', link =  '"
                + testProfileData(((PhdStudent) pAccount).getLink())
                + "', deparment = '"
                + testProfileData(((PhdStudent) pAccount).getDepartment())
                + "', researchInterest = '"
                + testProfileData(((PhdStudent) pAccount).getResearchInterest())
                + "' WHERE fkAccount = '"
                + testProfileData(((PhdStudent) pAccount).getSecondaryEmail());
      }

      if (pAccount instanceof Professor) {
        sql2 +=
            " set link = '"
                + ((Professor) pAccount).getLink()
                + "', set department = '"
                + ((Professor) pAccount).getDepartment()
                + "' WHERE fkAccount = '"
                + ((Professor) pAccount).getSecondaryEmail()
                + "'";
      }

      if (pAccount.getTypeAccount().equals("basic")) // aggiorna solo info base
      Utility.executeOperation(connect, sql);
      else {
        Utility.executeOperation(connect, sql);
        Utility.executeOperation(connect, sql2);
      }

      connect.commit();
    }
  }
예제 #3
0
 private User buildUserForAuthentication(Account account, List<GrantedAuthority> authorities) {
   return new User(
       account.getUsername(),
       account.getPassword(),
       account.isEnabled(),
       account.isAccountNonExpired(),
       account.isCredentialsNonExpired(),
       account.isAccountNonLocked(),
       authorities);
 }
 @Transactional
 public void createAccount(Account user) throws UsernameAlreadyInUseException {
   try {
     jdbcTemplate.update(
         "insert into Account (firstName, lastName, username, password) values (?, ?, ?, ?)",
         user.getFirstName(),
         user.getLastName(),
         user.getUsername(),
         passwordEncoder.encodePassword(user.getPassword(), null));
   } catch (DuplicateKeyException e) {
     throw new UsernameAlreadyInUseException(user.getUsername());
   }
 }
  @Test
  public void shouldReturnUserDetails() {
    // arrange
    Account demoUser = new Account("*****@*****.**", "demo", "ROLE_USER");
    when(accountRepositoryMock.findOneByEmail("*****@*****.**")).thenReturn(demoUser);

    // act
    UserDetails userDetails = accountService.loadUserByUsername("*****@*****.**");

    // assert
    assertThat(demoUser.getEmail()).isEqualTo(userDetails.getUsername());
    assertThat(demoUser.getPassword()).isEqualTo(userDetails.getPassword());
    assertThat(hasAuthority(userDetails, demoUser.getRole())).isTrue();
  }
예제 #6
0
  /**
   * Try to login a User by its user name and its password.
   *
   * @param username Name of the User
   * @param password Password of the user
   * @param session The Session object used by the gwt session management.
   * @return The User object which is connected to the user name and password combination
   * @throws LoginException If there is no account with the user name and password combination.
   */
  public User login(final String username, final String password, final HttpSession session)
      throws LoginException {
    for (final Account account : this.manager.getAccounts()) {
      if (account.getUser().getName().equals(username) && account.getPassword().equals(password)) {

        if (account.getUser().getPerson() != null && !account.getUser().getPerson().isDeleted()) {
          this.sessionManager.newSession(account.getUser(), session);
          return account.getUser();
        } else {
          throw new LoginException(
              "Account ist ungültig! Die Person zum Account existiert nicht mehr!");
        }
      }
    }

    throw new LoginException("Kombination von Name und Passwort existiert nicht!");
  }
예제 #7
0
 public void putAccount(Account account) {
   Editor editor = mPreference.edit();
   editor.putString(USERNAME_KEY, account.getUsername());
   editor.putString(PASSWORD_KEY, account.getPassword());
   editor.commit();
 }
예제 #8
0
 private User createUser(Account account) {
   return new User(
       account.getEmail(), account.getPassword(), Collections.singleton(createAuthority(account)));
 }
예제 #9
0
 @Transactional
 public Account save(Account account) {
   account.setPassword(passwordEncoder.encode(account.getPassword()));
   accountRepository.save(account);
   return account;
 }
예제 #10
0
  /**
   * {@inheritDoc}
   *
   * @see ch.entwine.weblounge.common.scheduler.JobWorker#execute(java.lang.String,
   *     java.util.Dictionary)
   */
  public void execute(String name, Dictionary<String, Serializable> ctx) throws JobException {

    Site site = (Site) ctx.get(Site.class.getName());

    // Make sure the site is ready to accept content
    if (site.getContentRepository().isReadOnly()) {
      logger.warn("Unable to publish e-mail messages to site '{}': repository is read only", site);
      return;
    }

    WritableContentRepository repository = (WritableContentRepository) site.getContentRepository();

    // Extract the configuration from the job properties
    String provider = (String) ctx.get(OPT_PROVIDER);
    Account account = null;
    try {
      if (StringUtils.isBlank(provider)) {
        provider = DEFAULT_PROVIDER;
      }
      account = new Account(ctx);
    } catch (IllegalArgumentException e) {
      throw new JobException(this, e);
    }

    // Connect to the server
    Properties sessionProperties = new Properties();
    Session session = Session.getDefaultInstance(sessionProperties, null);
    Store store = null;
    Folder inbox = null;

    try {

      // Connect to the server
      try {
        store = session.getStore(provider);
        store.connect(account.getHost(), account.getLogin(), account.getPassword());
      } catch (NoSuchProviderException e) {
        throw new JobException(
            this, "Unable to connect using unknown e-mail provider '" + provider + "'", e);
      } catch (MessagingException e) {
        throw new JobException(this, "Error connecting to " + provider + " account " + account, e);
      }

      // Open the account's inbox
      try {
        inbox = store.getFolder(INBOX);
        if (inbox == null) throw new JobException(this, "No inbox found at " + account);
        inbox.open(Folder.READ_WRITE);
      } catch (MessagingException e) {
        throw new JobException(this, "Error connecting to inbox at " + account, e);
      }

      // Get the messages from the server
      try {
        for (Message message : inbox.getMessages()) {
          if (!message.isSet(Flag.SEEN)) {
            try {
              Page page = aggregate(message, site);
              message.setFlag(Flag.DELETED, true);
              repository.put(page, true);
              logger.info("E-Mail message published at {}", page.getURI());
            } catch (Exception e) {
              logger.info("E-Mail message discarded: {}", e.getMessage());
              message.setFlag(Flag.SEEN, true);
              // TODO: Reply to sender if the "from" field exists
            }
          }
        }
      } catch (MessagingException e) {
        throw new JobException(this, "Error loading e-mail messages from inbox", e);
      }

      // Close the connection
      // but don't remove the messages from the server
    } finally {
      if (inbox != null) {
        try {
          inbox.close(true);
        } catch (MessagingException e) {
          throw new JobException(this, "Error closing inbox", e);
        }
      }
      if (store != null) {
        try {
          store.close();
        } catch (MessagingException e) {
          throw new JobException(this, "Error closing connection to e-mail server", e);
        }
      }
    }
  }
예제 #11
0
 @Transactional
 public Account save(Account account) {
   account.setPassword(passwordEncoder.encode(account.getPassword()));
   entityManager.persist(account);
   return account;
 }
  public static void onUpgrade(Context context, SQLiteDatabase db, int oldVersion, int newVersion) {
    // Update database to add the Paid Account flag. This was introduced in
    // DB version 3.
    if (oldVersion <= DatabaseVersionNumber.VERSION_1_0_0) {
      db.execSQL(QUERY_ADD_PAID_ACCOUNT_COLUM);
    }

    // Update database to create account content provider
    if (oldVersion <= DatabaseVersionNumber.VERSION_1_1_0) {
      // Rename old table
      db.execSQL(QUERY_RENAME_TABLE_OLD);
      db.execSQL(QUERY_TABLE_CREATE);
      db.execSQL(REPLICATE_ACCOUNT);
      db.execSQL(QUERY_DROP_TABLE_OLD);
    }

    // Migrate all accounts to Account Manager
    if (oldVersion < DatabaseVersionNumber.VERSION_1_5_0) {
      //
      List<Account> accounts = AccountProvider.retrieveAccounts(db);
      android.accounts.Account newAccount;
      String accountName;
      AccountManager mAccountManager = AccountManager.get(context);
      SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
      SyncContentManager syncManager = SyncContentManager.getInstance(context);
      for (Account account : accounts) {
        // Check Account Name
        accountName =
            AlfrescoAccountManager.getInstance(context)
                .createUniqueAccountName(account.getUsername());
        newAccount = new android.accounts.Account(accountName, AlfrescoAccount.ACCOUNT_TYPE);
        Bundle b = new Bundle();
        // Very important !
        // We keep the same Account Id from previous version.
        // Used by the SyncService
        b.putString(AlfrescoAccount.ACCOUNT_ID, Long.toString(account.getId()));
        BundleUtils.addIfNotEmpty(b, AlfrescoAccount.ACCOUNT_NAME, account.getDescription());
        BundleUtils.addIfNotEmpty(b, AlfrescoAccount.ACCOUNT_URL, account.getUrl());
        BundleUtils.addIfNotEmpty(b, AlfrescoAccount.ACCOUNT_USERNAME, account.getUsername());
        BundleUtils.addIfNotEmpty(
            b, AlfrescoAccount.ACCOUNT_REPOSITORY_ID, account.getRepositoryId());
        BundleUtils.addIfNotEmpty(
            b, AlfrescoAccount.ACCOUNT_REPOSITORY_TYPE_ID, String.valueOf(account.getTypeId()));
        BundleUtils.addIfNotEmpty(
            b,
            AlfrescoAccount.ACCOUNT_IS_PAID_ACCOUNT,
            Boolean.toString(account.getIsPaidAccount()));
        BundleUtils.addIfNotEmpty(b, AlfrescoAccount.ACCOUNT_ACTIVATION, account.getActivation());
        BundleUtils.addIfNotEmpty(
            b, AlfrescoAccount.ACCOUNT_ACCESS_TOKEN, account.getAccessToken());
        BundleUtils.addIfNotEmpty(
            b, AlfrescoAccount.ACCOUNT_REFRESH_TOKEN, account.getRefreshToken());

        // Time to create.
        if (mAccountManager.addAccountExplicitly(newAccount, account.getPassword(), b)) {
          // Let's define if sync automatically regarding previous
          // settings
          syncManager.setActivateSync(
              account.getId(), sharedPref.getBoolean(SYNCHRO_PREFIX + account.getId(), false));
          sharedPref.edit().remove(SYNCHRO_PREFIX + account.getId()).apply();
        }

        Log.i(
            "Migration",
            "Account " + account.getDescription() + "[" + account.getId() + "] has been migrated");
      }
      // Delete old table
      db.execSQL(QUERY_DROP_TABLE);
    }
  }