com.google.appengine.api.users.UserService Java Examples

The following examples show how to use com.google.appengine.api.users.UserService. 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);
  }

  greeting.save();

  resp.sendRedirect("/guestbook.jsp?guestbookName=" + guestbookName);
}
 
Example #2
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 #3
Source File: ApiUserServiceImpl.java    From sc2gears with Apache License 2.0 6 votes vote down vote up
@Override
public RpcResult< String > getApiKey( final String sharedApiAccount ) {
	LOGGER.fine( "sharedApiAccount: " + sharedApiAccount );
	
	final UserService userService = UserServiceFactory.getUserService();
	final User user = userService.getCurrentUser();
	if ( user == null )
		return RpcResult.createNotLoggedInErrorResult();
	
	PersistenceManager pm = null;
	try {
		
		pm = PMF.get().getPersistenceManager();
		
		final ApiAccount apiAccount = getApiAccount( pm, sharedApiAccount, user );
		if ( apiAccount == null )
			return RpcResult.createNoPermissionErrorResult();
		else
			return new RpcResult< String >( apiAccount.getApiKey() );
		
	} finally {
		if ( pm != null )
			pm.close();
	}
}
 
Example #4
Source File: AdminServiceImpl.java    From sc2gears with Apache License 2.0 6 votes vote down vote up
@Override
public RpcResult< List< MiscFunctionInfo > > getMiscFunctionInfoList() {
	LOGGER.fine( "" );
	
	final UserService userService = UserServiceFactory.getUserService();
	final User user = userService.getCurrentUser();
	if ( user == null )
		return RpcResult.createNotLoggedInErrorResult();
	if ( !userService.isUserAdmin() )
		return RpcResult.createNoPermissionErrorResult();
	
	final List< MiscFunctionInfo > miscFunctionInfoList = new ArrayList< MiscFunctionInfo >( miscFunctionMap.size() );
	
	for ( final Entry< String, DatastoreTask > entry : miscFunctionMap.entrySet() )
		miscFunctionInfoList.add( new MiscFunctionInfo( entry.getKey(), entry.getValue().getParamNames() ) );
	
	Collections.sort( miscFunctionInfoList, new Comparator< MiscFunctionInfo >() {
		@Override
           public int compare( final MiscFunctionInfo i1, final MiscFunctionInfo i2 ) {
            return i1.getName().compareTo( i2.getName() );
           }
	} );
	
	return new RpcResult< List< MiscFunctionInfo > >( miscFunctionInfoList );
}
 
Example #5
Source File: GuestbookServlet.java    From appengine-java-guestbook-multiphase with Apache License 2.0 6 votes vote down vote up
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws IOException {
  if (req.getParameter("testing") != null) {
    resp.setContentType("text/plain");
    resp.getWriter().println("Hello, this is a testing servlet. \n\n");
    Properties p = System.getProperties();
    p.list(resp.getWriter());

  } else {
    UserService userService = UserServiceFactory.getUserService();
    User currentUser = userService.getCurrentUser();

    if (currentUser != null) {
      resp.setContentType("text/plain");
      resp.getWriter().println("Hello, " + currentUser.getNickname());
    } else {
      resp.sendRedirect(userService.createLoginURL(req.getRequestURI()));
    }
  }
}
 
Example #6
Source File: SignGuestbookServlet.java    From appengine-modules-sample-java with Apache License 2.0 6 votes vote down vote up
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp)
    throws IOException {
  final UserService userService = UserServiceFactory.getUserService();
  final User user = userService.getCurrentUser();

  final String guestbookName = req.getParameter("guestbookName");
  final Key guestbookKey = KeyFactory.createKey("Guestbook", guestbookName);
  final String content = req.getParameter("content");
  final Date date = new Date();
  final Entity greeting = new Entity("Greeting", guestbookKey);
  greeting.setProperty("user", user);
  greeting.setProperty("date", date);
  greeting.setProperty("content", content);

  final DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
  datastore.put(greeting);

  resp.sendRedirect("/guestbook.jsp?guestbookName=" + guestbookName);
}
 
Example #7
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 #8
Source File: AdminServiceImpl.java    From sc2gears with Apache License 2.0 6 votes vote down vote up
@Override
public RpcResult< UserInfo > getUserInfo() {
	LOGGER.fine( "" );
	
	final UserInfo userInfo = new UserInfo();
	
	final UserService userService = UserServiceFactory.getUserService();
	final User        user        = userService.getCurrentUser();
	
	if ( user == null )
		userInfo.setLoginUrl( userService.createLoginURL( "/Admin.html" ) );
	else {
		userInfo.setAdmin( userService.isUserAdmin() );
		userInfo.setUserName( user.getNickname() );
		userInfo.setLogoutUrl( userService.createLogoutURL( "/Admin.html" ) );
	}
	
	return new RpcResult< UserInfo >( userInfo );
}
 
Example #9
Source File: LoginServlet.java    From getting-started-java with Apache License 2.0 6 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws IOException, ServletException {

  UserService userService = UserServiceFactory.getUserService();
  if (userService.isUserLoggedIn()) {
    // Save the relevant profile info and store it in the session.
    User user = userService.getCurrentUser();
    req.getSession().setAttribute("userEmail", user.getEmail());
    req.getSession().setAttribute("userId", user.getUserId());

    String destination = (String) req.getSession().getAttribute("loginDestination");
    if (destination == null) {
      destination = "/books";
    }

    resp.sendRedirect(destination);
  } else {
    resp.sendRedirect(userService.createLoginURL("/login"));
  }
}
 
Example #10
Source File: LogoutFilter.java    From getting-started-java with Apache License 2.0 6 votes vote down vote up
@Override
public void doFilter(ServletRequest servletReq, ServletResponse servletResp, FilterChain chain)
    throws IOException, ServletException {
  HttpServletRequest req = (HttpServletRequest) servletReq;
  HttpServletResponse resp = (HttpServletResponse) servletResp;
  String path = req.getRequestURI();

  chain.doFilter(servletReq, servletResp);

  UserService userService = UserServiceFactory.getUserService();
  if (userService.isUserLoggedIn()) {
    resp.sendRedirect(userService.createLogoutURL("/logout"));
  } else if (path.startsWith("/logout")) {
    resp.sendRedirect("/books");
  }
}
 
Example #11
Source File: ListByUserFilter.java    From getting-started-java with Apache License 2.0 6 votes vote down vote up
@Override
public void doFilter(ServletRequest servletReq, ServletResponse servletResp, FilterChain chain)
    throws IOException, ServletException {
  HttpServletRequest req = (HttpServletRequest) servletReq;
  HttpServletResponse resp = (HttpServletResponse) servletResp;

  // [START logStuff]
  String instanceId = System.getenv().containsKey("GAE_MODULE_INSTANCE")
      ? System.getenv("GAE_MODULE_INSTANCE") : "-1";
  logger.log(
      Level.INFO,
      "ListByUserFilter processing new request for path: " + req.getRequestURI()
      + " and instance: " + instanceId);
  // [END logStuff]

  UserService userService = UserServiceFactory.getUserService();
  if (userService.isUserLoggedIn()) {
    chain.doFilter(servletReq, servletResp);
  } else {
    logger.log(Level.INFO, "Not logged in, setting loginDestination to /books/mine");
    req.getSession().setAttribute("loginDestination", "/books/mine");
    resp.sendRedirect(userService.createLoginURL("/login"));
  }
}
 
Example #12
Source File: LoginServlet.java    From getting-started-java with Apache License 2.0 6 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws IOException, ServletException {

  UserService userService = UserServiceFactory.getUserService();
  if (userService.isUserLoggedIn()) {
    // Save the relevant profile info and store it in the session.
    User user = userService.getCurrentUser();
    req.getSession().setAttribute("userEmail", user.getEmail());
    req.getSession().setAttribute("userId", user.getUserId());

    String destination = (String) req.getSession().getAttribute("loginDestination");
    if (destination == null) {
      destination = "/books";
    }

    logger.log(Level.INFO, "logging destination " + destination);
    resp.sendRedirect(destination);
  } else {
    resp.sendRedirect(userService.createLoginURL("/login"));
    logger.log(Level.INFO, "logging destination /login");
  }
}
 
Example #13
Source File: LogoutFilter.java    From getting-started-java with Apache License 2.0 6 votes vote down vote up
@Override
public void doFilter(ServletRequest servletReq, ServletResponse servletResp, FilterChain chain)
    throws IOException, ServletException {
  HttpServletRequest req = (HttpServletRequest) servletReq;
  HttpServletResponse resp = (HttpServletResponse) servletResp;
  String path = req.getRequestURI();

  chain.doFilter(servletReq, servletResp);

  UserService userService = UserServiceFactory.getUserService();
  if (userService.isUserLoggedIn()) {
    resp.sendRedirect(userService.createLogoutURL("/logout"));
  } else if (path.startsWith("/logout")) {
    resp.sendRedirect("/books");
  }
}
 
Example #14
Source File: UsersServlet.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
  UserService userService = UserServiceFactory.getUserService();

  String thisUrl = req.getRequestURI();

  resp.setContentType("text/html");
  if (req.getUserPrincipal() != null) {
    resp.getWriter()
        .println(
            "<p>Hello, "
                + req.getUserPrincipal().getName()
                + "!  You can <a href=\""
                + userService.createLogoutURL(thisUrl)
                + "\">sign out</a>.</p>");
  } else {
    resp.getWriter()
        .println(
            "<p>Please <a href=\"" + userService.createLoginURL(thisUrl) + "\">sign in</a>.</p>");
  }
}
 
Example #15
Source File: MoveServlet.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
  String gameId = request.getParameter("gameKey");
  Objectify ofy = ObjectifyService.ofy();
  Game game = ofy.load().type(Game.class).id(gameId).safe();

  UserService userService = UserServiceFactory.getUserService();
  String currentUserId = userService.getCurrentUser().getUserId();

  int cell = new Integer(request.getParameter("cell"));
  if (!game.makeMove(cell, currentUserId)) {
    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
  } else {
    ofy.save().entity(game).now();
  }
}
 
Example #16
Source File: GuestbookResource.java    From appengine-angular-guestbook-java with Apache License 2.0 6 votes vote down vote up
@POST
@Path("/{guestbookName}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public GuestbookResponse signGuestbook(
    @DefaultValue("default") @PathParam("guestbookName") final String guestbookName,
    final Map<String, String> postData) {
  UserService userService = UserServiceFactory.getUserService();
  DatastoreService datastoreService = DatastoreServiceFactory.getDatastoreService();
  Key guestbookKey = KeyFactory.createKey("Guestbook", guestbookName);
  // We set the above parent key on each Greeting entity in order to make the queries strong
  // consistent. Please Note that as a trade off, we can not write to a single guestbook at a
  // rate more than 1 write/second.
  String content = postData.get("content");
  if (content != null && content.length() > 0) {
    Date date = new Date();
    Entity greeting = new Entity("Greeting", guestbookKey);
    greeting.setProperty("user", userService.getCurrentUser());
    greeting.setProperty("date", date);
    greeting.setProperty("content", content);
    datastoreService.put(greeting);
  }
  return new GuestbookResponse(guestbookName, getGreetings(guestbookName), null);
}
 
Example #17
Source File: GuestbookServlet.java    From appengine-modules-sample-java with Apache License 2.0 5 votes vote down vote up
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws IOException {

  final UserService userService = UserServiceFactory.getUserService();
  final User currentUser = userService.getCurrentUser();

  if (currentUser != null) {
    resp.setContentType("text/plain");
    resp.getWriter().println("Hello, " + currentUser.getNickname());
  } else {
    resp.sendRedirect(userService.createLoginURL(req.getRequestURI()));
  }
}
 
Example #18
Source File: ListByUserFilter.java    From getting-started-java with Apache License 2.0 5 votes vote down vote up
@Override
public void doFilter(ServletRequest servletReq, ServletResponse servletResp, FilterChain chain)
    throws IOException, ServletException {
  HttpServletRequest req = (HttpServletRequest) servletReq;
  HttpServletResponse resp = (HttpServletResponse) servletResp;

  UserService userService = UserServiceFactory.getUserService();
  if (userService.isUserLoggedIn()) {
    chain.doFilter(servletReq, servletResp);
  } else {
    req.getSession().setAttribute("loginDestination", "/books/mine");
    resp.sendRedirect(userService.createLoginURL("/login"));
  }
}
 
Example #19
Source File: AdminServiceImpl.java    From sc2gears with Apache License 2.0 5 votes vote down vote up
@Override
public RpcResult< List< NewAccountSuggestion > > getNewAccountSuggestionList() {
	LOGGER.fine( "" );
	
	final UserService userService = UserServiceFactory.getUserService();
	final User user = userService.getCurrentUser();
	if ( user == null )
		return RpcResult.createNotLoggedInErrorResult();
	if ( !userService.isUserAdmin() )
		return RpcResult.createNoPermissionErrorResult();
	
	PersistenceManager pm = null;
	try {
		pm = PMF.get().getPersistenceManager();
		
		final List< Visit > visitList = new JQBuilder<>( pm, Visit.class ).filter( "visitorKey==null", null ).desc( "date" ).range( 0, 20 ).get();
		
		final List< NewAccountSuggestion > newAccSuggestionList = new ArrayList< NewAccountSuggestion >( visitList.size() + 1 );
		if ( !visitList.isEmpty() )
			newAccSuggestionList.add( new NewAccountSuggestion() );
		
		for ( final Visit visit : visitList ) {
			final NewAccountSuggestion newAccSuggestion = new NewAccountSuggestion();
			
			newAccSuggestion.setGoogleAccount( visit.getUser().getEmail()                              );
			newAccSuggestion.setCountryCode  ( visit.getCountryCode()                                  );
			newAccSuggestion.setCountryName  ( ServerUtils.countryCodeToName( visit.getCountryCode() ) );
			
			newAccSuggestionList.add( newAccSuggestion );
		}
		
		return new RpcResult< List<NewAccountSuggestion> >( newAccSuggestionList );
	} finally {
		if ( pm != null )
			pm.close();
	}
}
 
Example #20
Source File: ApiUserServiceImpl.java    From sc2gears with Apache License 2.0 5 votes vote down vote up
@Override
public RpcResult< Void > saveSettings( final String sharedApiAccount, final SettingsInfo settingsInfo ) {
	LOGGER.fine( "sharedApiAccount: " + sharedApiAccount );
	
	final UserService userService = UserServiceFactory.getUserService();
	final User user = userService.getCurrentUser();
	if ( user == null )
		return RpcResult.createNotLoggedInErrorResult();
	
	PersistenceManager pm = null;
	try {
		
		pm = PMF.get().getPersistenceManager();
		
		final ApiAccount apiAccount = getApiAccount( pm, sharedApiAccount, user );
		if ( apiAccount == null )
			return RpcResult.createNoPermissionErrorResult();
		
		if ( settingsInfo.getContactEmail() != null && !settingsInfo.getContactEmail().isEmpty() )
			if ( !ServerUtils.isEmailValid( settingsInfo.getContactEmail() ) )
				return RpcResult.createErrorResult( "Invalid contact email!" );
		
		if ( settingsInfo.getNotificationAvailOps() < 0 )
			return RpcResult.createErrorResult( "Invalid notification available ops! (Must be equal to or greater than 0!)" );
		
		apiAccount.setContactEmail        ( settingsInfo.getContactEmail() == null || settingsInfo.getContactEmail().isEmpty() ? null : ServletApi.trimStringLength( settingsInfo.getContactEmail(), 500 ) );
		apiAccount.setName                ( settingsInfo.getUserName    () == null || settingsInfo.getUserName    ().isEmpty() ? null : ServletApi.trimStringLength( settingsInfo.getUserName    (), 500 ) );
		apiAccount.setNotificationAvailOps( settingsInfo.getNotificationAvailOps() );
		
	} finally {
		if ( pm != null )
			pm.close();
	}
	
	return RpcResult.createInfoResult( "Settings saved successfully." );
}
 
Example #21
Source File: AppEngineAuthentication.java    From appengine-java-vm-runtime with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isUserInRole(String role, Scope unusedScope) {
  UserService userService = UserServiceFactory.getUserService();
  log.fine("Checking if principal " + userPrincipal + " is in role " + role);
  if (userPrincipal == null) {
    log.info("isUserInRole() called with null principal.");
    return false;
  }

  if (USER_ROLE.equals(role)) {
    return true;
  }

  if (ADMIN_ROLE.equals(role)) {
    User user = userPrincipal.getUser();
    if (user.equals(userService.getCurrentUser())) {
      return userService.isUserAdmin();
    } else {
      // TODO(user): I'm not sure this will happen in
      // practice. If it does, we may need to pass an
      // application's admin list down somehow.
      log.severe("Cannot tell if non-logged-in user " + user + " is an admin.");
      return false;
    }
  } else {
    log.warning("Unknown role: " + role + ".");
    return false;
  }
}
 
Example #22
Source File: UserServiceImpl.java    From sc2gears with Apache License 2.0 5 votes vote down vote up
@Override
public RpcResult< QuotaStatus > getStorageQuotaStatus( final String sharedAccount ) {
	LOGGER.fine( sharedAccount == null ? "" : "Shared account: " + sharedAccount );
	
	final UserService userService = UserServiceFactory.getUserService();
	final User user = userService.getCurrentUser();
	if ( user == null )
		return RpcResult.createNotLoggedInErrorResult();
	
	PersistenceManager pm = null;
	try {
		
		pm = PMF.get().getPersistenceManager();
		
		final Account account = ServerUtils.getAccount( pm, sharedAccount, user );
		if ( account == null )
			return RpcResult.createNoPermissionErrorResult();
		if ( sharedAccount != null && !account.isPermissionGranted( user, Permission.VIEW_QUOTA ) )
			return RpcResult.createNoPermissionErrorResult();
		
		final QuotaStatus quotaStatus = new QuotaStatus();
		
		quotaStatus.setPaidStorage( account.getPaidStorage() );
		quotaStatus.setNotificationQuotaLevel( account.getNotificationQuotaLevel() );
		
		final List< FileStat > fileStatList = new JQBuilder<>( pm, FileStat.class ).filter( "ownerKey==p1", "KEY p1" ).get( account.getKey() );
		if ( !fileStatList.isEmpty() )
			quotaStatus.setUsedStorage( fileStatList.get( 0 ).getStorage() );
		
		return new RpcResult< QuotaStatus >( quotaStatus );
		
	} finally {
		if ( pm != null )
			pm.close();
	}
}
 
Example #23
Source File: AppEngineServletUtils.java    From google-oauth-java-client with Apache License 2.0 5 votes vote down vote up
/**
 * Return the user id for the currently logged in user.
 */
static final String getUserId() {
  UserService userService = UserServiceFactory.getUserService();
  User loggedIn = userService.getCurrentUser();
  Preconditions.checkState(loggedIn != null, "This servlet requires the user to be logged in.");
  return loggedIn.getUserId();
}
 
Example #24
Source File: AppEngineAuthentication.java    From appengine-java-vm-runtime with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new AppEngineUserIdentity based on information retrieved from the Users API.
 *
 * @return A AppEngineUserIdentity if a user is logged in, or null otherwise.
 */
private AppEngineUserIdentity loadUser() {
  UserService userService = UserServiceFactory.getUserService();
  User engineUser = userService.getCurrentUser();
  if (engineUser == null){
    return null;
  }
  return new AppEngineUserIdentity(new AppEnginePrincipal(engineUser));
}
 
Example #25
Source File: UserServiceImpl.java    From sc2gears with Apache License 2.0 5 votes vote down vote up
@Override
public RpcResult< Void > saveReplayLabels( final String sharedAccount, final String sha1, final List< Integer > labels ) {
	LOGGER.fine( ( sharedAccount == null ? "" : "Shared account: " + sharedAccount + ", " ) + "sha1: " + sha1 );
	
	final UserService userService = UserServiceFactory.getUserService();
	final User user = userService.getCurrentUser();
	if ( user == null )
		return RpcResult.createNotLoggedInErrorResult();
	
	PersistenceManager pm = null;
	try {
		
		pm = PMF.get().getPersistenceManager();
		
		final Key accountKey = ServerUtils.getAccountKey( pm, sharedAccount, user, Permission.CHANGE_REP_LABELS );
		if ( accountKey == null )
			return RpcResult.createNoPermissionErrorResult();
		
		final List< Rep > replayList = new JQBuilder<>( pm, Rep.class ).filter( "ownerk==p1 && sha1==p2", "KEY p1, String p2" ).get( accountKey, sha1 );
		if ( replayList.isEmpty() )
			return RpcResult.createNoPermissionErrorResult();
		
		final Rep replay = replayList.get( 0 );
		replay.setLabels( labels );
		
	} finally {
		if ( pm != null )
			pm.close();
	}
	
	return RpcResult.createInfoResult( "Labels saved." );
}
 
Example #26
Source File: UserServiceImpl.java    From sc2gears with Apache License 2.0 5 votes vote down vote up
@Override
public RpcResult< Void > saveReplayComment( final String sharedAccount, final String sha1, final String comment ) {
	LOGGER.fine( ( sharedAccount == null ? "" : "Shared account: " + sharedAccount + ", " ) + "sha1: " + sha1 );
	
	final UserService userService = UserServiceFactory.getUserService();
	final User user = userService.getCurrentUser();
	if ( user == null )
		return RpcResult.createNotLoggedInErrorResult();
	
	PersistenceManager pm = null;
	try {
		
		pm = PMF.get().getPersistenceManager();
		
		final Key accountKey = ServerUtils.getAccountKey( pm, sharedAccount, user, Permission.VIEW_UPDATE_REP_COMMENTS );
		if ( accountKey == null )
			return RpcResult.createNoPermissionErrorResult();
		
		final List< Rep > replayList = new JQBuilder<>( pm, Rep.class ).filter( "ownerk==p1 && sha1==p2", "KEY p1, String p2" ).get( accountKey, sha1 );
		if ( replayList.isEmpty() )
			return RpcResult.createNoPermissionErrorResult();
		
		final Rep replay = replayList.get( 0 );
		replay.setComment( comment == null || comment.isEmpty() ? null : InfoServletApi.trimPrivateRepComment( comment ) );
		
	} finally {
		if ( pm != null )
			pm.close();
	}
	
	return RpcResult.createInfoResult( "Comment saved." );
}
 
Example #27
Source File: UserServiceImpl.java    From sc2gears with Apache License 2.0 5 votes vote down vote up
@Override
public RpcResult< List< String > > saveLabelNames( final String sharedAccount, final List< String > labelNames ) {
	LOGGER.fine( sharedAccount == null ? "" : "Shared account: " + sharedAccount );
	
	final UserService userService = UserServiceFactory.getUserService();
	final User user = userService.getCurrentUser();
	if ( user == null )
		return RpcResult.createNotLoggedInErrorResult();
	
	PersistenceManager pm = null;
	try {
		
		pm = PMF.get().getPersistenceManager();
		
		final Account account = ServerUtils.getAccount( pm, sharedAccount, user );
		if ( account == null )
			return RpcResult.createNoPermissionErrorResult();
		if ( sharedAccount != null && !account.isPermissionGranted( user, Permission.RENAME_LABELS ) )
			return RpcResult.createNoPermissionErrorResult();
		
		// Restore default names for empty strings
		final List< String > checkedNames = new ArrayList< String >( Consts.DEFAULT_REPLAY_LABEL_LIST.size() );
		for ( int i = 0; i < Consts.DEFAULT_REPLAY_LABEL_LIST.size(); i++ )
			checkedNames.add( i >= labelNames.size() || Consts.DEFAULT_REPLAY_LABEL_LIST.get( i ).equals( labelNames.get( i ) ) ? "" : ServletApi.trimStringLength( labelNames.get( i ), 500 ) );
		
		account.setLabelNames( checkedNames );
		
		final RpcResult< List< String > > rpcResult = new RpcResult< List< String > >( ServerUtils.getLabelNames( account ) );
		rpcResult.setInfoMsg( "Label names saved." );
		
		return rpcResult;
		
	} finally {
		if ( pm != null )
			pm.close();
	}
}
 
Example #28
Source File: LoginServlet.java    From appengine-java-vm-runtime with Apache License 2.0 5 votes vote down vote up
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
  res.setContentType("text/html");
  res.getWriter().println("<html>");
  res.getWriter().println("<head>");
  res.getWriter().println("<title>whoami</title>");
  res.getWriter().println("</head>");
  res.getWriter().println("<body>");

  UserService userService = UserServiceFactory.getUserService();

  if (userService.isUserLoggedIn()) {
    User user = userService.getCurrentUser();

    res.getWriter().println("<h1>You are " + user.getNickname() + ".</h1>");

    if (userService.isUserAdmin()) {
      res.getWriter().println("<h2>You are an admin! :)</h2>");
    } else {
      res.getWriter().println("<h2>You are not an admin... :(</h2>");
    }

    res.getWriter().println("<h1>Your user ID is " + user.getUserId() + ".</h1>");
  } else {
    res.getWriter().println("<h1>You are not logged in.</h1>");
  }

  String destURL = "/whoami";
  String loginURL = userService.createLoginURL(destURL);
  String logoutURL = userService.createLogoutURL(destURL);

  res.getWriter().println("<br>");
  res.getWriter().println("<a href=\"" + loginURL + "\">login</a>");
  res.getWriter().println("<br>");
  res.getWriter().println("<a href=\"" + logoutURL + "\">logout</a>");
  res.getWriter().println("</body>");
  res.getWriter().println("</html>");
}
 
Example #29
Source File: UserServiceImpl.java    From sc2gears with Apache License 2.0 5 votes vote down vote up
@Override
public RpcResult< Void > recalcFileStats( final String sharedAccount ) {
	LOGGER.fine( sharedAccount == null ? "" : "Shared account: " + sharedAccount );
	
	final UserService userService = UserServiceFactory.getUserService();
	final User user = userService.getCurrentUser();
	if ( user == null )
		return RpcResult.createNotLoggedInErrorResult();
	
	PersistenceManager pm = null;
	try {
		
		pm = PMF.get().getPersistenceManager();
		
		final Key accountKey = ServerUtils.getAccountKey( pm, sharedAccount, user, Permission.VIEW_QUOTA );
		if ( accountKey == null )
			return RpcResult.createNoPermissionErrorResult();
		
		final Event lastRecalcEvent = ServerUtils.getLastEvent( accountKey, Type.FILE_STATS_RECALC_TRIGGERED );
		if ( lastRecalcEvent != null && System.currentTimeMillis() - lastRecalcEvent.getDate().getTime() < 24L*60*60*1000 ) {
			final int hours = (int) ( ( System.currentTimeMillis() - lastRecalcEvent.getDate().getTime() ) / (1000L*60*60) );
			return RpcResult.createErrorResult( "Recalculation can only be requested once per 24 hours"
				+ " (last was " + hours + ( hours == 1 ? " hour ago)!" : " hours ago)!" ) );
		}
		
		TaskServlet.register_recalcFileStatsTask( accountKey );
		
		pm.makePersistent( new Event( accountKey, Type.FILE_STATS_RECALC_TRIGGERED ) );
		
	} finally {
		if ( pm != null )
			pm.close();
	}
	
	return RpcResult.createInfoResult( "File stats recalculation has been kicked-off, check back in a short time..." );
}
 
Example #30
Source File: UserServiceImpl.java    From sc2gears with Apache License 2.0 5 votes vote down vote up
@Override
public RpcResult< String > getAuthorizationKey( final String sharedAccount ) {
	LOGGER.fine( sharedAccount == null ? "" : "Shared account: " + sharedAccount );
	
	final UserService userService = UserServiceFactory.getUserService();
	final User user = userService.getCurrentUser();
	if ( user == null )
		return RpcResult.createNotLoggedInErrorResult();
	
	PersistenceManager pm = null;
	try {
		
		pm = PMF.get().getPersistenceManager();
		
		final Account account = ServerUtils.getAccount( pm, sharedAccount, user );
		
		if ( account == null )
			return RpcResult.createNoPermissionErrorResult();
		if ( sharedAccount != null && !account.isPermissionGranted( user, Permission.VIEW_AUTHORIZATION_KEY ) )
			return RpcResult.createNoPermissionErrorResult();
		
		return new RpcResult< String >( account.getAuthorizationKey() );
		
	} finally {
		if ( pm != null )
			pm.close();
	}
}