Пример #1
0
        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);
        }
Пример #2
0
        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));
        }
Пример #3
0
 private bool AuthorizeUserToSelf(DbDialog dialog, DbUser user)
 {
     return(user.Id == dialog.UserId);
 }
Пример #4
0
 private bool AuthorizeUserToService(DbDialog dialog, DbUser user)
 {
     return(user.ServiceIds?.Contains(dialog.ServiceId) == true);
 }
Пример #5
0
 private bool AuthorizeUserToDialog(DbDialog dialog, DbUser user)
 {
     return(AuthorizeUserToSelf(dialog, user) || AuthorizeUserToService(dialog, user));
 }