use of com.google.samples.apps.iosched.server.gcm.db.models.Device in project iosched by google.
the class SendMessageServlet method doPost.
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
// Extract URL components
String result = req.getPathInfo();
if (result == null) {
send(resp, 400, "Bad request (check request format)");
return;
}
String[] components = result.split("/");
if (components.length != 3) {
send(resp, 400, "Bad request (check request format)");
return;
}
String target = components[1];
String action = components[2];
// Let's see what this user is authorized to do
AuthInfo authInfo = AuthHelper.processAuthorization(req);
// If no auth info or non-admin trying to run non-whitelisted actions, no access.
if (authInfo == null || action == null || (!UNPRIVILEGED_ACTIONS.contains(action) && !authInfo.permAdmin)) {
send(resp, 403, "Not authorized");
return;
}
// Extract extraData
String payload = readBody(req);
// Request decoding complete. Log request parameters
LOG.info("Authorized User: " + authInfo.clientName + "\nTarget: " + target + "\nAction: " + action + "\nExtra Data: " + payload);
MessageSender sender = new MessageSender(getServletConfig());
// what's the audience of the message?
if ("global".equals(target)) {
// Only admins can spam the world
if (!authInfo.permAdmin) {
LOG.info("Attempt to send global message, but no admin perm.");
send(resp, 403, "Not authorized");
return;
}
List<Device> allDevices = DeviceStore.getAllDevices();
if (allDevices == null || allDevices.isEmpty()) {
send(resp, 404, "No devices registered");
} else {
int resultCount = allDevices.size();
LOG.info("Selected " + resultCount + " devices");
sender.multicastSend(allDevices, action, payload);
send(resp, 200, "Message queued: " + resultCount + " devices");
}
} else {
// If target is SELF, the GCM Group ID will be the auth key in header
if (SELF.equals(target)) {
// do we have permission to send message to self?
if (!authInfo.permSendSelfMessage) {
LOG.info("Attempt to send self message, but no self message perm.");
send(resp, 403, "Not authorized");
return;
}
// the target is the auth key (it represents the group)
target = authInfo.authKey;
} else {
// sending message to a specific user. Only admin can do it.
if (!authInfo.permAdmin) {
LOG.info("Attempt to send message to specific target, but no admin perm.");
send(resp, 403, "Not authorized");
return;
}
}
List<Device> userDevices = DeviceStore.findDevicesByGcmGroupId(target);
if (userDevices == null || userDevices.isEmpty()) {
send(resp, 404, "User not found");
} else {
int resultCount = userDevices.size();
LOG.info("Selected " + resultCount + " devices");
sender.multicastSend(userDevices, action, payload);
send(resp, 200, "Message queued: " + resultCount + " devices");
}
}
}
use of com.google.samples.apps.iosched.server.gcm.db.models.Device in project iosched by google.
the class FcmRegistrationEndpoint method unregister.
/**
* Remove a registration of a user's device. When a user signs out of a client they should
* unregister. This will prevent messages from being sent to the wrong user if multiple users
* are using the same device.
*
* @param deviceId FCM token representing the device.
* @return Result containing a message about the un-registration.
* @throws BadRequestException Thrown when there is no device ID in the request.
*/
@ApiMethod(path = "unregister", httpMethod = HttpMethod.POST)
public void unregister(User user, @Named(PARAMETER_DEVICE_ID) String deviceId) throws BadRequestException, UnauthorizedException, com.google.api.server.spi.response.NotFoundException, ForbiddenException {
// Check to see if deviceId.
if (Strings.isNullOrEmpty(deviceId)) {
// Drop request.
throw new BadRequestException("Invalid request: Request must contain " + PARAMETER_DEVICE_ID);
}
// Check that user making requests is non null.
if (user == null) {
throw new UnauthorizedException("Invalid credentials");
}
try {
Device device = ofy().load().type(Device.class).id(deviceId).safe();
// Check that the user trying to unregister the token is the same one that registered it.
if (!device.getUserId().equals(user.getId())) {
throw new ForbiddenException("Not authorized to unregister token");
}
DeviceStore.unregister(deviceId);
} catch (NotFoundException e) {
throw new com.google.api.server.spi.response.NotFoundException("Device ID: " + deviceId + " not found");
}
}
use of com.google.samples.apps.iosched.server.gcm.db.models.Device in project iosched by google.
the class FcmSendEndpoint method sendFeedPing.
/**
* Ping all users' devices to update UI indicating that the feed has been updated.
*
* @param context Servlet context (injected by Endpoints)
* @param user User making the request (injected by Endpoints)
*/
@ApiMethod(name = "sendFeedPing", path = "feed", clientIds = { Ids.SERVICE_ACCOUNT_CLIENT_ID })
public void sendFeedPing(ServletContext context, User user) throws UnauthorizedException {
validateServiceAccount(user);
MessageSender sender = new MessageSender(context);
List<Device> devices = DeviceStore.getAllDevices();
sender.multicastSend(devices, "feed_update", null);
}
use of com.google.samples.apps.iosched.server.gcm.db.models.Device in project iosched by google.
the class DeviceStore method register.
/**
* Registers a device.
*
* @param deviceId device's registration id.
*/
public static void register(String deviceId, String userId) {
LOG.info("Registering device.\nGroup ID: " + userId + "\nGCM ID: " + deviceId);
Device oldDevice = findDeviceByDeviceId(deviceId);
if (oldDevice == null) {
// Existing device not found (as expected)
Device newDevice = new Device();
newDevice.setDeviceId(deviceId);
newDevice.setUserId(userId);
ofy().save().entity(newDevice);
} else {
// Existing device found
LOG.warning(deviceId + " is already registered");
if (userId == null || !userId.equals(oldDevice.getUserId())) {
LOG.info("User ID has changed from '" + oldDevice.getUserId() + "' to '" + userId + "'");
oldDevice.setUserId(userId);
ofy().save().entity(oldDevice);
}
}
}
use of com.google.samples.apps.iosched.server.gcm.db.models.Device in project iosched by google.
the class FcmSendEndpoint method sendSelfSync.
/**
* Clients can initiate a sync on all of a user's devices. This will usually be called
* when a client pushes a user data update to the server and wants other clients to
* sync that change.
*
* @param context Servlet context (injected by Endpoints)
* @param user User requesting the sync (injected by Endpoints)
*/
@ApiMethod(name = "sendSelfSync", path = "self")
public void sendSelfSync(ServletContext context, User user) throws UnauthorizedException {
if (user == null) {
throw new UnauthorizedException(INVALID_CREDENTIALS_MSG);
}
MessageSender sender = new MessageSender(context);
String userId = user.getId();
List<Device> devices = DeviceStore.findDevicesByUserId(userId);
sender.multicastSend(devices, ACTION_SYNC_USER, null);
}
Aggregations