Java Code Examples for com.google.appengine.api.users.UserService#getCurrentUser()

The following examples show how to use com.google.appengine.api.users.UserService#getCurrentUser() . 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: 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 2
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 3
Source File: AdminServiceImpl.java    From sc2gears with Apache License 2.0 5 votes vote down vote up
@Override
public RpcResult< String > executeMiscFunction( final boolean autoTx, final String functionName, final String[] params ) {
	final StringBuilder paramsBuilder = new StringBuilder( "[" );
	for ( final String param : params ) {
		if ( paramsBuilder.length() > 1 )
			paramsBuilder.append( ", " );
		paramsBuilder.append( param );
	}
	paramsBuilder.append( ']' );
	LOGGER.fine( "Auto Tx: " + autoTx + ", Function name: " + functionName + ", params: " + paramsBuilder );
	
	final UserService userService = UserServiceFactory.getUserService();
	final User user = userService.getCurrentUser();
	if ( user == null )
		return RpcResult.createNotLoggedInErrorResult();
	if ( !userService.isUserAdmin() )
		return RpcResult.createNoPermissionErrorResult();
	
	final DatastoreTask miscFunction = miscFunctionMap.get( functionName );
	if ( miscFunction == null ) {
		LOGGER.warning( "Invalid function name!" );
		return RpcResult.createErrorResult( "Invalid function name!" );
	}
	
	PersistenceManager pm = null;
	try {
		
		pm = ( autoTx ? PMF.getAutoTx() : PMF.getNoAutoTx() ).getPersistenceManager();
		
		final long start = System.nanoTime();
		String result = miscFunction.execute( getThreadLocalRequest(), pm, params );
		final long end = System.nanoTime();
		
		return new RpcResult< String >( "[" + ServerUtils.DECIMAL_FORMAT.format( ( end - start ) / 1000000l ) + " ms] Execution result: " + result );
		
	} finally {
		if ( pm != null )
			pm.close();
	}
}
 
Example 4
Source File: SignGuestbookServlet.java    From appengine-java-vm-guestbook-extras with Apache License 2.0 5 votes vote down vote up
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {
    UserService userService = UserServiceFactory.getUserService();
    User user = userService.getCurrentUser();

    String code = (String) req.getParameter("ccode");
    String captcha = (String) req.getSession().getAttribute("captcha");
    if (captcha != null && code != null) {
        if (!captcha.trim().equalsIgnoreCase(code)) {
            resp.getWriter().println("<html><head><title>error</title></head><body>error in captcha." +
                "<br/><a href='/guestbook.jsp'>Try again</a>.</body></html>");
            return;
        }
    }
    else {
        resp.getWriter().println("error in captcha");
        return;
    }

    String guestbookName = req.getParameter("guestbookName");
    Key guestbookKey = KeyFactory.createKey("Guestbook", guestbookName);
    String content = req.getParameter("content");
    Date date = new Date();
    Entity greeting = new Entity("Greeting", guestbookKey);
    greeting.setProperty("user", user);
    greeting.setProperty("date", date);
    content = content.substring(0, Math.min(content.length(), 490));
    greeting.setProperty("content", content);

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

    resp.sendRedirect("/guestbook.jsp?guestbookName=" + guestbookName);
}
 
Example 5
Source File: ApiUserServiceImpl.java    From sc2gears with Apache License 2.0 5 votes vote down vote up
@Override
public RpcResult< SettingsInfo > getSettings( 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();
		
		final SettingsInfo settingsInfo = new SettingsInfo();
		settingsInfo.setGoogleAccount       ( apiAccount.getUser                ().getEmail() );
		settingsInfo.setContactEmail        ( apiAccount.getContactEmail        ()            );
		settingsInfo.setUserName            ( apiAccount.getName                ()            );
		settingsInfo.setNotificationAvailOps( apiAccount.getNotificationAvailOps()            );
		return new RpcResult< SettingsInfo >( settingsInfo );
		
	} finally {
		if ( pm != null )
			pm.close();
	}
}
 
Example 6
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 7
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 8
Source File: SignGuestbookServlet.java    From appengine-java-vm-guestbook-extras with Apache License 2.0 5 votes vote down vote up
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {
    UserService userService = UserServiceFactory.getUserService();
    User user = userService.getCurrentUser();

    String code = (String) req.getParameter("ccode");
    String captcha = (String) req.getSession().getAttribute("captcha");
    if (captcha != null && code != null) {
        if (!captcha.trim().equalsIgnoreCase(code)) {
            resp.getWriter().println("<html><head><title>error</title></head><body>error in captcha." +
                "<br/><a href='/guestbook.jsp'>Try again</a>.</body></html>");
            return;
        }
    }
    else {
        resp.getWriter().println("error in captcha");
        return;
    }

    String guestbookName = req.getParameter("guestbookName");
    Key guestbookKey = KeyFactory.createKey("Guestbook", guestbookName);
    String content = req.getParameter("content");
    Date date = new Date();
    Entity greeting = new Entity("Greeting", guestbookKey);
    greeting.setProperty("user", user);
    greeting.setProperty("date", date);
    content = content.substring(0, Math.min(content.length(), 490));
    greeting.setProperty("content", content);

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

    resp.sendRedirect("/guestbook.jsp?guestbookName=" + guestbookName);
}
 
Example 9
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 10
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 11
Source File: XSRFTokenUtility.java    From solutions-mobile-backend-starter-java with Apache License 2.0 4 votes vote down vote up
private static String buildTokenString(String secretKey, String action, String time) {
  UserService userService = UserServiceFactory.getUserService();
  User user = userService.getCurrentUser();

  return buildTokenString(secretKey, user.getEmail(), action, time);
}
 
Example 12
Source File: AdminServiceImpl.java    From sc2gears with Apache License 2.0 4 votes vote down vote up
@Override
public RpcResult< List< ApiCallStatInfo > > getApiCallStatInfoList( final String googleAccount ) {
	LOGGER.fine( "For Google account: " + googleAccount);
	
	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 JQBuilder< ApiCallStat > q = new JQBuilder<>( pm, ApiCallStat.class ).range( 0, 1000 );
		
		final Object[] queryParams;
		if ( googleAccount != null && !googleAccount.isEmpty() ) {
			@SuppressWarnings( "unchecked" )
			final List< Key > apiAccountKey = (List< Key >) pm.newQuery( "select key from " + ApiAccount.class.getName() + " where user==:1" ).execute( new User( googleAccount, "gmail.com" ) );
			if ( apiAccountKey.isEmpty() )
				return new RpcResult< List<ApiCallStatInfo> >( new ArrayList< ApiCallStatInfo >( 0 ) );
			
			q.filter( "ownerKey==p1 && day==p2", "KEY p1, String p2" );
			queryParams = new Object[] { apiAccountKey.get( 0 ), ApiCallStat.DAY_TOTAL };
		}
		else {
			q.filter( "day==p1", "String p1" );
			queryParams = new Object[] { ApiCallStat.DAY_TOTAL };
		}
		
		// To keep track of total
		final ApiCallStatInfo totalApiCallStatInfo = new ApiCallStatInfo();
		totalApiCallStatInfo.setGoogleAccount( "TOTAL: ∑ ALL" );
		
		final List< ApiCallStatInfo > apiCallStatInfoList = new ArrayList< ApiCallStatInfo >();
		// First add the total info record
		apiCallStatInfoList.add( totalApiCallStatInfo );
		
		while ( true ) {
			final List< ApiCallStat > apiCallStatList = q.get( queryParams );
			
			for ( final ApiCallStat apiCallStat : apiCallStatList ) {
				final ApiCallStatInfo info = new ApiCallStatInfo();
				
				final ApiAccount apiAccount  = pm.getObjectById( ApiAccount.class, apiCallStat.getOwnerKey() );
				info.setGoogleAccount   ( apiAccount .getUser().getEmail () );
				info.setPaidOps         ( apiAccount .getPaidOps         () );
				ServerUtils.integrateApiCallStatIntoInfo( info, apiCallStat );
				apiCallStatInfoList.add( info );
				
				// Keep track of totals
				totalApiCallStatInfo.integrateApiCallStat( info );
				totalApiCallStatInfo.setPaidOps( totalApiCallStatInfo.getPaidOps() + info.getPaidOps() );
			}
			
			if ( apiCallStatList.size() < 1000 )
				break;
			
			q.cursor( apiCallStatList );
		}
		
		Collections.sort( apiCallStatInfoList, new Comparator< ApiCallStatInfo >() {
			@Override
			public int compare( final ApiCallStatInfo i1, final ApiCallStatInfo i2 ) {
				return new Long( i2.getUsedOps() ).compareTo( i1.getUsedOps() );
			}
		} );
		
		return new RpcResult< List<ApiCallStatInfo> >( apiCallStatInfoList );
		
	} finally {
		if ( pm != null )
			pm.close();
	}
}
 
Example 13
Source File: UserServiceImpl.java    From sc2gears with Apache License 2.0 4 votes vote down vote up
@Override
public RpcResult< ReplayFullInfo > getReplayFullInfo( final String sharedAccount, final String sha1 ) {
	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_REPLAYS );
		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 );
		
		final ReplayFullInfo replayFullInfo = new ReplayFullInfo();
		
		ServerUtils.copyReplayToReplayInfo( replay, replayFullInfo );
		
		replayFullInfo.setFormat          ( replay.getFormat () );
		replayFullInfo.setUploadedDate    ( replay.getDate   () );
		replayFullInfo.setFileSize        ( replay.getSize   () );
		replayFullInfo.setFileLastModified( replay.getLastmod() );
		replayFullInfo.setFileSize        ( replay.getSize   () );
		
		return new RpcResult< ReplayFullInfo >( replayFullInfo );
		
	} finally {
		if ( pm != null )
			pm.close();
	}
}
 
Example 14
Source File: UserServiceInfo.java    From appengine-angular-guestbook-java with Apache License 2.0 4 votes vote down vote up
public static UserServiceInfo get(String path) {
  UserService userService = UserServiceFactory.getUserService();
  return new UserServiceInfo(userService.getCurrentUser(), userService.createLoginURL(path),
      userService.createLogoutURL(path));
}
 
Example 15
Source File: UserServiceImpl.java    From sc2gears with Apache License 2.0 4 votes vote down vote up
@Override
public RpcResult< MousePrintFullInfo > getMousePrintFullInfo( final String sharedAccount, final String sha1 ) {
	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_MOUSE_PRINTS );
		if ( accountKey == null )
			return RpcResult.createNoPermissionErrorResult();
		
		final List< Smpd > mousePrintList = new JQBuilder<>( pm, Smpd.class ).filter( "ownerk==p1 && sha1==p2", "KEY p1, String p2" ).get( accountKey, sha1 );
		if ( mousePrintList.isEmpty() )
			return RpcResult.createNoPermissionErrorResult();
		
		final Smpd mousePrint = mousePrintList.get( 0 );
		
		final MousePrintFullInfo mousePrintFullInfo = new MousePrintFullInfo();
		
		mousePrintFullInfo.setRecordingStart( mousePrint.getStart () );
		mousePrintFullInfo.setRecordingEnd  ( mousePrint.getEnd   () );
		mousePrintFullInfo.setScreenWidth   ( mousePrint.getWidth () );
		mousePrintFullInfo.setScreenHeight  ( mousePrint.getHeight() );
		mousePrintFullInfo.setFileSize      ( mousePrint.getSize  () );
		mousePrintFullInfo.setSamplesCount  ( mousePrint.getCount () );
		mousePrintFullInfo.setSha1          ( mousePrint.getSha1  () );
		mousePrintFullInfo.setFileName      ( mousePrint.getFname () );
		
		mousePrintFullInfo.setUploadedDate        ( mousePrint.getDate   () );
		mousePrintFullInfo.setSamplingTime        ( mousePrint.getTime   () );
		mousePrintFullInfo.setFileLastModified    ( mousePrint.getLastmod() );
		mousePrintFullInfo.setVersion             ( mousePrint.getVer    () );
		mousePrintFullInfo.setScreenResolution    ( mousePrint.getRes    () );
		mousePrintFullInfo.setUncompressedDataSize( mousePrint.getUdsize () );
		mousePrintFullInfo.setSavedWithCompression( mousePrint.getCompr  () );
		
		return new RpcResult< MousePrintFullInfo >( mousePrintFullInfo );
		
	} finally {
		if ( pm != null )
			pm.close();
	}
}
 
Example 16
Source File: ApiUserServiceImpl.java    From sc2gears with Apache License 2.0 4 votes vote down vote up
@Override
public RpcResult< QuotaAndPaymentsInfo > getQuotaAndPaymentsInfo( 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();
		
		final List< ApiCallStat > apiCallStatList = new JQBuilder<>( pm, ApiCallStat.class ).filter( "ownerKey==p1 && day==p2", "KEY p1, String p2" ).get( apiAccount.getKey(), ApiCallStat.DAY_TOTAL );
		
		final List< ApiPayment > apiPaymentList = new JQBuilder<>( pm, ApiPayment.class ).filter( "apiAccountKey==p1", "KEY p1" ).desc( "date" ).get( apiAccount.getKey() );
		
		final QuotaAndPaymentsInfo quotaAndPaymentsInfo = new QuotaAndPaymentsInfo();
		quotaAndPaymentsInfo.setPaidOps( apiAccount.getPaidOps() );
		quotaAndPaymentsInfo.setUsedOps( apiCallStatList.isEmpty() ? 0 : apiCallStatList.get( 0 ).getUsedOps() );
		final List< ApiPaymentInfo > apiPaymentInfoList = new ArrayList< ApiPaymentInfo >( apiPaymentList.size() );
		for ( final ApiPayment apiPayment : apiPaymentList ) {
			final ApiPaymentInfo apiPaymentInfo = new ApiPaymentInfo();
			apiPaymentInfo.setDate         ( apiPayment.getDate         () );
			apiPaymentInfo.setPaymentSender( apiPayment.getPaypalAccount() == null || apiPayment.getPaypalAccount().isEmpty() ? apiPayment.getBankAccount() : apiPayment.getPaypalAccount() );
			apiPaymentInfo.setGrossPayment ( apiPayment.getGrossPayment () );
			apiPaymentInfo.setNetPayment   ( apiPayment.getNetPayment   () );
			apiPaymentInfo.setPaidOps      ( apiPayment.getPaidOps      () );
			apiPaymentInfoList.add( apiPaymentInfo );
		}
		quotaAndPaymentsInfo.setApiPaymentInfoList( apiPaymentInfoList );
		
		return new RpcResult< QuotaAndPaymentsInfo >( quotaAndPaymentsInfo );
		
	} finally {
		if ( pm != null )
			pm.close();
	}
}
 
Example 17
Source File: UserServiceImpl.java    From sc2gears with Apache License 2.0 4 votes vote down vote up
@Override
public RpcResult< FileStatInfo > getFileStatInfo( 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 FileStatInfo fileStatInfo = new FileStatInfo();
		
		// File stats
		final List< FileStat > fileStatList = new JQBuilder<>( pm, FileStat.class ).filter( "ownerKey==p1", "KEY p1" ).get( account.getKey() );
		final FileStat fileStat = fileStatList.isEmpty() ? null : fileStatList.get( 0 );
		if ( fileStat != null ) {
			fileStatInfo.setHasFileStat ( true                       );
			fileStatInfo.setAllCount    ( fileStat.getCount       () );
			fileStatInfo.setAllStorage  ( fileStat.getStorage     () );
			fileStatInfo.setRepCount    ( fileStat.getRepCount    () );
			fileStatInfo.setRepStorage  ( fileStat.getRepStorage  () );
			fileStatInfo.setSmpdCount   ( fileStat.getSmpdCount   () );
			fileStatInfo.setSmpdStorage ( fileStat.getSmpdStorage () );
			fileStatInfo.setOtherCount  ( fileStat.getOtherCount  () );
			fileStatInfo.setOtherStorage( fileStat.getOtherStorage() );
			fileStatInfo.setRecalced    ( fileStat.getRecalced    () );
		}
		
		fileStatInfo.setPaidStorage( account.getPaidStorage() );
		final DbPackage dbPackage = DbPackage.getFromStorage( account.getPaidStorage() );
		if ( dbPackage != null ) {
			fileStatInfo.setDbPackageName( dbPackage.name );
			fileStatInfo.setDbPackageIcon( ServerUtils.getDbPackageIcon( dbPackage, account.getPaidStorage(), fileStatInfo.getAllStorage() ) );
		}
		
		return new RpcResult< FileStatInfo >( fileStatInfo );
		
	} finally {
		if ( pm != null )
			pm.close();
	}
}
 
Example 18
Source File: UserServiceImpl.java    From sc2gears with Apache License 2.0 4 votes vote down vote up
@Override
public RpcResult< Void > saveSettings( final String sharedAccount, final SettingsInfo settingsInfo ) {
	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.CHANGE_SETTINGS ) )
			return RpcResult.createNoPermissionErrorResult();
		
		if ( settingsInfo.getContactEmail() != null && !settingsInfo.getContactEmail().isEmpty() )
			if ( !ServerUtils.isEmailValid( settingsInfo.getContactEmail() ) )
				return RpcResult.createErrorResult( "Invalid contact email!" );
		
		if ( settingsInfo.getNotificationQuotaLevel() < 50 || settingsInfo.getNotificationQuotaLevel() > 100 )
			return RpcResult.createErrorResult( "Invalid notification quota level! (Must be between 50 and 100!)" );
		
		account.setContactEmail          ( settingsInfo.getContactEmail() == null || settingsInfo.getContactEmail().isEmpty() ? null : ServletApi.trimStringLength( settingsInfo.getContactEmail(), 500 ) );
		account.setName                  ( settingsInfo.getUserName    () == null || settingsInfo.getUserName    ().isEmpty() ? null : ServletApi.trimStringLength( settingsInfo.getUserName    (), 500 ) );
		account.setNotificationQuotaLevel( settingsInfo.getNotificationQuotaLevel() );
		account.setConvertToRealTime     ( settingsInfo.isConvertToRealTime      () );
		account.setMapImageSize          ( settingsInfo.getMapImageSize          () );
		account.setDisplayWinners        ( settingsInfo.getDisplayWinners        () );
		account.setFavoredPlayers        ( settingsInfo.getFavoredPlayerList     () );
		
		if ( settingsInfo.getGrantedUsers().size() != settingsInfo.getGrantedPermissions().size() )
			return RpcResult.createErrorResult( "Bad request!" );
		
		if ( settingsInfo.getGrantedUsers().size() > 100 )
			return RpcResult.createErrorResult( "Maximum 100 granted users allowed!" );
		
		// Sort granted users by their Google account
		final List< Object[] > grantedPairs = new ArrayList< Object[] >( settingsInfo.getGrantedUsers().size() );
		final Set< String > grantedUserSet = new HashSet< String >( settingsInfo.getGrantedUsers().size() );
		for ( int i = 0; i < settingsInfo.getGrantedUsers().size(); i++ ) {
			final String grantedGoogleAccount = settingsInfo.getGrantedUsers().get( i );
			// Do not allow duplicates:
			if ( !grantedUserSet.add( grantedGoogleAccount ) )
				return RpcResult.createErrorResult( "Duplicate granted Google account: " + grantedGoogleAccount );
			grantedPairs.add( new Object[] { grantedGoogleAccount, settingsInfo.getGrantedPermissions().get( i ) } );
		}
		Collections.sort( grantedPairs, new Comparator< Object[] >() {
			@Override
               public int compare( final Object[] p1, final Object[] p2 ) {
                return String.CASE_INSENSITIVE_ORDER.compare( (String) p1[ 0 ], (String) p2[ 0 ] );
               }
		} );
		
		final List< User > grantedUsers       = new ArrayList< User >( grantedPairs.size() );
		final List< Long > grantedPermissions = new ArrayList< Long >( grantedPairs.size() );
		for ( final Object[] grantedPair : grantedPairs ) {
			if ( !ServerUtils.isEmailValid( (String) grantedPair[ 0 ] ) )
				return RpcResult.createErrorResult( "Invalid Google account: " + (String) grantedPair[ 0 ] );
			grantedUsers.add( new User( (String) grantedPair[ 0 ], "gmail.com" ) );
			grantedPermissions.add( (Long) grantedPair[ 1 ] );
		}
		account.setGrantedUsers      ( grantedUsers       );
		account.setGrantedPermissions( grantedPermissions );
		
	} finally {
		if ( pm != null )
			pm.close();
	}
	
	return RpcResult.createInfoResult( "Settings saved successfully." );
}
 
Example 19
Source File: UserServiceImpl.java    From sc2gears with Apache License 2.0 4 votes vote down vote up
@Override
  public RpcResult< Void > register( final FreeAccountInfo freeAccountInfo ) {
final UserService userService = UserServiceFactory.getUserService();
final User user = userService.getCurrentUser();
if ( user == null )
	return RpcResult.createNotLoggedInErrorResult();

if ( freeAccountInfo.getGoogleAccount() == null || freeAccountInfo.getGoogleAccount().isEmpty() )
	return RpcResult.createErrorResult( "Google account is required! Refresh the page!" );

if ( !ServerUtils.isEmailValid( freeAccountInfo.getGoogleAccount() ) )
	return RpcResult.createErrorResult( "Invalid Google account! Refresh the page!" );

if ( !user.getEmail().equals( freeAccountInfo.getGoogleAccount() ) )
	return RpcResult.createErrorResult( "Google account does not match the user you're logged in with! Refresh the page!" );

if ( freeAccountInfo.getContactEmail() != null && freeAccountInfo.getContactEmail().length() > 500 )
	return RpcResult.createErrorResult( "Invalid contact email, cannot be longer than 500 characters!" );

if ( freeAccountInfo.getContactEmail() != null && !freeAccountInfo.getContactEmail().isEmpty() )
	if ( !ServerUtils.isEmailValid( freeAccountInfo.getContactEmail() ) )
		return RpcResult.createErrorResult( "Invalid contact email!" );

if ( freeAccountInfo.getName() != null && freeAccountInfo.getName().length() > 500 )
	return RpcResult.createErrorResult( "Invalid name, cannot be longer than 500 characters!" );

PersistenceManager pm = null;
try {
	
	pm = PMF.get().getPersistenceManager();
	
	if ( !( (List< ? >) pm.newQuery( "select key from " + Account.class.getName() + " where user==:1" ).execute( user ) ).isEmpty() )
		return RpcResult.createErrorResult( "There is already an account with this Google account! Refresh the page!" );
	
	// REGISTRATION IS DISABLED.
	if ( true )
		return RpcResult.createErrorResult( "Registration is disabled!" );
	
	// Create and save account
	final Account account = new Account( user );
	ServerUtils.initializeNewAccount( pm, account );
	if ( freeAccountInfo.getName() != null && !freeAccountInfo.getName().isEmpty() )
		account.setName( freeAccountInfo.getName() );
	if ( freeAccountInfo.getContactEmail() != null && !freeAccountInfo.getContactEmail().isEmpty() )
		account.setContactEmail( freeAccountInfo.getContactEmail() );
	account.setCountry( ServerUtils.countryCodeToName( getThreadLocalRequest().getHeader( "X-AppEngine-Country" ) ) );
	pm.makePersistent( account );
	
	// Email will be sent by the TaskServlet:
	TaskServlet.register_updatePackageTask( account.getKey() );
	
} finally {
	if ( pm != null )
		pm.close();
}

   return new RpcResult< Void >();
  }
 
Example 20
Source File: MapImageServlet.java    From sc2gears with Apache License 2.0 4 votes vote down vote up
@Override
protected void doGet( final HttpServletRequest request, final HttpServletResponse response ) throws ServletException, IOException {
	// Restrict map image download for logged in Google accounts
   	// This simple check does not require datastore read but will prevent
   	// images to get "stolen" by simple downloader apps...
   	final UserService userService = UserServiceFactory.getUserService();
	final User        user        = userService.getCurrentUser();
	if ( user == null ) {
		LOGGER.warning( "Unauthorized access, not logged in!" );
		response.sendError( HttpServletResponse.SC_FORBIDDEN, "Unauthorized access, you are not logged in!" );
		return;
	}
	
	String mapFileName = request.getPathInfo();
	if ( mapFileName != null && !mapFileName.isEmpty() )
		mapFileName = mapFileName.substring( 1 ); // Cut off leading slash
	
	if ( mapFileName == null ) {
		LOGGER.warning( "Missing map file name!" );
		response.sendError( HttpServletResponse.SC_BAD_REQUEST, "Missing map file name!" );
		return;
	}
	if ( ( mapFileName = ServerUtils.checkMapFileName( mapFileName ) ) == null ) {
		LOGGER.warning( "Invalid map file name!" );
		response.sendError( HttpServletResponse.SC_BAD_REQUEST, "Invalid map file name!" );
		return;
	}
	
	PersistenceManager pm = null;
	try {
		pm = PMF.get().getPersistenceManager();
		
		final List< Map > mapList = new JQBuilder<>( pm, Map.class ).filter( "fname==p1", "String p1" ).get( mapFileName );
		
		if ( mapList.isEmpty() ) {
			// Register a task to process the map
			TaskServlet.register_processMapTask( mapFileName );
			
			// Serve "processing" image
			LOGGER.fine( "Response: Processing image..." );
			setNoCache( response );
			getServletContext().getRequestDispatcher( "/images/fugue/hourglass.png" ).forward( request, response );
		}
		else {
			final Map map = mapList.get( 0 );
			
			switch ( map.getStatus() ) {
			case Map.STATUS_READY :
				// Serve the image
				response.setContentType( "image/jpeg" );
				response.setDateHeader( "Expires", new Date().getTime() + 60L*24*60*60*1000 ); // 60 days cache time
				response.addHeader( "Cache-Control", "private, max-age=5184000" ); // 5_184_000 sec = 60 days cache time
				response.getOutputStream().write( map.getImage().getBytes() );
				break;
			case Map.STATUS_PROCESSING :
				// Serve "processing" image
				LOGGER.fine( "Response: Processing image..." );
				setNoCache( response );
				getServletContext().getRequestDispatcher( "/images/fugue/hourglass.png" ).forward( request, response );
				break;
			default :
				// Serve "N/A" image
				LOGGER.fine( "Response: N/A" );
				setNoCache( response );
				getServletContext().getRequestDispatcher( "/images/fugue/na.png"        ).forward( request, response );
				break;
			}
		}
		
	} finally {
		if ( pm != null )
			pm.close();
	}
}