Ejemplo n.º 1
0
        public async Task TestInvalidFeedbackRejected()
        {
            Authenticate(
                new[] { new Claim("botId", "1") },
                Scopes.SCOPE_BOT
                );

            WithDatabase(dbContext =>
            {
                dbContext.Dashboards.Add(new DbDashboard {
                    Id = 1
                });
                dbContext.SaveChanges();
            });


            var request = new RegisterPostRequest
            {
                Title           = "My Title",
                ContentUrl      = "My Url",
                ContentId       = 1,
                ContentSite     = "stackoverflow.com",
                ContentType     = "comment",
                AllowedFeedback = new List <string> {
                    "tp"
                }
            };

            var result = await Client.PostAsync("/Bot/RegisterPost", request);

            await result.AssertError(HttpStatusCode.BadRequest, "Feedback 'tp' not registered for bot");
        }
Ejemplo n.º 2
0
        public async Task TestBotCanProvideFeedbackForUserWithReviewerRole()
        {
            Authenticate(
                new[] { new Claim("botId", "1") },
                Scopes.SCOPE_BOT
                );

            WithDatabase(dbContext =>
            {
                dbContext.Dashboards.Add(new DbDashboard {
                    Id = 1
                });
                dbContext.Users.Add(new Data.Models.DbUser()
                {
                    AccountId  = 1,
                    UserScopes = new List <DbUserScope> {
                        new DbUserScope {
                            ScopeName = Scopes.SCOPE_REVIEWER
                        }
                    }
                });
                dbContext.Feedbacks.Add(new Data.Models.DbFeedback()
                {
                    DashboardId = 1,
                    Name        = "tp"
                });
                dbContext.SaveChanges();
            });

            var registerPostRequest = new RegisterPostRequest
            {
                Title           = "My Title",
                ContentUrl      = "My Url",
                ContentId       = 1,
                ContentSite     = "stackoverflow.com",
                ContentType     = "comment",
                AllowedFeedback = new List <string> {
                    "tp"
                }
            };
            var result = await Client.PostAsync("/Bot/RegisterPost", registerPostRequest);

            await result.AssertSuccess();

            var reportId = JsonConvert.DeserializeObject <int>(await result.Content.ReadAsStringAsync());

            var feedbackResult = await Client.PostAsync("/Bot/RegisterUserFeedback", new RegisterUserFeedbackRequest
            {
                ReportId = reportId,
                UserId   = 1,
                Feedback = "tp"
            });

            await feedbackResult.AssertSuccess();
        }
Ejemplo n.º 3
0
        public async Task TestBlankContentUrlInvalid()
        {
            Authenticate(
                new[] { new Claim("botId", "1") },
                Scopes.SCOPE_BOT
                );

            var request = new RegisterPostRequest
            {
                Title      = "My Title",
                ContentUrl = ""
            };

            var result = await Client.PostAsync("/Bot/RegisterPost", request);

            await result.AssertError(HttpStatusCode.BadRequest, "ContentUrl is required");
        }
Ejemplo n.º 4
0
        public async Task TestBotInvalidFeedback()
        {
            Authenticate(
                new[] { new Claim("botId", "1") },
                Scopes.SCOPE_BOT
                );

            WithDatabase(dbContext =>
            {
                dbContext.Dashboards.Add(new DbDashboard {
                    Id = 1
                });
                dbContext.Feedbacks.Add(new Data.Models.DbFeedback()
                {
                    DashboardId = 1,
                    Name        = "tp"
                });
                dbContext.SaveChanges();
            });

            var registerPostRequest = new RegisterPostRequest
            {
                Title           = "My Title",
                ContentUrl      = "My Url",
                ContentId       = 1,
                ContentSite     = "stackoverflow.com",
                ContentType     = "comment",
                AllowedFeedback = new List <string> {
                    "tp"
                }
            };
            var result = await Client.PostAsync("/Bot/RegisterPost", registerPostRequest);

            await result.AssertSuccess();

            var reportId = JsonConvert.DeserializeObject <int>(await result.Content.ReadAsStringAsync());

            var userFeedbackResult = await Client.PostAsync("/Bot/RegisterUserFeedback", new RegisterUserFeedbackRequest
            {
                ReportId = reportId,
                UserId   = 1,
                Feedback = "fp"
            });

            await userFeedbackResult.AssertError(HttpStatusCode.BadRequest, "Feedback not allowed for report");
        }
Ejemplo n.º 5
0
        public async Task TestBlankTitleInvalid()
        {
            Authenticate(
                new[] { new Claim("botId", "1") },
                Scopes.SCOPE_BOT
                );

            var request = new RegisterPostRequest
            {
                Title      = "",
                ContentUrl = "http://www.google.com"
            };

            var response = await Client.PostAsync("/Bot/RegisterPost", request);

            await response.AssertError(HttpStatusCode.BadRequest, "Title is required");
        }
        public async Task <IActionResult> Register(RegisterPostRequest registerRequest)
        {
            var user = new User {
                UserName = registerRequest.Username, Email = registerRequest.Email
            };

            var result = await _userManager.CreateAsync(user, registerRequest.Password);



            if (result.Succeeded)
            {
                await _userManager.AddClaimAsync(user, new Claim(ClaimTypes.Email, user.Email));

                return(Created("", user));
            }

            return(StatusCode(406, string.Join("\n", result.Errors.Select(x => x.Description))));
        }
Ejemplo n.º 7
0
        public IActionResult RegisterPost([FromBody] RegisterPostRequest request)
        {
            var botId = GetBotId();

            if (!botId.HasValue)
            {
                throw new HttpStatusException(HttpStatusCode.BadRequest, "Invalid or missing botId in claim");
            }
            if (string.IsNullOrWhiteSpace(request.Title))
            {
                throw new HttpStatusException(HttpStatusCode.BadRequest, "Title is required");
            }
            if (string.IsNullOrWhiteSpace(request.ContentUrl))
            {
                throw new HttpStatusException(HttpStatusCode.BadRequest, "ContentUrl is required");
            }
            if (!request.ContentId.HasValue)
            {
                throw new HttpStatusException(HttpStatusCode.BadRequest, "ContentId is required");
            }
            if (string.IsNullOrWhiteSpace(request.ContentSite))
            {
                throw new HttpStatusException(HttpStatusCode.BadRequest, "ContentSite is required");
            }
            if (string.IsNullOrWhiteSpace(request.ContentType))
            {
                throw new HttpStatusException(HttpStatusCode.BadRequest, "ContentType is required");
            }

            var report = new DbReport
            {
                AuthorName       = request.AuthorName,
                AuthorReputation = request.AuthorReputation,
                DashboardId      = botId.Value,
                Title            = request.Title,

                ContentUrl  = request.ContentUrl,
                ContentId   = request.ContentId.Value,
                ContentSite = request.ContentSite,
                ContentType = request.ContentType,

                ContentCreationDate = request.ContentCreationDate?.ToUniversalTime(),
                DetectedDate        = request.DetectedDate?.ToUniversalTime(),
                DetectionScore      = request.DetectionScore,

                Feedbacks          = new List <DbReportFeedback>(),
                ConflictExceptions = new List <DbConflictException>()
            };


            var dashboard = _dbContext.Dashboards.FirstOrDefault(d => d.Id == botId);

            if (dashboard == null)
            {
                throw new HttpStatusException(HttpStatusCode.BadRequest, $"Dashboard with id {botId} does not exist");
            }

            report.RequiredFeedback           = request.RequiredFeedback ?? dashboard.RequiredFeedback;
            report.RequiredFeedbackConflicted = request.RequiredFeedbackConflicted ?? dashboard.RequiredFeedbackConflicted;

            var contentFragments = request.ContentFragments ?? Enumerable.Empty <RegisterPostContentFragment>();
            var fragments        =
                string.IsNullOrWhiteSpace(request.Content)
                    ? contentFragments
                    : new[]
            {
                new RegisterPostContentFragment
                {
                    Content       = request.Content,
                    Name          = "Original",
                    Order         = 0,
                    RequiredScope = string.Empty
                }
            }.Concat(contentFragments.Select(cf => new RegisterPostContentFragment
            {
                Content       = cf.Content,
                Name          = cf.Name,
                Order         = cf.Order + 1,
                RequiredScope = cf.RequiredScope
            }));

            foreach (var contentFragment in fragments)
            {
                var dbContentFragment = new DbContentFragment
                {
                    Order         = contentFragment.Order,
                    Name          = contentFragment.Name,
                    Content       = contentFragment.Content,
                    RequiredScope = contentFragment.RequiredScope,
                    Report        = report
                };

                _dbContext.ContentFragments.Add(dbContentFragment);
            }
            _dbContext.Reports.Add(report);

            if (request.AllowedFeedback?.Any() ?? false)
            {
                var feedbackTypes = _dbContext.Feedbacks.Where(f => f.DashboardId == botId && request.AllowedFeedback.Contains(f.Name)).ToDictionary(f => f.Name, f => f.Id);
                foreach (var allowedFeedback in request.AllowedFeedback)
                {
                    if (feedbackTypes.ContainsKey(allowedFeedback))
                    {
                        _dbContext.ReportAllowedFeedbacks.Add(new DbReportAllowedFeedback
                        {
                            FeedbackId = feedbackTypes[allowedFeedback],
                            Report     = report
                        });
                    }
                    else
                    {
                        throw new HttpStatusException(HttpStatusCode.BadRequest, $"Feedback '{allowedFeedback}' not registered for bot");
                    }
                }
            }

            if (request.Reasons?.Any() ?? false)
            {
                var reasons = _dbContext.Reasons.Where(f => f.DashboardId == botId).ToDictionary(f => f.Name, f => f);
                foreach (var reason in request.Reasons ?? Enumerable.Empty <RegisterPostReason>())
                {
                    DbReason dbReason;

                    if (reasons.ContainsKey(reason.ReasonName))
                    {
                        dbReason = reasons[reason.ReasonName];
                    }
                    else
                    {
                        dbReason = new DbReason
                        {
                            Name        = reason.ReasonName,
                            DashboardId = botId.Value
                        };
                        _dbContext.Reasons.Add(dbReason);
                    }

                    _dbContext.ReportReasons.Add(new DbReportReason
                    {
                        Confidence = reason.Confidence,
                        Tripped    = reason.Tripped ?? false,
                        Reason     = dbReason,
                        Report     = report
                    });
                }
            }

            foreach (var attribute in request.Attributes ?? Enumerable.Empty <RegisterPostAttribute>())
            {
                _dbContext.ReportAttributes.Add(new DbReportAttribute
                {
                    Name   = attribute.Key,
                    Value  = attribute.Value,
                    Report = report
                });
            }

            _dbContext.SaveChanges();

            _dbContext.ProcessReport(report.Id);

            _dbContext.SaveChanges();

            return(Json(report.Id));
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Used by bots to register a detected post
        /// </summary>
        /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception>
        /// <param name="request"> (optional)</param>
        /// <returns>Task of ApiResponse (int?)</returns>
        public async System.Threading.Tasks.Task <ApiResponse <int?> > BotRegisterPostPostAsyncWithHttpInfo(RegisterPostRequest request = null)
        {
            var    localVarPath         = "/Bot/RegisterPost";
            var    localVarPathParams   = new Dictionary <String, String>();
            var    localVarQueryParams  = new List <KeyValuePair <String, String> >();
            var    localVarHeaderParams = new Dictionary <String, String>(Configuration.DefaultHeader);
            var    localVarFormParams   = new Dictionary <String, String>();
            var    localVarFileParams   = new Dictionary <String, FileParameter>();
            Object localVarPostBody     = null;

            // to determine the Content-Type header
            String[] localVarHttpContentTypes = new String[] {
                "application/json-patch+json",
                "application/json",
                "text/json",
                "application/_*+json"
            };
            String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);

            // to determine the Accept header
            String[] localVarHttpHeaderAccepts = new String[] {
                "text/plain",
                "application/json",
                "text/json"
            };
            String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);

            if (localVarHttpHeaderAccept != null)
            {
                localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
            }

            if (request != null && request.GetType() != typeof(byte[]))
            {
                localVarPostBody = Configuration.ApiClient.Serialize(request); // http body (model) parameter
            }
            else
            {
                localVarPostBody = request; // byte array
            }

            // authentication (oauth2) required
            // oauth required
            if (!String.IsNullOrEmpty(Configuration.AccessToken))
            {
                localVarHeaderParams["Authorization"] = "Bearer " + Configuration.AccessToken;
            }

            // make the HTTP request
            IRestResponse localVarResponse = (IRestResponse)await Configuration.ApiClient.CallApiAsync(localVarPath,
                                                                                                       Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
                                                                                                       localVarPathParams, localVarHttpContentType);

            int localVarStatusCode = (int)localVarResponse.StatusCode;

            if (ExceptionFactory != null)
            {
                Exception exception = ExceptionFactory("BotRegisterPostPost", localVarResponse);
                if (exception != null)
                {
                    throw exception;
                }
            }

            return(new ApiResponse <int?>(localVarStatusCode,
                                          localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
                                          (int?)Configuration.ApiClient.Deserialize(localVarResponse, typeof(int?))));
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Used by bots to register a detected post
        /// </summary>
        /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception>
        /// <param name="request"> (optional)</param>
        /// <returns>Task of int?</returns>
        public async System.Threading.Tasks.Task <int?> BotRegisterPostPostAsync(RegisterPostRequest request = null)
        {
            ApiResponse <int?> localVarResponse = await BotRegisterPostPostAsyncWithHttpInfo(request);

            return(localVarResponse.Data);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Used by bots to register a detected post
        /// </summary>
        /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception>
        /// <param name="request"> (optional)</param>
        /// <returns>int?</returns>
        public int?BotRegisterPostPost(RegisterPostRequest request = null)
        {
            ApiResponse <int?> localVarResponse = BotRegisterPostPostWithHttpInfo(request);

            return(localVarResponse.Data);
        }