Пример #1
0
 @Before
 static void setConnectedUser() {
   if (Security.isConnected()) {
     User user = User.find("byEmail", Security.connected()).first();
     renderArgs.put("user", user.fullname);
   }
 }
Пример #2
0
 @Before
 static void setConnectedUser() {
   if (Security.isConnected()) {
     User user = User.find("byUsername", Security.connected()).first();
     if (!user.isAdmin) {
       flash.error(Messages.get("UserIsNotAuthorized"));
       Application.index();
     }
   }
 }
Пример #3
0
  @Before
  static void setConnectedUser() {
    if (Security.isConnected()) {
      User user = User.find("byEmail", Security.connected()).first();

      if (user == null) {
        user = new User("*****@*****.**", "1234", "Andreas");
        user.save();
      }

      renderArgs.put("user", user.fullname);
    }
  }
Пример #4
0
  /**
   * Returns a Set of Strings containing the names of all available algorithms or types for the
   * specified Java cryptographic service (e.g., Signature, MessageDigest, Cipher, Mac, KeyStore).
   * Returns an empty Set if there is no provider that supports the specified service or if
   * serviceName is null. For a complete list of Java cryptographic services, please see the <a
   * href="../../../guide/security/CryptoSpec.html">Java Cryptography Architecture API Specification
   * &amp; Reference</a>. Note: the returned set is immutable.
   *
   * @param serviceName the name of the Java cryptographic service (e.g., Signature, MessageDigest,
   *     Cipher, Mac, KeyStore). Note: this parameter is case-insensitive.
   * @return a Set of Strings containing the names of all available algorithms or types for the
   *     specified Java cryptographic service or an empty set if no provider supports the specified
   *     service.
   * @since 1.4
   */
  public static Set<String> getAlgorithms(String serviceName) {

    if ((serviceName == null) || (serviceName.length() == 0) || (serviceName.endsWith("."))) {
      return Collections.EMPTY_SET;
    }

    HashSet result = new HashSet();
    Provider[] providers = Security.getProviders();

    for (int i = 0; i < providers.length; i++) {
      // Check the keys for each provider.
      for (Enumeration e = providers[i].keys(); e.hasMoreElements(); ) {
        String currentKey = ((String) e.nextElement()).toUpperCase();
        if (currentKey.startsWith(serviceName.toUpperCase())) {
          // We should skip the currentKey if it contains a
          // whitespace. The reason is: such an entry in the
          // provider property contains attributes for the
          // implementation of an algorithm. We are only interested
          // in entries which lead to the implementation
          // classes.
          if (currentKey.indexOf(" ") < 0) {
            result.add(currentKey.substring(serviceName.length() + 1));
          }
        }
      }
    }
    return Collections.unmodifiableSet(result);
  }
Пример #5
0
 public static void save(Long id, String title, String content, String tags) {
   Post post;
   if (id == null) {
     // Create post
     User author = User.find("byEmail", Security.connected()).first();
     post = new Post(author, title, content);
   } else {
     // Retrieve post
     post = Post.findById(id);
     // Edit
     post.title = title;
     post.content = content;
     post.tags.clear();
   }
   // Set tags list
   for (String tag : tags.split("\\s+")) {
     if (tag.trim().length() > 0) {
       post.tags.add(Tag.findOrCreateByName(tag));
     }
   }
   // Validate
   validation.valid(post);
   if (validation.hasErrors()) {
     render("@form", post);
   }
   // Save
   post.save();
   index();
 }
Пример #6
0
  public static void editerBateau(String nomBateau, String couleurVoile, String couleurcoque) {
    if (Security.isConnected()) {
      Utilisateur user = Utilisateur.find("byEmail", Security.connected()).first();
      renderArgs.put("user", user);
    }

    Utilisateur user = Utilisateur.find("byEmail", Security.connected()).first();

    if (validation.hasErrors()) {
      // add http parameters to the flash scope
      params.flash();
    } else {
      user.couleurcoque = couleurcoque;
      user.couleurVoile = couleurVoile;
      user.nomBateau = nomBateau;
      user.save();
    }
    render("Admin/index.html");
  }
Пример #7
0
  public static void sauvegardermoncompte(String pseudo, String password) {

    if (Security.isConnected()) {
      Utilisateur user = Utilisateur.find("byEmail", Security.connected()).first();
      renderArgs.put("user", user);
    }

    Utilisateur user = Utilisateur.find("byEmail", Security.connected()).first();

    if (validation.hasErrors()) {
      // add http parameters to the flash scope
      params.flash();
    } else {
      user.pseudo = pseudo;
      user.password = password;
      user.save();
    }
    render("Admin/index.html");
  }
Пример #8
0
  @Before
  static void header() {
    Journal journal = Journal.all().first();
    renderArgs.put("journal", journal);
    renderArgs.put("journalName", journal.name);
    renderArgs.put("journalDesc", journal.description);

    User currentUser = User.find("byEmail", Security.connected()).<User>first();
    renderArgs.put("currentUser", currentUser);
  }
Пример #9
0
  /**
   * Returns an array containing all installed providers that satisfy the specified* selection
   * criteria, or null if no such providers have been installed. The returned providers are ordered
   * according to their <a href= "#insertProviderAt(java.security.Provider, int)">preference
   * order</a>.
   *
   * <p>The selection criteria are represented by a map. Each map entry represents a selection
   * criterion. A provider is selected iff it satisfies all selection criteria. The key for any
   * entry in such a map must be in one of the following two formats:
   *
   * <ul>
   *   <li><i>&lt;crypto_service>.&lt;algorithm_or_type></i>
   *       <p>The cryptographic service name must not contain any dots.
   *       <p>The value associated with the key must be an empty string.
   *       <p>A provider satisfies this selection criterion iff the provider implements the
   *       specified algorithm or type for the specified cryptographic service.
   *   <li><i>&lt;crypto_service>.&lt;algorithm_or_type> &lt;attribute_name></i>
   *       <p>The cryptographic service name must not contain any dots. There must be one or more
   *       space charaters between the <i>&lt;algorithm_or_type></i> and the
   *       <i>&lt;attribute_name></i>.
   *       <p>The value associated with the key must be a non-empty string. A provider satisfies
   *       this selection criterion iff the provider implements the specified algorithm or type for
   *       the specified cryptographic service and its implementation meets the constraint expressed
   *       by the specified attribute name/value pair.
   * </ul>
   *
   * <p>See Appendix A in the <a href= "../../../guide/security/CryptoSpec.html#AppA"> Java
   * Cryptogaphy Architecture API Specification &amp; Reference </a> for information about standard
   * cryptographic service names, standard algorithm names and standard attribute names.
   *
   * @param filter the criteria for selecting providers. The filter is case-insensitive.
   * @return all the installed providers that satisfy the selection criteria, or null if no such
   *     providers have been installed.
   * @throws InvalidParameterException if the filter is not in the required format
   * @throws NullPointerException if filter is null
   * @see #getProviders(java.lang.String)
   */
  public static Provider[] getProviders(Map<String, String> filter) {
    // Get all installed providers first.
    // Then only return those providers who satisfy the selection criteria.
    Provider[] allProviders = Security.getProviders();
    Set keySet = filter.keySet();
    LinkedHashSet candidates = new LinkedHashSet(5);

    // Returns all installed providers
    // if the selection criteria is null.
    if ((keySet == null) || (allProviders == null)) {
      return allProviders;
    }

    boolean firstSearch = true;

    // For each selection criterion, remove providers
    // which don't satisfy the criterion from the candidate set.
    for (Iterator ite = keySet.iterator(); ite.hasNext(); ) {
      String key = (String) ite.next();
      String value = (String) filter.get(key);

      LinkedHashSet newCandidates = getAllQualifyingCandidates(key, value, allProviders);
      if (firstSearch) {
        candidates = newCandidates;
        firstSearch = false;
      }

      if ((newCandidates != null) && !newCandidates.isEmpty()) {
        // For each provider in the candidates set, if it
        // isn't in the newCandidate set, we should remove
        // it from the candidate set.
        for (Iterator cansIte = candidates.iterator(); cansIte.hasNext(); ) {
          Provider prov = (Provider) cansIte.next();
          if (!newCandidates.contains(prov)) {
            cansIte.remove();
          }
        }
      } else {
        candidates = null;
        break;
      }
    }

    if ((candidates == null) || (candidates.isEmpty())) return null;

    Object[] candidatesArray = candidates.toArray();
    Provider[] result = new Provider[candidatesArray.length];

    for (int i = 0; i < result.length; i++) {
      result[i] = (Provider) candidatesArray[i];
    }

    return result;
  }
Пример #10
0
 /** Initializes Java cryptography provider */
 private void initProvider() throws DigiDocException {
   try {
     m_secProvider =
         (Provider)
             Class.forName(ConfigManager.instance().getProperty("DIGIDOC_SECURITY_PROVIDER"))
                 .newInstance();
     Security.addProvider(m_secProvider);
   } catch (Exception ex) {
     m_secProvider = null;
     DigiDocException.handleException(ex, DigiDocException.ERR_CRYPTO_PROVIDER);
   }
 }
Пример #11
0
  public static void testDefault(PKCS11Test test) throws Exception {
    // run test for default configured PKCS11 providers (if any)

    if ("true".equals(System.getProperty("NO_DEFAULT"))) {
      return;
    }

    Provider[] providers = Security.getProviders();
    for (int i = 0; i < providers.length; i++) {
      Provider p = providers[i];
      if (p.getName().startsWith("SunPKCS11-")) {
        test.premain(p);
      }
    }
  }
Пример #12
0
 void initCipher() {
   try {
     b64Decoder = new BASE64Decoder();
     b64Encoder = new BASE64Encoder();
     Provider sunJce = new com.sun.crypto.provider.SunJCE();
     Security.addProvider(sunJce);
     byte[] raw = b64Decoder.decodeBuffer(key);
     SecretKeySpec skeySpec = new SecretKeySpec(raw, "Blowfish");
     deCipher = Cipher.getInstance("Blowfish");
     deCipher.init(Cipher.DECRYPT_MODE, skeySpec);
     enCipher = Cipher.getInstance("Blowfish");
     enCipher.init(Cipher.ENCRYPT_MODE, skeySpec);
   } catch (Exception ex) {
     textPane.setText("Unable to create the cipher");
   }
 }
Пример #13
0
 public static void uploadFile(String filename, File file) {
   User user = User.find("byEmail", Security.connected()).first();
   Upload uploadObj = new Upload();
   uploadObj.UploadFile(filename, user, file);
   Admin.upload();
 }
Пример #14
0
 public static void index() {
   String user = Security.connected();
   List<Post> posts = Post.find("author.email", user).fetch();
   render(posts);
 }
Пример #15
0
  /**
   * Common method for notes retrieval. It accepts a query to perform and returns matching records.
   */
  public List<Note> getNotes(String whereCondition, boolean order) {
    List<Note> noteList = new ArrayList<>();

    String sort_column, sort_order = "";

    // Getting sorting criteria from preferences. Reminder screen forces sorting.
    if (Navigation.checkNavigation(Navigation.REMINDERS)) {
      sort_column = KEY_REMINDER;
    } else {
      sort_column = prefs.getString(Constants.PREF_SORTING_COLUMN, KEY_TITLE);
    }
    if (order) {
      sort_order =
          KEY_TITLE.equals(sort_column) || KEY_REMINDER.equals(sort_column) ? " ASC " : " DESC ";
    }

    // In case of title sorting criteria it must be handled empty title by concatenating content
    sort_column = KEY_TITLE.equals(sort_column) ? KEY_TITLE + "||" + KEY_CONTENT : sort_column;

    // In case of reminder sorting criteria the empty reminder notes must be moved on bottom of
    // results
    sort_column =
        KEY_REMINDER.equals(sort_column)
            ? "IFNULL(" + KEY_REMINDER + ", " + "" + Constants.TIMESTAMP_UNIX_EPOCH + ")"
            : sort_column;

    // Generic query to be specialized with conditions passed as parameter
    String query =
        "SELECT "
            + KEY_CREATION
            + ","
            + KEY_LAST_MODIFICATION
            + ","
            + KEY_TITLE
            + ","
            + KEY_CONTENT
            + ","
            + KEY_ARCHIVED
            + ","
            + KEY_TRASHED
            + ","
            + KEY_REMINDER
            + ","
            + KEY_REMINDER_FIRED
            + ","
            + KEY_RECURRENCE_RULE
            + ","
            + KEY_LATITUDE
            + ","
            + KEY_LONGITUDE
            + ","
            + KEY_ADDRESS
            + ","
            + KEY_LOCKED
            + ","
            + KEY_CHECKLIST
            + ","
            + KEY_CATEGORY
            + ","
            + KEY_CATEGORY_NAME
            + ","
            + KEY_CATEGORY_DESCRIPTION
            + ","
            + KEY_CATEGORY_COLOR
            + " FROM "
            + TABLE_NOTES
            + " LEFT JOIN "
            + TABLE_CATEGORY
            + " USING( "
            + KEY_CATEGORY
            + ") "
            + whereCondition
            + (order ? " ORDER BY " + sort_column + sort_order : "");

    Log.v(Constants.TAG, "Query: " + query);

    Cursor cursor = null;
    try {
      cursor = getDatabase().rawQuery(query, null);

      // Looping through all rows and adding to list
      if (cursor.moveToFirst()) {
        do {
          int i = 0;
          Note note = new Note();
          note.setCreation(cursor.getLong(i++));
          note.setLastModification(cursor.getLong(i++));
          note.setTitle(cursor.getString(i++));
          note.setContent(cursor.getString(i++));
          note.setArchived("1".equals(cursor.getString(i++)));
          note.setTrashed("1".equals(cursor.getString(i++)));
          note.setAlarm(cursor.getString(i++));
          note.setReminderFired(cursor.getInt(i++));
          note.setRecurrenceRule(cursor.getString(i++));
          note.setLatitude(cursor.getString(i++));
          note.setLongitude(cursor.getString(i++));
          note.setAddress(cursor.getString(i++));
          note.setLocked("1".equals(cursor.getString(i++)));
          note.setChecklist("1".equals(cursor.getString(i++)));

          // Eventual decryption of content
          if (note.isLocked()) {
            note.setContent(
                Security.decrypt(note.getContent(), prefs.getString(Constants.PREF_PASSWORD, "")));
          }

          // Set category
          long categoryId = cursor.getLong(i++);
          if (categoryId != 0) {
            Category category =
                new Category(
                    categoryId,
                    cursor.getString(i++),
                    cursor.getString(i++),
                    cursor.getString(i++));
            note.setCategory(category);
          }

          // Add eventual attachments uri
          note.setAttachmentsList(getNoteAttachments(note));

          // Adding note to list
          noteList.add(note);

        } while (cursor.moveToNext());
      }

    } finally {
      if (cursor != null) cursor.close();
    }

    Log.v(Constants.TAG, "Query: Retrieval finished!");
    return noteList;
  }
Пример #16
0
  // Inserting or updating single note
  public Note updateNote(Note note, boolean updateLastModification) {
    SQLiteDatabase db = getDatabase(true);

    String content;
    if (note.isLocked()) {
      content = Security.encrypt(note.getContent(), prefs.getString(Constants.PREF_PASSWORD, ""));
    } else {
      content = note.getContent();
    }

    // To ensure note and attachments insertions are atomical and boost performances transaction are
    // used
    db.beginTransaction();

    ContentValues values = new ContentValues();
    values.put(KEY_TITLE, note.getTitle());
    values.put(KEY_CONTENT, content);
    values.put(
        KEY_CREATION,
        note.getCreation() != null ? note.getCreation() : Calendar.getInstance().getTimeInMillis());
    values.put(
        KEY_LAST_MODIFICATION,
        updateLastModification
            ? Calendar.getInstance().getTimeInMillis()
            : (note.getLastModification() != null
                ? note.getLastModification()
                : Calendar.getInstance().getTimeInMillis()));
    values.put(KEY_ARCHIVED, note.isArchived());
    values.put(KEY_TRASHED, note.isTrashed());
    values.put(KEY_REMINDER, note.getAlarm());
    values.put(KEY_REMINDER_FIRED, note.isReminderFired());
    values.put(KEY_RECURRENCE_RULE, note.getRecurrenceRule());
    values.put(KEY_LATITUDE, note.getLatitude());
    values.put(KEY_LONGITUDE, note.getLongitude());
    values.put(KEY_ADDRESS, note.getAddress());
    values.put(KEY_CATEGORY, note.getCategory() != null ? note.getCategory().getId() : null);
    boolean locked = note.isLocked() != null ? note.isLocked() : false;
    values.put(KEY_LOCKED, locked);
    boolean checklist = note.isChecklist() != null ? note.isChecklist() : false;
    values.put(KEY_CHECKLIST, checklist);

    db.insertWithOnConflict(TABLE_NOTES, KEY_ID, values, SQLiteDatabase.CONFLICT_REPLACE);
    Log.d(Constants.TAG, "Updated note titled '" + note.getTitle() + "'");

    // Updating attachments
    List<Attachment> deletedAttachments = note.getAttachmentsListOld();
    for (Attachment attachment : note.getAttachmentsList()) {
      updateAttachment(
          note.get_id() != null ? note.get_id() : values.getAsLong(KEY_CREATION), attachment, db);
      deletedAttachments.remove(attachment);
    }
    // Remove from database deleted attachments
    for (Attachment attachmentDeleted : deletedAttachments) {
      db.delete(
          TABLE_ATTACHMENTS,
          KEY_ATTACHMENT_ID + " = ?",
          new String[] {String.valueOf(attachmentDeleted.getId())});
    }

    db.setTransactionSuccessful();
    db.endTransaction();

    // Fill the note with correct data before returning it
    note.setCreation(
        note.getCreation() != null ? note.getCreation() : values.getAsLong(KEY_CREATION));
    note.setLastModification(values.getAsLong(KEY_LAST_MODIFICATION));

    return note;
  }