Java Code Examples for com.google.appengine.api.users.User#getEmail()

The following examples show how to use com.google.appengine.api.users.User#getEmail() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SignGuestbookServlet.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
  Greeting greeting;

  UserService userService = UserServiceFactory.getUserService();
  User user = userService.getCurrentUser(); // Find out who the user is.

  String guestbookName = req.getParameter("guestbookName");
  String content = req.getParameter("content");
  if (user != null) {
    greeting = new Greeting(guestbookName, content, user.getUserId(), user.getEmail());
  } else {
    greeting = new Greeting(guestbookName, content);
  }

  // Use Objectify to save the greeting and now() is used to make the call synchronously as we
  // will immediately get a new page using redirect and we want the data to be present.
  ObjectifyService.ofy().save().entity(greeting).now();

  resp.sendRedirect("/guestbook.jsp?guestbookName=" + guestbookName);
}
 
Example 2
Source File: ConferenceApi.java    From ud859 with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Creates or updates a Profile object associated with the given user object.
 *
 * @param user A User object injected by the cloud endpoints.
 * @param profileForm A ProfileForm object sent from the client form.
 * @return Profile object just created.
 * @throws UnauthorizedException when the User object is null.
 */
@ApiMethod(name = "saveProfile", path = "profile", httpMethod = HttpMethod.POST)
public Profile saveProfile(final User user, final ProfileForm profileForm)
        throws UnauthorizedException {
    if (user == null) {
        throw new UnauthorizedException("Authorization required");
    }
    String displayName = profileForm.getDisplayName();
    TeeShirtSize teeShirtSize = profileForm.getTeeShirtSize();

    Profile profile = ofy().load().key(Key.create(Profile.class, getUserId(user))).now();
    if (profile == null) {
        // Populate displayName and teeShirtSize with the default values if null.
        if (displayName == null) {
            displayName = extractDefaultDisplayNameFromEmail(user.getEmail());
        }
        if (teeShirtSize == null) {
            teeShirtSize = TeeShirtSize.NOT_SPECIFIED;
        }
        profile = new Profile(getUserId(user), displayName, user.getEmail(), teeShirtSize);
    } else {
        profile.update(displayName, teeShirtSize);
    }
    ofy().save().entity(profile).now();
    return profile;
}
 
Example 3
Source File: SignGuestbookServlet.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
  Greeting greeting;

  UserService userService = UserServiceFactory.getUserService();
  User user = userService.getCurrentUser(); // Find out who the user is.

  String guestbookName = req.getParameter("guestbookName");
  String content = req.getParameter("content");
  if (user != null) {
    greeting = new Greeting(guestbookName, content, user.getUserId(), user.getEmail());
  } else {
    greeting = new Greeting(guestbookName, content);
  }

  greeting.save();

  resp.sendRedirect("/guestbook.jsp?guestbookName=" + guestbookName);
}
 
Example 4
Source File: SignGuestbookServlet.java    From appengine-java-guestbook-multiphase with Apache License 2.0 6 votes vote down vote up
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
  Greeting greeting;

  UserService userService = UserServiceFactory.getUserService();
  User user = userService.getCurrentUser();  // Find out who the user is.

  String guestbookName = req.getParameter("guestbookName");
  String content = req.getParameter("content");
  if (user != null) {
    greeting = new Greeting(guestbookName, content, user.getUserId(), user.getEmail());
  } else {
    greeting = new Greeting(guestbookName, content);
  }

  // Use Objectify to save the greeting and now() is used to make the call synchronously as we
  // will immediately get a new page using redirect and we want the data to be present.
  ObjectifyService.ofy().save().entity(greeting).now();

  resp.sendRedirect("/guestbook.jsp?guestbookName=" + guestbookName);
}
 
Example 5
Source File: Fido2RequestHandler.java    From webauthndemo with Apache License 2.0 6 votes vote down vote up
@ApiMethod(name = "getRegistrationRequest", path="get/register")
public List<String> getRegistrationRequest(User user) throws OAuthRequestException {
  if (user == null) {
    throw new OAuthRequestException("User is not authenticated");
  }

  PublicKeyCredentialCreationOptions options = new PublicKeyCredentialCreationOptions(
      user.getNickname() /* userName */, user.getEmail() /* userId */,
      Constants.APP_ID /* rpId */, Constants.APP_ID /* rpName */);
  SessionData session = new SessionData(options.challenge, Constants.APP_ID);
  session.save(user.getEmail());
  JsonObject sessionJson = session.getJsonObject();
  JsonObject optionsJson = options.getJsonObject();
  optionsJson.add("session", sessionJson);

  List<String> resultList = new ArrayList<String>();
  resultList.add(optionsJson.toString());
  return resultList;
}
 
Example 6
Source File: RegistryLockGetAction.java    From nomulus with Apache License 2.0 5 votes vote down vote up
private ImmutableMap<String, ?> getLockedDomainsMap(String clientId)
    throws RegistrarAccessDeniedException {
  // Note: admins always have access to the locks page
  checkArgument(authResult.userAuthInfo().isPresent(), "User auth info must be present");

  boolean isAdmin = registrarAccessor.isAdmin();
  Registrar registrar = getRegistrarAndVerifyLockAccess(registrarAccessor, clientId, isAdmin);
  User user = authResult.userAuthInfo().get().user();

  Optional<RegistrarContact> contactOptional = getContactMatchingLogin(user, registrar);
  boolean isRegistryLockAllowed =
      isAdmin || contactOptional.map(RegistrarContact::isRegistryLockAllowed).orElse(false);
  // Use the contact's registry lock email if it's present, else use the login email (for admins)
  String relevantEmail =
      isAdmin
          ? user.getEmail()
          // if the contact isn't present, we shouldn't display the email anyway so empty is fine
          : contactOptional.flatMap(RegistrarContact::getRegistryLockEmailAddress).orElse("");
  return ImmutableMap.of(
      LOCK_ENABLED_FOR_CONTACT_PARAM,
      isRegistryLockAllowed,
      EMAIL_PARAM,
      relevantEmail,
      PARAM_CLIENT_ID,
      registrar.getClientId(),
      LOCKS_PARAM,
      getLockedDomains(clientId, isAdmin));
}
 
Example 7
Source File: UserServiceTGImpl.java    From tech-gallery with Apache License 2.0 5 votes vote down vote up
/**
 * This method should be executed whenever a user logs in It check whether the
 * user exists on TG's datastore and create them, if not. It also checks if
 * the user's email has been changed and update it, in case it was changed.
 *
 * @param user
 *          A Google AppEngine API user
 * @return A response with the user data as it is on TG datastore
 *
 * @throws InternalServerErrorException
 *           in case something goes wrong
 * @throws NotFoundException
 *           in case the information are not founded
 * @throws BadRequestException
 *           in case a request with problem were made.
 * @throws OAuthRequestException
 *           in case of authentication problem
 * @throws IOException
 *           in case of a IO exception
 */
@Override
public TechGalleryUser handleLogin(Integer timezoneOffset, final User user, HttpServletRequest req)
    throws NotFoundException, BadRequestException, InternalServerErrorException, IOException,
    OAuthRequestException {
  authorize(user);
  String userEmail = user.getEmail();
  String header = req.getHeader("Authorization");
  String accesstoken = header.substring(header.indexOf(' ')).trim(); // "Bearer
                                                                     // ".length

  GoogleCredential credential = new GoogleCredential().setAccessToken(accesstoken);
  Plus plus = new Plus.Builder(new NetHttpTransport(), new JacksonFactory(), credential)
      .setApplicationName(i18n.t("Tech Gallery")).build();
  Person person = plus.people().get("me").execute();
  TechGalleryUser tgUser = userDao.findByGoogleId(user.getUserId());
  // Couldn't find by googleID. Try email
  if (tgUser == null) {
    tgUser = userDao.findByEmail(userEmail);
  }
  // Ok, we couldn't find it. Create it.
  if (tgUser == null) {
    tgUser = new TechGalleryUser();
  }
  updateUserInformation(user, person, tgUser);
  tgUser.setTimezoneOffset(timezoneOffset);
  addUser(tgUser);
  log.info("User " + tgUser.getName() + " added/updated");
  return tgUser;
}
 
Example 8
Source File: ConferenceApi.java    From ud859 with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Gets the Profile entity for the current user
 * or creates it if it doesn't exist
 * @param user
 * @return user's Profile
 */
private static Profile getProfileFromUser(User user) {
    // First fetch the user's Profile from the datastore.
    Profile profile = ofy().load().key(
            Key.create(Profile.class, user.getUserId())).now();
    if (profile == null) {
        // Create a new Profile if it doesn't exist.
        // Use default displayName and teeShirtSize
        String email = user.getEmail();
        profile = new Profile(user.getUserId(),
                extractDefaultDisplayNameFromEmail(email), email, TeeShirtSize.NOT_SPECIFIED);
    }
    return profile;
}
 
Example 9
Source File: BeginMakeCredential.java    From webauthndemo with Apache License 2.0 5 votes vote down vote up
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
  User user = userService.getCurrentUser();
  // String rpId = (request.isSecure() ? "https://" : "http://") + request.getHeader("Host");
  String rpId = Iterables.get(Splitter.on(':').split(request.getHeader("Host")), 0);
  String rpName = getServletContext().getInitParameter("name");
  rpName = (rpName == null ? "" : rpName);

  PublicKeyCredentialCreationOptions options =
      new PublicKeyCredentialCreationOptions(user.getNickname(), user.getEmail(), rpId, rpName);

  String hasAdvanced = request.getParameter("advanced");
  if (hasAdvanced.equals("true")) {
    parseAdvancedOptions(request.getParameter("advancedOptions"), options);
  }

  SessionData session = new SessionData(options.challenge, rpId);

  session.save(userService.getCurrentUser().getEmail());
  JsonObject sessionJson = session.getJsonObject();
  JsonObject optionsJson = options.getJsonObject();
  optionsJson.add("session", sessionJson);

  AuthenticationExtensionsClientInputs extensions = new AuthenticationExtensionsClientInputs();
  try {
    KeyPair cableKeyPair = extensions.addCableRegistrationData();
    // Store the KeyPair in storage
    CableKeyPair storedKeyPair = new CableKeyPair(cableKeyPair);
    storedKeyPair.save(session.getId());
  } catch (Exception e) {}

  optionsJson.add("extensions", extensions.getRegistrationExtensions());

  response.setContentType("application/json");
  response.getWriter().println(optionsJson.toString());
}
 
Example 10
Source File: Greeting.java    From appengine-angular-guestbook-java with Apache License 2.0 5 votes vote down vote up
public static Greeting fromEntity(Entity greetingEntity) {
  String author;
  User user = (User) greetingEntity.getProperty("user");
  if (user == null) {
    author = "an anonymous user";
  } else {
    author = user.getEmail();
  }
  return new Greeting((String) greetingEntity.getProperty("content"),
      (Date) greetingEntity.getProperty("date"), author);
}
 
Example 11
Source File: CheckInEndpoint.java    From solutions-mobile-shopping-assistant-backend-java with Apache License 2.0 5 votes vote down vote up
private void pushPersonalizedOffers(String placeId, User user) {
  // insert a task to a queue
  log.info("adding a task to recommendations-queue");
  Queue queue = QueueFactory.getQueue("recommendations-queue");

  try {
    String userEmail = user.getEmail();
    queue.add(withUrl("/tasks/recommendations")
        .param("userEmail", userEmail).param("placeId", placeId));
    log.info("task added");
  } catch (RuntimeException e) {
    log.severe(e.getMessage());
  }
}
 
Example 12
Source File: DummyGameEndpoint.java    From solutions-ios-push-notification-sample-backend-java with Apache License 2.0 5 votes vote down vote up
/**
 * Called when the player unlocked an achievement.
 *
 * @param achievement the achievement unlocked by the player.
 * @throws ServiceException
 */
public void achievementUnlocked(@Named("message") String achievement, User user)
    throws ServiceException {

  if (user == null && !Configuration.ALLOW_UNAUTHENTICATED_CALLS) {
    throw new UnauthorizedException("Only authenticated calls are allowed");
  }

  // The actual game backend would probably validate the achievement first
  // and then store it in Datastore. Then it might send push notification
  // to user's friends.
  // In this sample only the send part is implemented and instead of
  // retrieving the list of user's friends, the code just retrieves
  // a few most recently registered devices and sends an alert to them

  String playerName =
      (user == null || user.getEmail() == null) ? "Anonymous User" : user.getEmail();

  String alert = String.format("%1$s unlocked achievement '%2$s'", playerName, achievement);

  EntityManager mgr = null;
  try {
    mgr = getEntityManager();
    Query query =
        mgr.createQuery("select deviceToken from DeviceRegistration d order by timestamp");

    query.setFirstResult(0);
    query.setMaxResults(5);

    @SuppressWarnings("unchecked")
    List<String> deviceTokensOfFriends = query.getResultList();

    log.info("Sent achievement unlocked push notification to " + deviceTokensOfFriends.size()
        + " friend(s) of " + playerName);
    PushNotificationUtility.enqueuePushAlert(alert, deviceTokensOfFriends);
  } finally {
    mgr.close();
  }
}
 
Example 13
Source File: ConferenceApi.java    From ud859 with GNU General Public License v3.0 5 votes vote down vote up
private static Profile getProfileFromUser(User user, String userId) {
    // First fetch it from the datastore.
    Profile profile = ofy().load().key(
            Key.create(Profile.class, userId)).now();
    if (profile == null) {
        // Create a new Profile if not exist.
        String email = user.getEmail();
        profile = new Profile(userId,
                extractDefaultDisplayNameFromEmail(email), email, TeeShirtSize.NOT_SPECIFIED);
    }
    return profile;
}
 
Example 14
Source File: TechnologyServiceImpl.java    From tech-gallery with Apache License 2.0 4 votes vote down vote up
private String getSafeEmail(User user) {
    if (user != null) {
        return user.getEmail();
    }
    return null;
}
 
Example 15
Source File: Greetings.java    From appengine-maven-archetypes-java with Apache License 2.0 4 votes vote down vote up
@ApiMethod(name = "greetings.authed", path = "hellogreeting/authed")
public HelloGreeting authedGreeting(User user) {
  HelloGreeting response = new HelloGreeting("hello " + user.getEmail());
  return response;
}
 
Example 16
Source File: EndpointUtil.java    From solutions-mobile-shopping-assistant-backend-java with Apache License 2.0 4 votes vote down vote up
/** Throws an exception if the user object doesn't represent an authenticated call. 
 * @param user User object to be checked if it represents an authenticated caller.
 * @throws UnauthorizedException when the user object does not represent an admin.
 */
public static void throwIfNotAuthenticated(User user) throws UnauthorizedException {
   if (user == null || user.getEmail() == null) {
     throw new UnauthorizedException("Only authenticated users may invoke this operation");
   }
 }
 
Example 17
Source File: ConferenceApi.java    From ud859 with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Creates or updates a Profile object associated with the given user
 * object.
 *
 * @param user
 *            A User object injected by the cloud endpoints.
 * @param profileForm
 *            A ProfileForm object sent from the client form.
 * @return Profile object just created.
 * @throws UnauthorizedException
 *             when the User object is null.
 */

   // Declare this method as a method available externally through Endpoints
@ApiMethod(name = "saveProfile", path = "profile", httpMethod = HttpMethod.POST)

// The request that invokes this method should provide data that
// conforms to the fields defined in ProfileForm

// TODO 1 Pass the ProfileForm parameter
// TODO 2 Pass the User parameter
public Profile saveProfile(final User user, ProfileForm profileForm)
		throws UnauthorizedException {

	String userId = "";
	String mainEmail = "";
	String displayName = "Your name will go here";
	TeeShirtSize teeShirtSize = TeeShirtSize.NOT_SPECIFIED;

	// TODO 2
	// If the user is not logged in, throw an UnauthorizedException
	if (user == null) {
           throw new UnauthorizedException("Authorization required");
       }

	// TODO 1
    // Set the teeShirtSize to the value sent by the ProfileForm, if sent
       // otherwise leave it as the default value
	 if (profileForm.getTeeShirtSize() != null) {
		 teeShirtSize = profileForm.getTeeShirtSize();
	 }

	// TODO 1
       // Set the displayName to the value sent by the ProfileForm, if sent
       // otherwise set it to null
	displayName = profileForm.getDisplayName();
	
	// TODO 2
	// Get the userId and mainEmail
	mainEmail = user.getEmail();
	userId = user.getUserId();

       // TODO 2
       // If the displayName is null, set it to the default value based on the user's email
       // by calling extractDefaultDisplayNameFromEmail(...)
	 if (displayName == null) {
	   displayName = extractDefaultDisplayNameFromEmail(user.getEmail());
	   }

	// Create a new Profile entity from the
	// userId, displayName, mainEmail and teeShirtSize
	Profile profile = new Profile(userId, displayName, mainEmail, teeShirtSize);

	// TODO 3 (In lesson 3)
	// Save the entity in the datastore

	// Return the profile
	return profile;
}
 
Example 18
Source File: ConferenceApi.java    From ud859 with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Creates or updates a Profile object associated with the given user
 * object.
 *
 * @param user
 *            A User object injected by the cloud endpoints.
 * @param profileForm
 *            A ProfileForm object sent from the client form.
 * @return Profile object just created.
 * @throws UnauthorizedException
 *             when the User object is null.
 */

// Declare this method as a method available externally through Endpoints
@ApiMethod(name = "saveProfile", path = "profile", httpMethod = HttpMethod.POST)
// The request that invokes this method should provide data that
// conforms to the fields defined in ProfileForm
// TODO 1 Pass the ProfileForm parameter
// TODO 2 Pass the User parameter
public Profile saveProfile(final User user, ProfileForm profileForm)
        throws UnauthorizedException {

    // TODO 2
    // If the user is not logged in, throw an UnauthorizedException
    if (user == null) {
        throw new UnauthorizedException("Authorization required");
    }

    // TODO 2
    // Get the userId and mainEmail
    String mainEmail = user.getEmail();
    String userId = user.getUserId();

    // TODO 1
    // Get the displayName and teeShirtSize sent by the request.

    String displayName = profileForm.getDisplayName();
    TeeShirtSize teeShirtSize = profileForm.getTeeShirtSize();

    // Get the Profile from the datastore if it exists
    // otherwise create a new one
    Profile profile = ofy().load().key(Key.create(Profile.class, userId))
            .now();

    if (profile == null) {
        // Populate the displayName and teeShirtSize with default values
        // if not sent in the request
        if (displayName == null) {
            displayName = extractDefaultDisplayNameFromEmail(user
                    .getEmail());
        }
        if (teeShirtSize == null) {
            teeShirtSize = TeeShirtSize.NOT_SPECIFIED;
        }
        // Now create a new Profile entity
        profile = new Profile(userId, displayName, mainEmail, teeShirtSize);
    } else {
        // The Profile entity already exists
        // Update the Profile entity
        profile.update(displayName, teeShirtSize);
    }

    // TODO 3
    // Save the entity in the datastore
    ofy().save().entity(profile).now();

    // Return the profile
    return profile;
}
 
Example 19
Source File: ConferenceApi.java    From ud859 with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Creates or updates a Profile object associated with the given user
 * object.
 *
 * @param user
 *            A User object injected by the cloud endpoints.
 * @param profileForm
 *            A ProfileForm object sent from the client form.
 * @return Profile object just created.
 * @throws UnauthorizedException
 *             when the User object is null.
 */

// Declare this method as a method available externally through Endpoints
@ApiMethod(name = "saveProfile", path = "profile", httpMethod = HttpMethod.POST)
// The request that invokes this method should provide data that
// conforms to the fields defined in ProfileForm
// TODO 1 Pass the ProfileForm parameter
// TODO 2 Pass the User parameter
public Profile saveProfile(final User user, ProfileForm profileForm)
        throws UnauthorizedException {

    // TODO 2
    // If the user is not logged in, throw an UnauthorizedException
    if (user == null) {
        throw new UnauthorizedException("Authorization required");
    }

    // TODO 2
    // Get the userId and mainEmail
    String mainEmail = user.getEmail();
    String userId = user.getUserId();

    // TODO 1
    // Get the displayName and teeShirtSize sent by the request.

    String displayName = profileForm.getDisplayName();
    TeeShirtSize teeShirtSize = profileForm.getTeeShirtSize();

    // Get the Profile from the datastore if it exists
    // otherwise create a new one
    Profile profile = ofy().load().key(Key.create(Profile.class, userId))
            .now();

    if (profile == null) {
        // Populate the displayName and teeShirtSize with default values
        // if not sent in the request
        if (displayName == null) {
            displayName = extractDefaultDisplayNameFromEmail(user
                    .getEmail());
        }
        if (teeShirtSize == null) {
            teeShirtSize = TeeShirtSize.NOT_SPECIFIED;
        }
        // Now create a new Profile entity
        profile = new Profile(userId, displayName, mainEmail, teeShirtSize);
    } else {
        // The Profile entity already exists
        // Update the Profile entity
        profile.update(displayName, teeShirtSize);
    }

    // TODO 3
    // Save the entity in the datastore
    ofy().save().entity(profile).now();

    // Return the profile
    return profile;
}
 
Example 20
Source File: EndpointUtil.java    From MobileShoppingAssistant-sample with Apache License 2.0 3 votes vote down vote up
/**
 * Throws an exception if the user object doesn't represent an authenticated
 * call.
 * @param user User object to be checked if it represents an authenticated
 *      caller.
 * @throws com.google.api.server.spi.response.UnauthorizedException when the
 *      user object does not represent an admin.
 */
public static void throwIfNotAuthenticated(final User user) throws
        UnauthorizedException {
    if (user == null || user.getEmail() == null) {
        throw new UnauthorizedException(
                "Only authenticated users may invoke this operation");
    }
}