Search in sources :

Example 16 with ApiMethod

use of com.google.api.server.spi.config.ApiMethod in project cryptonomica by Cryptonomica.

the class NewUserRegistrationAPI method registerNewUser.

@ApiMethod(name = "registerNewUser", path = "registerNewUser", httpMethod = ApiMethod.HttpMethod.POST)
@SuppressWarnings("unused")
public // creates a new cryptonomica user and saves him/her to database
NewUserRegistrationReturn registerNewUser(final HttpServletRequest httpServletRequest, final User googleUser, final NewUserRegistrationForm newUserRegistrationForm) throws Exception {
    /* --- Ensure 1) user login, 2) not already registered:: */
    UserTools.ensureNewCryptonomicaUser(googleUser);
    /* --- Check form:*/
    if (newUserRegistrationForm.getArmoredPublicPGPkeyBlock() == null || newUserRegistrationForm.getArmoredPublicPGPkeyBlock().length() == 0) {
        throw new Exception("ASCII-armored PGP public key can not be empty");
    // } else if (newUserRegistrationForm.getUserInfo() == null) {
    // throw new Exception("Info can not be empty");
    } else if (newUserRegistrationForm.getBirthday() == null) {
        throw new Exception("Birthdate can not be empty");
    }
    /* --- user BirthDate */
    Date userBirthDate = newUserRegistrationForm.getBirthday();
    // TODO: add check
    /* --- create PGPPublicKey from armored PGP key block: */
    String userId = googleUser.getUserId();
    String armoredPublicPGPkeyBlock = newUserRegistrationForm.getArmoredPublicPGPkeyBlock();
    LOG.warning("[armoredPublicPGPkeyBlock]:");
    LOG.warning(armoredPublicPGPkeyBlock);
    PGPPublicKey pgpPublicKey = PGPTools.readPublicKeyFromString(armoredPublicPGPkeyBlock);
    // create PGPPublicKeyData (Entity in DS) from PGPPublicKey:
    PGPPublicKeyData pgpPublicKeyData = new PGPPublicKeyData(pgpPublicKey, armoredPublicPGPkeyBlock, userId);
    pgpPublicKeyData.setUserBirthday(userBirthDate);
    /* --- Check PGPPublic Key: */
    // --- check key creation date/time:
    Date creationTime = pgpPublicKey.getCreationTime();
    if (creationTime.after(new Date())) {
        throw new Exception("Invalid key creation Date/Time");
    }
    // -- bits size check:
    if (pgpPublicKeyData.getBitStrength() < 2048) {
        throw new Exception("Key Strength (bits size) should be min 2048 bits");
    }
    // -- email check:
    if (!pgpPublicKeyData.getUserEmail().getEmail().toLowerCase().equals(googleUser.getEmail().toLowerCase())) {
        throw new Exception("Email in the key's user ID should be the same as in account");
    }
    // -- key validity period check
    Integer validDays = pgpPublicKey.getValidDays();
    if (validDays > 366 * 2) {
        throw new Exception("This key valid for more than 2 years");
    } else if (validDays <= 0) {
        // 
        throw new Exception("This key's validity term is incorrect");
    }
    // --- check for dublicates in DS:
    List<PGPPublicKeyData> duplicates = ofy().load().type(PGPPublicKeyData.class).filter("fingerprintStr", pgpPublicKeyData.getFingerprint()).list();
    if (!duplicates.isEmpty()) {
        throw new Exception("The key with fingerprint" + pgpPublicKeyData.getFingerprint() + "already registered");
    }
    // create CryptonomicaUser:
    CryptonomicaUser cryptonomicaUser = new CryptonomicaUser(googleUser, pgpPublicKeyData, newUserRegistrationForm);
    // save new user and his key
    Key<CryptonomicaUser> cryptonomicaUserKey = ofy().save().entity(cryptonomicaUser).now();
    cryptonomicaUser = // ?
    ofy().load().key(cryptonomicaUserKey).now();
    Key<PGPPublicKeyData> pgpPublicKeyDataKey = ofy().save().entity(pgpPublicKeyData).now();
    pgpPublicKeyData = ofy().load().key(pgpPublicKeyDataKey).now();
    // 
    Login login = UserTools.registerLogin(httpServletRequest, googleUser);
    // 
    ArrayList<PGPPublicKeyData> pgpPublicKeyDataArrayList = new ArrayList<>();
    pgpPublicKeyDataArrayList.add(pgpPublicKeyData);
    UserProfileGeneralView userProfileGeneralView = new UserProfileGeneralView(cryptonomicaUser, pgpPublicKeyDataArrayList);
    // - for $rootScope.currentUser
    userProfileGeneralView.setRegisteredCryptonomicaUser(Boolean.TRUE);
    // 
    String messageToUser;
    if (cryptonomicaUser != null) {
        messageToUser = "User created successful";
    } else {
        messageToUser = "Error creating new user";
    }
    NewUserRegistrationReturn result = new NewUserRegistrationReturn(messageToUser, new PGPPublicKeyGeneralView(pgpPublicKeyData), userProfileGeneralView, new LoginView(login));
    // send an email to user:
    final Queue queue = QueueFactory.getDefaultQueue();
    Gson prettyGson = new GsonBuilder().setPrettyPrinting().create();
    queue.add(TaskOptions.Builder.withUrl("/_ah/SendGridServlet").param("email", googleUser.getEmail()).param("messageSubject", "You are registered on Cryptonomica server").param("messageText", "Congratulation! \n\n" + userProfileGeneralView.getFirstName().toUpperCase() + " " + userProfileGeneralView.getLastName().toUpperCase() + ",\n\n" + "You are registered on Cryptonomica server" + "\n\n" + "To verify your key online:" + "\n" + "1) go to 'My profile', 2) click on key ID and go to page with key data , " + "3) click green button 'Verify online' and follow instructions provided by web application" + "\n\n" + "Best regards, \n\n" + "Cryptonomica team\n\n" + new Date().toString() + "\n\n" + "if you think it's wrong or it is an error, please write to admin@cryptonomica.net \n"));
    // 
    return result;
}
Also used : PGPPublicKeyData(net.cryptonomica.entities.PGPPublicKeyData) PGPPublicKeyGeneralView(net.cryptonomica.returns.PGPPublicKeyGeneralView) GsonBuilder(com.google.gson.GsonBuilder) ArrayList(java.util.ArrayList) PGPPublicKey(org.bouncycastle.openpgp.PGPPublicKey) Gson(com.google.gson.Gson) Login(net.cryptonomica.entities.Login) CryptonomicaUser(net.cryptonomica.entities.CryptonomicaUser) Date(java.util.Date) UserProfileGeneralView(net.cryptonomica.returns.UserProfileGeneralView) NewUserRegistrationReturn(net.cryptonomica.returns.NewUserRegistrationReturn) LoginView(net.cryptonomica.returns.LoginView) Queue(com.google.appengine.api.taskqueue.Queue) ApiMethod(com.google.api.server.spi.config.ApiMethod)

Example 17 with ApiMethod

use of com.google.api.server.spi.config.ApiMethod in project cryptonomica by Cryptonomica.

the class NotaryAPI method addOrRewriteNotary.

@ApiMethod(name = "addOrRewriteNotary", path = "addOrRewriteNotary", httpMethod = ApiMethod.HttpMethod.POST)
@SuppressWarnings("unused")
public // add or rewrite "Notary" info to user.
NotaryGeneralView addOrRewriteNotary(// final HttpServletRequest httpServletRequest,
final User googleUser, // TODO: add form verification (required fields not empty)
final AddNotaryForm addNotaryForm) throws Exception {
    LOG.warning("addNotaryForm: ");
    LOG.warning(new Gson().toJson(addNotaryForm));
    /* -- check authorization */
    CryptonomicaUser cryptonomicaUser = UserTools.ensureNotaryOrCryptonomicaOfficer(googleUser);
    /* verify addNotaryForm */
    if ((addNotaryForm.getNotaryInfo().length() < 1 || addNotaryForm.getNotaryInfo() == null) || (addNotaryForm.getLicenceIssuedBy().length() < 1 || addNotaryForm.getLicenceIssuedBy() == null) || (addNotaryForm.getLicenceCountry().length() < 1 || addNotaryForm.getLicenceCountry() == null) || (addNotaryForm.getLicenceIssuedOn() == null) || (addNotaryForm.getLicenceInfo() == null) || (addNotaryForm.getNotaryInfo().length() < 1 || addNotaryForm.getNotaryInfo() == null)) {
        throw new Exception("Notary form is not complete or invalid");
    }
    /* create and store new NotaryLicence */
    NotaryLicence notaryLicence = new NotaryLicence(addNotaryForm);
    Key<NotaryLicence> notaryLicenceKey = ofy().save().entity(notaryLicence).now();
    notaryLicence = ofy().load().key(notaryLicenceKey).now();
    LOG.warning("notaryLicence form DB: " + new Gson().toJson(notaryLicence));
    /* create and save new Verification */
    Verification verification = new Verification(addNotaryForm, cryptonomicaUser, notaryLicenceKey);
    Key<Verification> verificationKey = ofy().save().entity(verification).now();
    verification = ofy().load().key(verificationKey).now();
    LOG.warning("Verification from DB: " + new Gson().toJson(verification));
    // add Verification to notary licence and save license
    notaryLicence.setVerification(verificationKey);
    notaryLicenceKey = ofy().save().entity(notaryLicence).now();
    notaryLicence = ofy().load().key(notaryLicenceKey).now();
    /*  create and save new Notary  */
    Notary notary = new Notary(addNotaryForm, notaryLicenceKey);
    Key<Notary> notaryKey = ofy().save().entity(notary).now();
    notary = ofy().load().key(notaryKey).now();
    LOG.warning("Notary from DB: " + new Gson().toJson(notary));
    // load notary licenses list // TODO: modify connection Notary - NotaryLicence
    List<NotaryLicence> notaryLicenceList = ofy().load().type(NotaryLicence.class).ancestor(Key.create(CryptonomicaUser.class, notary.getId())).list();
    // transform Notary licenses list to licenceGeneralView lis
    ArrayList<NotaryLicenceGeneralView> notaryLicenceGeneralViewArrayList = new ArrayList<>();
    // create verification list
    List<Verification> verificationList = new ArrayList<>();
    verificationList.add(verification);
    // 
    notaryLicenceGeneralViewArrayList.add(new NotaryLicenceGeneralView(notaryLicence, verificationList));
    List<PGPPublicKeyData> pgpPublicKeyDataList = ofy().load().type(PGPPublicKeyData.class).ancestor(notary).list();
    ArrayList<PGPPublicKeyGeneralView> pgpPublicKeyGeneralViewArrayList = new ArrayList<>();
    // create ArrayList of PGP Public Keys representations:
    for (PGPPublicKeyData pgpPublicKeyData : pgpPublicKeyDataList) {
        pgpPublicKeyGeneralViewArrayList.add(new PGPPublicKeyGeneralView(pgpPublicKeyData));
    }
    LOG.warning("ArrayList<PGPPublicKeyGeneralView>: " + new Gson().toJson(pgpPublicKeyGeneralViewArrayList));
    // load Cryptonomica user from db
    CryptonomicaUser notaryCryptonomicaUser = ofy().load().key(Key.create(CryptonomicaUser.class, addNotaryForm.getNotaryCryptonomicaUserID())).now();
    LOG.warning("notaryCryptonomicaUser from DB: " + new Gson().toJson(notaryCryptonomicaUser));
    // set active user and set notary and save in DB:
    // < TODO: connect to payment
    notaryCryptonomicaUser.setActive(Boolean.TRUE);
    // 
    Boolean alreadyWasANotary;
    if (notaryCryptonomicaUser.getNotary() != null && notaryCryptonomicaUser.getNotary()) {
        alreadyWasANotary = true;
    } else {
        alreadyWasANotary = false;
    }
    notaryCryptonomicaUser.setNotary(Boolean.TRUE);
    ofy().save().entity(notaryCryptonomicaUser);
    // transfer cryptonomica user data from DB to UserProfileGeneralView
    UserProfileGeneralView userProfileGeneralView = new UserProfileGeneralView(notaryCryptonomicaUser, pgpPublicKeyDataList);
    LOG.warning("UserProfileGeneralView: " + new Gson().toJson(userProfileGeneralView));
    NotaryGeneralView notaryGeneralView = new NotaryGeneralView(userProfileGeneralView, notary, notaryLicenceGeneralViewArrayList);
    LOG.warning("Notary General View to return: " + new Gson().toJson(notaryGeneralView));
    // send an email to notary:
    final Queue queue = QueueFactory.getDefaultQueue();
    if (alreadyWasANotary) {
        queue.add(TaskOptions.Builder.withUrl("/_ah/SendGridServlet").param("email", notaryCryptonomicaUser.getEmail().getEmail()).param("messageSubject", "Your notary data changed on Cryptonomica server").param("messageText", notaryCryptonomicaUser.getFirstName() + " " + notaryCryptonomicaUser.getLastName() + ", \n" + "On " + DATE_TIME_PRINTER.format(verification.getVerifiedOn()) + " your notary data were changed on Cryptonomica server:\n\n" + "Notary info: \n" + notary.getInfo() + "\n" + "Notary country code: \n" + notaryLicence.getCountry() + "\n" + "Notary licence issued by: \n" + notaryLicence.getIssuedBy() + "\n" + "Notary licence issued on: \n" + DATE_PRINTER.format(notaryLicence.getIssuedOn()) + "\n" + "Information about your notary data verification: \n" + verification.getVerificationInfo() + "\n" + "\n" + "changes made by: \n" + cryptonomicaUser.getFirstName() + " " + cryptonomicaUser.getLastName() + "\n\n" + "if you think it's wrong or it is an error, please write to admin@cryptonomica.net \n"));
    } else {
        queue.add(TaskOptions.Builder.withUrl("/_ah/SendGridServlet").param("email", notaryCryptonomicaUser.getEmail().getEmail()).param("messageSubject", "You were authorized as a notary on Cryptonomica server").param("messageText", "CONGRATULATION! \n\n" + notaryCryptonomicaUser.getFirstName() + " " + notaryCryptonomicaUser.getLastName() + ", \n\n" + "You were authorized as a notary on Cryptonomica server!\n\n" + "Information about your notary data verification: \n\n" + "Notary info: \n\n" + notary.getInfo() + "\n\n" + "Notary country code: \n\n" + notaryLicence.getCountry() + "\n\n" + "Notary licence issued by: \n\n" + notaryLicence.getIssuedBy() + "\n\n" + "Notary licence issued on: \n" + DATE_PRINTER.format(notaryLicence.getIssuedOn()) + "\n\n" + "Information about your notary data verification: \n" + verification.getVerificationInfo() + "\n\n" + "Verification made by: \n\n" + cryptonomicaUser.getFirstName() + " " + cryptonomicaUser.getLastName()));
    }
    return notaryGeneralView;
}
Also used : ArrayList(java.util.ArrayList) Gson(com.google.gson.Gson) Queue(com.google.appengine.api.taskqueue.Queue) ApiMethod(com.google.api.server.spi.config.ApiMethod)

Example 18 with ApiMethod

use of com.google.api.server.spi.config.ApiMethod in project iosched by google.

the class ReservationsEndpoint method reset.

/**
 * Reset reservations in datastore to match those in RTDB. Reservations in RTDB are used
 * as the source of truth, corresponding reservations in datastore are updated to match
 * those in RTDB. Reservations in RTDB that do not exist in datastore are added to datastore.
 * Reservations that exist in datastore and do not exist in RTDB are updated in datastore
 * with status DELETED.
 *
 * Use of this endpoint should be followed by a user data sync.
 *
 * @param user User making request (injected by Endpoints)
 */
@ApiMethod(name = "reset", path = "reset")
public void reset(User user) throws UnauthorizedException {
    if (user == null) {
        throw new UnauthorizedException("Invalid credentials");
    }
    // Add Sync Reservations worker to queue.
    Queue queue = QueueFactory.getQueue("SyncReservationsQueue");
    TaskOptions taskOptions = TaskOptions.Builder.withUrl("/queue/syncres").method(Method.GET);
    queue.add(taskOptions);
}
Also used : TaskOptions(com.google.appengine.api.taskqueue.TaskOptions) UnauthorizedException(com.google.api.server.spi.response.UnauthorizedException) Queue(com.google.appengine.api.taskqueue.Queue) ApiMethod(com.google.api.server.spi.config.ApiMethod)

Example 19 with ApiMethod

use of com.google.api.server.spi.config.ApiMethod in project iosched by google.

the class UserdataEndpoint method addReviewedSessions.

/**
 * Mark a session as reviewed for the current user. This can not be unset.
 *
 * @param user       Current user (injected by Endpoints)
 * @param sessionIds Session IDs to mark as reviewed.
 * @return The list of reviewed sessions for the user (as an array of Strings)
 */
@ApiMethod(name = "addReviewedSessions", path = "reviewed/batch", httpMethod = ApiMethod.HttpMethod.POST)
public Object[] addReviewedSessions(User user, @Named("sessionIds") String[] sessionIds) throws UnauthorizedException {
    UserData data = getUser(user);
    for (String session : sessionIds) {
        data.reviewedSessions.add(session);
    }
    save(data);
    return data.reviewedSessions.toArray();
}
Also used : UserData(com.google.samples.apps.iosched.server.userdata.db.UserData) ApiMethod(com.google.api.server.spi.config.ApiMethod)

Example 20 with ApiMethod

use of com.google.api.server.spi.config.ApiMethod in project iosched by google.

the class UserdataEndpoint method addBookmarkedSessions.

/**
 * Add a bookmarked session for the current user. If the session is already in the user's feed,
 * it will be annotated with inSchedule=true.
 *
 * @param user         Current user (injected by Endpoints)
 * @param sessionIds   Session IDs to mark as bookmarked.
 * @param timestampUTC The time (in millis, UTC) when the user performed this action. May be
 *                     different than the time this method is called if offline sync is
 *                     implemented. MUST BE ACCURATE - COMPENSATE FOR CLOCK DRIFT!
 * @return The list of bookmarked sessions for the user
 */
@ApiMethod(name = "addBookmarkedSessions", path = "bookmarked/batch", httpMethod = ApiMethod.HttpMethod.POST)
public Map<String, BookmarkedSession> addBookmarkedSessions(User user, @Named("sessionIds") String[] sessionIds, @Named("timestampUTC") long timestampUTC) throws UnauthorizedException {
    UserData data = getUser(user);
    for (String session : sessionIds) {
        BookmarkedSession s = new BookmarkedSession(session, true, timestampUTC);
        data.bookmarkedSessions.put(session, s);
    }
    save(data);
    return data.bookmarkedSessions;
}
Also used : BookmarkedSession(com.google.samples.apps.iosched.server.userdata.db.BookmarkedSession) UserData(com.google.samples.apps.iosched.server.userdata.db.UserData) ApiMethod(com.google.api.server.spi.config.ApiMethod)

Aggregations

ApiMethod (com.google.api.server.spi.config.ApiMethod)54 CryptonomicaUser (net.cryptonomica.entities.CryptonomicaUser)19 Gson (com.google.gson.Gson)16 UserData (com.google.samples.apps.iosched.server.userdata.db.UserData)10 PGPPublicKeyData (net.cryptonomica.entities.PGPPublicKeyData)10 ArrayList (java.util.ArrayList)9 StringWrapperObject (net.cryptonomica.returns.StringWrapperObject)9 NotFoundException (com.google.api.server.spi.response.NotFoundException)8 BadRequestException (com.google.api.server.spi.response.BadRequestException)7 UnauthorizedException (com.google.api.server.spi.response.UnauthorizedException)7 Queue (com.google.appengine.api.taskqueue.Queue)7 HTTPResponse (com.google.appengine.api.urlfetch.HTTPResponse)6 Device (com.google.samples.apps.iosched.server.gcm.db.models.Device)6 MessageSender (com.google.samples.apps.iosched.server.gcm.device.MessageSender)5 AppSettings (net.cryptonomica.entities.AppSettings)5 PGPPublicKeyGeneralView (net.cryptonomica.returns.PGPPublicKeyGeneralView)5 UserProfileGeneralView (net.cryptonomica.returns.UserProfileGeneralView)5 BookmarkedSession (com.google.samples.apps.iosched.server.userdata.db.BookmarkedSession)4 BooleanWrapperObject (net.cryptonomica.returns.BooleanWrapperObject)4 PGPPublicKey (org.bouncycastle.openpgp.PGPPublicKey)4