fixes the api/gcm/register call

main
Paul Schneider 10 years ago
parent d2bcbfb55a
commit 39f9157f8b
1 changed files with 36 additions and 26 deletions

@ -4,13 +4,15 @@ using Microsoft.AspNet.Authorization;
using Microsoft.AspNet.Mvc; using Microsoft.AspNet.Mvc;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Yavsc.Models; using Yavsc.Models;
using Yavsc.Models.Identity;
[Authorize,Route("~/api/gcm")] [Authorize, Route("~/api/gcm")]
public class GCMController : Controller { public class GCMController : Controller
{
ILogger _logger; ILogger _logger;
ApplicationDbContext _context; ApplicationDbContext _context;
public GCMController (ApplicationDbContext context, public GCMController(ApplicationDbContext context,
ILoggerFactory loggerFactory) ILoggerFactory loggerFactory)
{ {
_logger = loggerFactory.CreateLogger<GCMController>(); _logger = loggerFactory.CreateLogger<GCMController>();
@ -22,29 +24,37 @@ public class GCMController : Controller {
/// </summary> /// </summary>
/// <param name="declaration"></param> /// <param name="declaration"></param>
/// <returns></returns> /// <returns></returns>
public IActionResult Register (GoogleCloudMobileDeclaration declaration) [Authorize, HttpPost("register")]
public IActionResult Register(
[FromBody] GoogleCloudMobileDeclaration declaration)
{
var uid = User.GetUserId();
_logger.LogWarning($"Registering device with id:{declaration.DeviceId} for {uid}");
if (ModelState.IsValid)
{ {
if (declaration.DeviceOwnerId!=null)
if (User.GetUserId() != declaration.DeviceOwnerId)
return new BadRequestObjectResult(
new { error = "you're not allowed to register for another user" } 
);
declaration.DeviceOwnerId = User.GetUserId();
if (_context.GCMDevices.Any(d => d.DeviceId == declaration.DeviceId)) if (_context.GCMDevices.Any(d => d.DeviceId == declaration.DeviceId))
{ {
var alreadyRegisteredDevice = _context.GCMDevices.FirstOrDefault(d => d.DeviceId == declaration.DeviceId); var alreadyRegisteredDevice = _context.GCMDevices.FirstOrDefault(d => d.DeviceId == declaration.DeviceId);
// Assert alreadyRegisteredDevice != null if (alreadyRegisteredDevice.DeviceOwnerId != uid)
if (alreadyRegisteredDevice != declaration) { {
_context.GCMDevices.Update(declaration); return new BadRequestObjectResult(new { error = $"Device owned by someone else {declaration.DeviceId}" });
}
alreadyRegisteredDevice.GCMRegistrationId = declaration.GCMRegistrationId;
alreadyRegisteredDevice.Model = declaration.Model;
alreadyRegisteredDevice.Platform = declaration.Platform;
alreadyRegisteredDevice.Version = declaration.Version;
_context.Update(alreadyRegisteredDevice);
_context.SaveChanges(); _context.SaveChanges();
} // else nothing to do.
} }
else else
{ {
declaration.DeviceOwnerId = uid;
_context.GCMDevices.Add(declaration); _context.GCMDevices.Add(declaration);
_context.SaveChanges(); _context.SaveChanges();
} }
return Ok(); return Ok();
} }
return new BadRequestObjectResult(ModelState);
}
} }
Loading…