public async Task <IQueryable <Ad> > AddAsync(AdCreateRequest adCreateRequest, Guid userId) { var newAd = mapper.Map <Ad>(adCreateRequest); if (newAd.OrganizationId.HasValue) { // check if such organization exists bool exist = await dbContext.Organizations .Where(org => org.Id == newAd.OrganizationId.Value) .AnyAsync(); if (!exist) { throw new ArgumentNullException(); } // check if user has rights to create ads in organization bool hasRight = await dbContext.Organizations .Where(org => org.Id == newAd.OrganizationId.Value) .SelectMany(org => org.Users) .Where(u => u.UserId == userId && u.OrganizationId == newAd.OrganizationId.Value) .AnyAsync(userorgright => userorgright.UserOrganizationRight.RightName == Configure.OrganizationRights.CanEditAd.ToString()); if (!hasRight) { throw new MethodAccessException(); } Organization creator = await dbContext.Organizations .FirstOrDefaultAsync(org => org.Id == newAd.OrganizationId.Value); newAd.Organization = creator; logger.LogDebug($"Current user {userId} created ad '{newAd.Id}' in organization {newAd.OrganizationId.Value}"); } else { User creator = await userManager.FindByIdAsync(userId.ToString()) ?? throw new ArgumentNullException(); newAd.User = creator; } newAd.CreationTime = DateTime.UtcNow; await dbContext.Ads.AddAsync(newAd); await dbContext.SaveChangesAsync(); return(dbContext.Ads .Where(ad => ad.Id == newAd.Id)); }
public async Task <ActionResult <AdView> > CreateAdAsync([FromBody] AdCreateRequest adCreateRequest) { var currentUserId = GetCurrentUserId(); try { var createdAd = await adManager.AddAsync(adCreateRequest, currentUserId); AdView newAd = await createdAd .AttachCurrentUserId(mapper.ConfigurationProvider, GetCurrentUserId()) .ProjectTo <AdView>(mapper.ConfigurationProvider) .SingleAsync(); return(Ok(newAd)); } catch (ArgumentNullException ane) { logger.LogDebug(ane.Message + "\n" + ane.StackTrace); if (adCreateRequest.OrganizationId.HasValue) { logger.LogDebug($"Organization {adCreateRequest.OrganizationId.Value} doesn't exist in database"); return(NotFound($"Organization {adCreateRequest.OrganizationId.Value} doesn't exist in database")); } else { logger.LogDebug($"Current user {currentUserId} doesn't exist in database"); return(NotFound($"Current user {currentUserId} doesn't exist in database")); } } catch (MethodAccessException mae) { logger.LogDebug(mae.Message + "\n" + mae.StackTrace); logger.LogDebug($"Current user {currentUserId} has no rights to create ads in organization {adCreateRequest.OrganizationId.Value}"); return(Forbid(JwtBearerDefaults.AuthenticationScheme, CookieAuthenticationDefaults.AuthenticationScheme)); } catch (Exception ex) { logger.LogDebug(ex.Message + "\n" + ex.StackTrace); return(StatusCode(500)); } }
public async Task <AdResponse> Post([FromForm] AdCreateRequest createRequest) { var newEntry = await _adService.PostNewAdAsync <AdResponse>(createRequest, UserId); return(newEntry); }