public DbDialog GetOrCreate(DbDialog dialog) { using var context = contextFactory.Create(); var existingDialog = context.Dialogs.SingleOrDefault(x => x.UserId == dialog.UserId && x.ServiceId == dialog.ServiceId); if (existingDialog == null) { dialog.Id = Guid.NewGuid().ToString(); context.Dialogs.Add(dialog); context.SaveChanges(); } return(dialog); }
public IActionResult GetOrCreateDialog([FromQuery(Name = "user-id")] string?userId, [FromQuery(Name = "service-id")] string?serviceId) { if (string.IsNullOrEmpty(serviceId)) { return(BadRequest($"{nameof(DbDialog.ServiceId)} is required")); } if (string.IsNullOrEmpty(userId)) { return(BadRequest($"{nameof(DbDialog.UserId)} is required")); } var user = HttpContext.TryGetUser(); if (user == null) { throw new InvalidStateException("User should be not null"); } var dialog = new DbDialog { ServiceId = serviceId, UserId = userId }; if (!AuthorizeUserToDialog(dialog, user)) { return(BadRequest("You are not authorized to dialog")); } var dbDialog = dialogsRepository.GetOrCreate(new DbDialog { ServiceId = serviceId, UserId = userId }); return(Ok(dbDialog)); }
private bool AuthorizeUserToSelf(DbDialog dialog, DbUser user) { return(user.Id == dialog.UserId); }
private bool AuthorizeUserToService(DbDialog dialog, DbUser user) { return(user.ServiceIds?.Contains(dialog.ServiceId) == true); }
private bool AuthorizeUserToDialog(DbDialog dialog, DbUser user) { return(AuthorizeUserToSelf(dialog, user) || AuthorizeUserToService(dialog, user)); }