Esempio n. 1
0
        public async Task <ActionResult <AdView> > EditAdAsync([FromBody] AdEditRequest adEditRequest)
        {
            var currentUserId = GetCurrentUserId();

            try
            {
                var editedAd = await adManager.EditAsync(adEditRequest, currentUserId);

                return(Ok(await editedAd
                          .AttachCurrentUserId(mapper.ConfigurationProvider, GetCurrentUserId())
                          .ProjectTo <AdView>(mapper.ConfigurationProvider)
                          .SingleAsync()));
            }
            catch (ArgumentNullException ane)
            {
                logger.LogDebug(ane.Message + "\n" + ane.StackTrace);
                return(NotFound($"Can't find ad {adEditRequest.Id}"));
            }
            catch (MethodAccessException mae)
            {
                logger.LogDebug(mae.Message + "\n" + mae.StackTrace);
                logger.LogDebug($"Current user {currentUserId} has no rights to edit ad {adEditRequest.Id}");
                return(Forbid(JwtBearerDefaults.AuthenticationScheme, CookieAuthenticationDefaults.AuthenticationScheme));
            }
            catch (Exception ex)
            {
                logger.LogDebug(ex.Message + "\n" + ex.StackTrace);
                return(StatusCode(500));
            }
        }
Esempio n. 2
0
        public async Task <IQueryable <Ad> > EditAsync(AdEditRequest adEditRequest, Guid userId)
        {
            Ad adToEdit = await Ads.FirstOrDefaultAsync(ad => ad.Id == adEditRequest.Id)
                          ?? throw new ArgumentNullException();

            if (adToEdit.OrganizationId.HasValue)
            {
                bool hasRight = await dbContext.Organizations
                                .Where(org => org.Id == adToEdit.OrganizationId.Value)
                                .SelectMany(org => org.Users)
                                .Where(u => u.UserId == userId)
                                .AnyAsync(userorgright => userorgright.UserOrganizationRight.RightName == Configure.OrganizationRights.CanEditAd.ToString());

                if (!hasRight)
                {
                    throw new MethodAccessException();
                }

                logger.LogDebug($"Current user {userId} edited ad {adToEdit.Id} in organization {adToEdit.OrganizationId.Value}");
            }
            else
            {
                if (adToEdit.UserId.Value != userId)
                {
                    throw new MethodAccessException();
                }
            }

            mapper.Map(adEditRequest, adToEdit);

            dbContext.Ads.Update(adToEdit);
            await dbContext.SaveChangesAsync();

            return(dbContext.Ads
                   .Where(ad => ad.Id == adToEdit.Id));
        }