Пример #1
0
 public IActionResult NewUser(ValidatedUser validatedUser)
 {
     if (ModelState.IsValid)
     {
         var users = context.users.Where(x => x.email == validatedUser.email).ToList();
         if (users.Count == 0)
         {
             var user = new User {
                 first_name = validatedUser.first_name,
                 last_name  = validatedUser.last_name,
                 email      = validatedUser.email,
             };
             var hasher = new PasswordHasher <User>();
             user.password = hasher.HashPassword(user, validatedUser.password);
             context.Add(user);
             context.SaveChanges();
             HttpContext.Session.SetInt32("user", user.id);
             return(RedirectToAction("Main"));
         }
         else
         {
         }
     }
     return(View("Register"));
 }
        public IActionResult Check([FromBody] ValidateUser validate)
        {
            var valid = new ValidatedUser
            {
                PassWordIsValid = _usersLogic.CheckIfPassWordIsCorrect(validate)
            };

            return(Ok(valid));
        }
Пример #3
0
        /// <summary>
        /// Validates the user node tree permissions.
        /// </summary>
        /// <param name="Path">The path.</param>
        /// <param name="Action">The action.</param>
        /// <returns></returns>
        public bool ValidateUserNodeTreePermissions(string Path, string Action)
        {
            string permissions = ValidatedUser.GetPermissions(Path);

            if (permissions.IndexOf(Action) > -1 &&
                (Path.Contains("-20") || ("," + Path + ",").Contains("," + ValidatedUser.StartNodeId.ToString() + ",")))
            {
                return(true);
            }

            Log.Add(LogTypes.LoginFailure, ValidatedUser, -1,
                    "Insufient permissions in UmbracoEnsuredPage: '" + Path + "', '" + permissions + "', '" + Action + "'");
            return(false);
        }
        public async Task <ValidatedUser> ValidateUserToken(string token)
        {
            ValidatedUser validatedUser = null;
            ValidateToken validateToken = new ValidateToken
            {
                Token = token
            };

            var jsonSerializedToken = JsonConvert.SerializeObject(validateToken);
            var request             = new HttpRequestMessage
            {
                Method     = HttpMethod.Post,
                RequestUri = new Uri($"http://{this._httpContextAccessor.HttpContext.Request.Headers[HEADER_VTEX_ACCOUNT]}.vtexcommercestable.com.br/api/vtexid/credential/validate"),
                Content    = new StringContent(jsonSerializedToken, Encoding.UTF8, APPLICATION_JSON)
            };

            string authToken = this._httpContextAccessor.HttpContext.Request.Headers[HEADER_VTEX_CREDENTIAL];

            if (authToken != null)
            {
                request.Headers.Add(AUTHORIZATION_HEADER_NAME, authToken);
            }

            var client = _clientFactory.CreateClient();

            try
            {
                var response = await client.SendAsync(request);

                string responseContent = await response.Content.ReadAsStringAsync();

                //_context.Vtex.Logger.Info("ValidateUserToken", null, $"[{response.StatusCode}] {responseContent}");
                if (response.IsSuccessStatusCode)
                {
                    validatedUser = JsonConvert.DeserializeObject <ValidatedUser>(responseContent);
                }
            }
            catch (Exception ex)
            {
                _context.Vtex.Logger.Error("ValidateUserToken", null, $"Error validating user token", ex);
            }

            return(validatedUser);
        }
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            var productReviewService =
                context.HttpContext.RequestServices.GetService(typeof(IProductReviewService)) as IProductReviewService;

            //Response.Headers.Add("Cache-Control", "no-cache");
            var           vtexCookie       = context.HttpContext.Request.Headers[HEADER_VTEX_COOKIE];
            ValidatedUser validatedUser    = null;
            var           keyAndTokenValid = false;
            var           vtexAppKey       = context.HttpContext.Request.Headers[HEADER_VTEX_APP_KEY];
            var           vtexAppToken     = context.HttpContext.Request.Headers[HEADER_VTEX_APP_TOKEN];

            if (!string.IsNullOrEmpty(vtexCookie))
            {
                validatedUser = productReviewService !.ValidateUserToken(vtexCookie).Result;
                if (validatedUser == null)
                {
                    throw new InvalidOperationException();
                }

                if (!validatedUser.AuthStatus.Equals(AUTH_SUCCESS))
                {
                    throw new InvalidOperationException();
                }
            }

            if (!string.IsNullOrEmpty(vtexAppKey) && !string.IsNullOrEmpty(vtexAppToken))
            {
                string baseUrl = context.HttpContext.Request.Headers[FORWARDED_HOST];
                keyAndTokenValid = productReviewService !.ValidateKeyAndToken(vtexAppKey, vtexAppToken, baseUrl).Result;
            }

            if (!keyAndTokenValid)
            {
                throw new InvalidOperationException();
            }

            context.HttpContext.User = new GenericPrincipal(new GenericIdentity(validatedUser !.Id), new string[1]);
            throw new System.NotImplementedException();
        }
        public async Task <Review> NewReview(Review review, bool doValidation)
        {
            bool success = false;

            if (review != null)
            {
                if (doValidation)
                {
                    bool          userValidated       = false;
                    bool          hasShopperReviewed  = false;
                    bool          hasShopperPurchased = false;
                    string        userId        = string.Empty;
                    ValidatedUser validatedUser = null;
                    try
                    {
                        validatedUser = await this.ValidateUserToken(_context.Vtex.StoreUserAuthToken);
                    }
                    catch (Exception ex)
                    {
                        _context.Vtex.Logger.Error("NewReview", null, "Error Validating User", ex);
                    }

                    if (validatedUser != null)
                    {
                        if (validatedUser.AuthStatus.Equals("Success"))
                        {
                            userValidated = true;
                        }
                    }

                    if (userValidated)
                    {
                        userId             = validatedUser.User;
                        hasShopperReviewed = await this.HasShopperReviewed(userId, review.ProductId);

                        if (hasShopperReviewed)
                        {
                            return(null);
                        }

                        hasShopperPurchased = await this.ShopperHasPurchasedProduct(userId, review.ProductId);
                    }

                    review.ShopperId         = userId;
                    review.VerifiedPurchaser = hasShopperPurchased;
                }

                if (review.Approved == null)
                {
                    review.Approved = false;
                }

                //IDictionary<int, string> lookup = await _productReviewRepository.LoadLookupAsync();

                //int maxKeyValue = 0;
                //if (lookup != null && lookup.Count > 0)
                //{
                //    maxKeyValue = lookup.Keys.Max();
                //}
                //else
                //{
                //    lookup = new Dictionary<int, string>();
                //}

                //review.Id = ++maxKeyValue;
                //review.CacheId = review.Id;

                if (string.IsNullOrWhiteSpace(review.ReviewDateTime))
                {
                    // TODO: Check timezone for store
                    review.ReviewDateTime = DateTime.Now.ToString();
                }

                //string productId = review.ProductId;

                //IList<Review> reviews = await this._productReviewRepository.GetProductReviewsAsync(productId);
                //if (reviews == null)
                //{
                //    reviews = new List<Review>();
                //}

                //reviews.Add(review);
                //await this._productReviewRepository.SaveProductReviewsAsync(productId, reviews);
                //lookup.Add(review.Id, review.ProductId);
                //await this._productReviewRepository.SaveLookupAsync(lookup);

                string id = await this._productReviewRepository.SaveProductReviewMD(review);

                if (string.IsNullOrEmpty(id))
                {
                    review = null;
                }
                else
                {
                    review.Id = id;
                }
            }

            return(review);
        }
Пример #7
0
        public async Task <IActionResult> ProcessReviewApiAction(string requestedAction, string id)
        {
            Response.Headers.Add("Cache-Control", "no-cache");
            string        responseString   = string.Empty;
            string        vtexCookie       = HttpContext.Request.Headers[HEADER_VTEX_COOKIE];
            ValidatedUser validatedUser    = null;
            bool          userValidated    = false;
            bool          keyAndTokenValid = false;
            string        vtexAppKey       = HttpContext.Request.Headers[HEADER_VTEX_APP_KEY];
            string        vtexAppToken     = HttpContext.Request.Headers[HEADER_VTEX_APP_TOKEN];

            if (!string.IsNullOrEmpty(vtexCookie))
            {
                validatedUser = await this._productReviewsService.ValidateUserToken(vtexCookie);

                if (validatedUser != null)
                {
                    if (validatedUser.AuthStatus.Equals(AUTH_SUCCESS))
                    {
                        userValidated = true;
                    }
                }
            }

            if (!string.IsNullOrEmpty(vtexAppKey) && !string.IsNullOrEmpty(vtexAppToken))
            {
                string baseUrl = HttpContext.Request.Headers[FORWARDED_HOST];
                keyAndTokenValid = await this._productReviewsService.ValidateKeyAndToken(vtexAppKey, vtexAppToken, baseUrl);
            }

            if (string.IsNullOrEmpty(requestedAction))
            {
                return(BadRequest("Missing parameter"));
            }

            if ("post".Equals(HttpContext.Request.Method, StringComparison.OrdinalIgnoreCase))
            {
                string bodyAsText = await new System.IO.StreamReader(HttpContext.Request.Body).ReadToEndAsync();
                switch (requestedAction)
                {
                case REVIEW:
                    if (!userValidated && !keyAndTokenValid)
                    {
                        return(Unauthorized("Invalid User"));
                    }

                    Review newReview          = JsonConvert.DeserializeObject <Review>(bodyAsText);
                    bool   hasShopperReviewed = await _productReviewsService.HasShopperReviewed(validatedUser.User, newReview.ProductId);

                    if (hasShopperReviewed)
                    {
                        return(Json("Duplicate Review"));
                    }

                    bool hasShopperPurchased = await _productReviewsService.ShopperHasPurchasedProduct(validatedUser.User, newReview.ProductId);

                    Review reviewToSave = new Review
                    {
                        ProductId         = newReview.ProductId,
                        Rating            = newReview.Rating,
                        ShopperId         = validatedUser.User,
                        Title             = newReview.Title,
                        Text              = newReview.Text,
                        VerifiedPurchaser = hasShopperPurchased
                    };

                    var reviewResponse = await this._productReviewsService.NewReview(reviewToSave);

                    return(Json(reviewResponse.Id));

                    break;

                case REVIEWS:
                    if (!keyAndTokenValid)
                    {
                        return(Unauthorized());
                    }

                    IList <Review> reviews = JsonConvert.DeserializeObject <IList <Review> >(bodyAsText);
                    List <int>     ids     = new List <int>();
                    foreach (Review review in reviews)
                    {
                        var reviewsResponse = await this._productReviewsService.NewReview(review);

                        ids.Add(reviewsResponse.Id);
                    }

                    return(Json(ids));

                    break;
                }
            }
            else if ("delete".Equals(HttpContext.Request.Method, StringComparison.OrdinalIgnoreCase))
            {
                int[] ids;
                switch (requestedAction)
                {
                case REVIEW:
                    if (!userValidated && !keyAndTokenValid)
                    {
                        return(Json("Invalid User"));
                    }

                    if (string.IsNullOrEmpty(id))
                    {
                        return(BadRequest("Missing parameter."));
                    }

                    ids    = new int[1];
                    ids[0] = int.Parse(id);
                    return(Json(await this._productReviewsService.DeleteReview(ids)));

                    break;

                case REVIEWS:
                    if (!keyAndTokenValid)
                    {
                        return(Unauthorized());
                    }

                    string bodyAsText = await new System.IO.StreamReader(HttpContext.Request.Body).ReadToEndAsync();
                    ids = JsonConvert.DeserializeObject <int[]>(bodyAsText);
                    return(Json(await this._productReviewsService.DeleteReview(ids)));

                    break;
                }
            }
            else if ("patch".Equals(HttpContext.Request.Method, StringComparison.OrdinalIgnoreCase))
            {
                switch (requestedAction)
                {
                case REVIEW:
                    if (!userValidated && !keyAndTokenValid)
                    {
                        return(Json("Invalid User"));
                    }

                    string bodyAsText = await new System.IO.StreamReader(HttpContext.Request.Body).ReadToEndAsync();
                    Review review     = JsonConvert.DeserializeObject <Review>(bodyAsText);
                    return(Json(await this._productReviewsService.EditReview(review)));

                    break;
                }
            }
            else if ("get".Equals(HttpContext.Request.Method, StringComparison.OrdinalIgnoreCase))
            {
                var queryString = HttpContext.Request.Query;
                var searchTerm  = queryString["search_term"];
                var fromParam   = queryString["from"];
                var toParam     = queryString["to"];
                var orderBy     = queryString["order_by"];
                var status      = queryString["status"];
                var productId   = queryString["product_id"];
                switch (requestedAction)
                {
                case REVIEW:
                    if (string.IsNullOrEmpty(id))
                    {
                        return(BadRequest("Missing parameter."));
                    }

                    Review review = await this._productReviewsService.GetReview(int.Parse(id));

                    return(Json(review));

                    break;

                case REVIEWS:
                    IList <Review> reviews;
                    if (string.IsNullOrEmpty(fromParam))
                    {
                        fromParam = "0";
                    }

                    if (string.IsNullOrEmpty(toParam))
                    {
                        toParam = "3";
                    }

                    int            from         = int.Parse(fromParam);
                    int            to           = int.Parse(toParam);
                    IList <Review> searchResult = null;
                    int            totalCount   = 0;

                    if (!string.IsNullOrEmpty(productId))
                    {
                        searchResult = await _productReviewsService.GetReviewsByProductId(productId);
                    }
                    else
                    {
                        searchResult = await _productReviewsService.GetReviews();
                    }

                    IList <Review> searchData = await _productReviewsService.FilterReviews(searchResult, searchTerm, orderBy, status);

                    totalCount = searchData.Count;
                    searchData = await _productReviewsService.LimitReviews(searchData, from, to);

                    SearchResponse searchResponse = new SearchResponse
                    {
                        Data = new DataElement {
                            data = searchData
                        },
                        Range = new SearchRange {
                            From = from, To = to, Total = totalCount
                        }
                    };

                    return(Json(searchResponse));

                    break;

                case RATING:
                    decimal average = await _productReviewsService.GetAverageRatingByProductId(id);

                    searchResult = await _productReviewsService.GetReviewsByProductId(id);

                    totalCount = searchResult.Count;
                    RatingResponse ratingResponse = new RatingResponse
                    {
                        Average    = average,
                        TotalCount = totalCount
                    };

                    return(Json(ratingResponse));
                }
            }

            return(Json(responseString));
        }