Exemplo n.º 1
0
 public void OnAuthorization(AuthorizationFilterContext context)
 {
     if (context != null)
     {
         if (context.HttpContext.Response.Headers.ContainsKey("Token-Expired"))
         {
             context.HttpContext.Response.StatusCode = StatusCodes.Status401Unauthorized;
             context.Result = new JsonResult("")
             {
                 Value = new { Error = "User is not logged in" }
             };
             return;
         }
         if (context.HttpContext.Request.Headers.ContainsKey("Authorization"))
         {
             Microsoft.Extensions.Primitives.StringValues accessToken_Bearear = context.HttpContext.Request.Headers["Authorization"];
             User User = _tokenValidatorService.AuthenticateUser(accessToken_Bearear.ToString().Split("Bearer")[1]?.Trim());
             if (User != null)
             {
                 // nothing to do
             }
             else
             {
                 context.Result = new JsonResult("")
                 {
                     Value = new { Error = "User is not logged in" }
                 };
             }
         }
     }
 }
Exemplo n.º 2
0
        public async Task PostGet()
        {
            var metadataOnly = GetBoolValueQueryString("metadataOnly", required: false) ?? false;

            using (ContextPool.AllocateOperationContext(out DocumentsOperationContext context))
            {
                var docs = await context.ReadForMemoryAsync(RequestBodyStream(), "docs");

                if (docs.TryGet("Ids", out BlittableJsonReaderArray array) == false)
                {
                    ThrowRequiredPropertyNameInRequest("Ids");
                }

                var ids = new string[array.Length];
                for (int i = 0; i < array.Length; i++)
                {
                    ids[i] = array.GetStringByIndex(i);
                }

                context.OpenReadTransaction();

                // init here so it can be passed to TW
                var idsStringValues = new Microsoft.Extensions.Primitives.StringValues(ids);

                if (TrafficWatchManager.HasRegisteredClients)
                {
                    AddStringToHttpContext(idsStringValues.ToString(), TrafficWatchChangeType.Documents);
                }

                await GetDocumentsByIdAsync(context, idsStringValues, metadataOnly);
            }
        }
Exemplo n.º 3
0
        public async Task <IActionResult> GetTrips([FromHeader] object header)
        {
            Microsoft.Extensions.Primitives.StringValues value = "";
            var coll      = Request.Headers.TryGetValue("Authorization", out value);
            var values    = value.ToString().Split().ToList();
            var stream    = values[1];
            var handler   = new JwtSecurityTokenHandler();
            var jsonToken = handler.ReadToken(stream);
            var tokenS    = handler.ReadToken(stream) as JwtSecurityToken;

            //await CommandDispatcher.DispatchAsync(command);
            var userId = Guid.Parse(tokenS.Claims.First().Value);
            var trips  = await _context.Trips.Where(x => x.UserId == userId).ToListAsync();

            Dictionary <string, Tuple <string, List <string> > > tripList = new Dictionary <string, Tuple <string, List <string> > >();
            List <TripPOCOs> trip_list = new List <TripPOCOs>();

            foreach (var trip in trips)
            {
                var _trips = new TripPOCOs();
                _trips.locations  = _context.Destinations.Where(x => x.TripId == trip.Id).Select(x => x.Name).ToList();
                _trips.image_url  = trip.PhotoUrl;
                _trips.name       = trip.TripName;
                _trips.created_at = trip.CreatedAt.ToString("g",
                                                            DateTimeFormatInfo.InvariantInfo);
                _trips.Id = trip.Id;
                trip_list.Add(_trips);
            }


            return(Json(new
            {
                trip_list
            }));
        }
Exemplo n.º 4
0
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            Microsoft.Extensions.Primitives.StringValues authorizationHeader = "";
            bool headerPresent = context.HttpContext.Request.Headers.TryGetValue("Authorization", out authorizationHeader);

            if (headerPresent)
            {
                // extract and parse header value
                var headerValue = authorizationHeader.ToString();
                var headerParts = headerValue.Split(':');

                // authenticate
                if (headerParts.Length == 2)
                {
                    AppUser matchingUser = null;
                    bool    found        = AppUsers.TryGetValue(headerParts[0], out matchingUser);
                    if (found && headerParts[1] == matchingUser.Password)
                    {
                        return;
                    }
                }
            }

            // reaching here means authentication failed
            context.Result = new UnauthorizedResult();
        }
Exemplo n.º 5
0
        public async Task Invoke(HttpContext context)
        {
            // Do something here
            //context.Response.ContentType = "application/pdf";
            //await context.Response.Body.WriteAsync
            Microsoft.Extensions.Primitives.StringValues paramFileName = new Microsoft.Extensions.Primitives.StringValues();
            context.Request.Query.TryGetValue("filename", out paramFileName);
            string FileName = paramFileName.ToString();

            if (FileName != "")
            {
                try
                {
                    byte[] FileBytes = File.ReadAllBytes(FileName);

                    context.Response.StatusCode  = StatusCodes.Status200OK;
                    context.Response.ContentType = "application/pdf";
                    await context.Response.Body.WriteAsync(FileBytes, 0, FileBytes.Length);
                }
                catch (Exception ex)
                {
                    context.Response.StatusCode = StatusCodes.Status500InternalServerError;
                    await context.Response.WriteAsync(ex.Message);
                }
            }
            else
            {
                context.Response.StatusCode = StatusCodes.Status500InternalServerError;
                await context.Response.WriteAsync("URL requires a filename parameter.");
            }
        }
Exemplo n.º 6
0
 public static string GetCustomerId(this Microsoft.AspNetCore.Mvc.Controller controller)
 {
     Microsoft.Extensions.Primitives.StringValues customerId = Microsoft.Extensions.Primitives.StringValues.Empty;
     if (!controller.HttpContext.Request.Headers.TryGetValue("customerId", out customerId))
     {
         return(string.Empty);
     }
     return(customerId.ToString().ToLower());
 }
Exemplo n.º 7
0
        public static string GetParam(HttpRequest Request, string name)
        {
            string value = "";

            Microsoft.Extensions.Primitives.StringValues temp = new Microsoft.Extensions.Primitives.StringValues();
            if (Request.Form.TryGetValue(name, out temp))
            {
                value = temp.ToString();
            }
            return(value);
        }
        public Task <TenantContext <ITenant> > ResolveAsync(HttpContext context)
        {
            Tenant tenant      = null;
            var    tenantAlias = new Microsoft.Extensions.Primitives.StringValues();

            if (context.Request.Headers.TryGetValue("tenant", out tenantAlias))
            {
                tenant = _repository.LoadByAlias(tenantAlias.ToString());
            }
            if (tenant == null)
            {
                return(Task.FromResult(null as TenantContext <ITenant>));
            }
            using (var tenantContext = new TenantContext <ITenant>(tenant))
                return(Task.FromResult(tenantContext));
        }
Exemplo n.º 9
0
        public IEnumerable <string> Get()
        {
            var name = "";
            var dN   = new Microsoft.Extensions.Primitives.StringValues("");

            try
            {
                HttpContext.Request.Query.TryGetValue("name", out dN);
                name = dN.ToString();
            } catch (ArgumentNullException ane)
            {
            }

            var message = "Hello " + name;

            return(new string[] { message });
        }
Exemplo n.º 10
0
        // See https://raw.githubusercontent.com/dotnet/aspnetcore/c565386a3ed135560bc2e9017aa54a950b4e35dd/src/Mvc/Mvc.Core/src/Formatters/FormatFilter.cs
        public override string GetFormat(ActionContext context)
        {
            if (context.RouteData.Values.TryGetValue("f", out object obj))
            {
                // null and string.Empty are equivalent for route values.
                string routeValue = Convert.ToString(obj, CultureInfo.InvariantCulture);
                return(string.IsNullOrEmpty(routeValue) ? null : routeValue);
            }

            Microsoft.Extensions.Primitives.StringValues query = context.HttpContext.Request.Query["f"];
            if (query.Count > 0)
            {
                return(query.ToString());
            }

            return(base.GetFormat(context));
        }
Exemplo n.º 11
0
        public async Task <IActionResult> Post([FromHeader] object header, [FromBody] AddNewTrip command)
        {
            Microsoft.Extensions.Primitives.StringValues value = "";
            var coll      = Request.Headers.TryGetValue("Authorization", out value);
            var coll1     = Request.Body;
            var values    = value.ToString().Split().ToList();
            var stream    = values[1];
            var handler   = new JwtSecurityTokenHandler();
            var jsonToken = handler.ReadToken(stream);
            var tokenS    = handler.ReadToken(stream) as JwtSecurityToken;

            command.UserID = tokenS.Claims.First().Value;

            await CommandDispatcher.DispatchAsync(command);

            return(StatusCode(201));
        }
Exemplo n.º 12
0
        public IActionResult GetTokenParameters()
        {
            var retVal = new List <dynamic>();
            var claims = Request.HttpContext.User.Claims;

            foreach (var item in claims)
            {
                retVal.Add(new { item.Type, item.Value });
            }

            var authToken = new Microsoft.Extensions.Primitives.StringValues();
            var token     = Request.Headers.TryGetValue("Authorization", out authToken);

            authToken = authToken.ToString().Replace("Bearer ", "");

            var principal = _tokenService.ValidateToken(authToken);

            return(Ok(new { retVal, principal }));
        }
Exemplo n.º 13
0
        //public static string QueryString(this HttpRequest request,string name) { return GetParam(request,name); }
        //public static string Form(this HttpRequest request, string name) { return GetParam(request, name); }
        /// <summary>
        /// 前端使用,取地址栏中值,避免XXS
        /// </summary>
        /// <returns></returns>
        public static string GetParam(this HttpRequest request, string name)
        {
            string value = "";

            try
            {
                if (request.Method.Equals("POST"))
                {
                    Microsoft.Extensions.Primitives.StringValues temp = new Microsoft.Extensions.Primitives.StringValues();
                    if (request.Form.TryGetValue(name, out temp))
                    {
                        value = temp.ToString();
                    }
                }
            }
            catch { }
            if (string.IsNullOrEmpty(value) && !string.IsNullOrEmpty(request.Query[name]))
            {
                value = request.Query[name];
            }
            return(value);
        }
Exemplo n.º 14
0
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            var request   = context.HttpContext.Request;
            var authToken = new Microsoft.Extensions.Primitives.StringValues();
            var token     = request.Headers.TryGetValue("Authorization", out authToken);

            authToken = authToken.ToString().Replace("Bearer ", "");

            if (_tokenService.ValidateToken(authToken))
            {
                var claims   = _tokenService.GetClaims(authToken);
                var identity = _tokenService.GetIdentity(authToken);
                // TODO
                // You can do some extra checks here
                return;
            }
            else
            {
                context.Result = new StatusCodeResult((int)System.Net.HttpStatusCode.Unauthorized);
                return;
            }
        }
Exemplo n.º 15
0
        public IActionResult EditUserData(IFormFile file)
        {
            if (HttpContext.Request.Form.Keys.Any())
            {
                var claimsIdentity = (ClaimsIdentity)this.User.Identity;
                var claim          = claimsIdentity.FindFirst(ClaimTypes.NameIdentifier);
                if (claim != null)
                {
                    Microsoft.Extensions.Primitives.StringValues fullname  = "";
                    Microsoft.Extensions.Primitives.StringValues bio       = "";
                    Microsoft.Extensions.Primitives.StringValues birthdate = "";
                    Microsoft.Extensions.Primitives.StringValues gender    = "";

                    HttpContext.Request.Form.TryGetValue("fullname", out fullname);
                    HttpContext.Request.Form.TryGetValue("bio", out bio);
                    HttpContext.Request.Form.TryGetValue("birthdate", out birthdate);
                    HttpContext.Request.Form.TryGetValue("gender", out gender);

                    var userId = claim.Value;
                    var status = _context.isBlocked(userId);
                    if (!status)
                    {
                        AppUser user = new AppUser
                        {
                            Id        = userId,
                            FullName  = fullname.ToString(),
                            Bio       = bio.ToString(),
                            BirthDate = DateTime.Parse(birthdate.ToString()),
                            Gender    = (Gender)Enum.Parse(typeof(Gender), gender.ToString())
                        };
                        _context.UpdateUserInfo(user);
                        return(Json(user));
                    }
                }
            }

            return(Json("error"));
        }
Exemplo n.º 16
0
 private string extractToken(Microsoft.Extensions.Primitives.StringValues HttpAuthHeader)
 {
     return(HttpAuthHeader.ToString().Replace("Bearer ", ""));
 }
Exemplo n.º 17
0
        //[ValidateAntiForgeryToken]
        public IActionResult AddComment(IFormFile file)
        {
            var claimsIdentity = (ClaimsIdentity)this.User.Identity;
            var claim          = claimsIdentity.FindFirst(ClaimTypes.NameIdentifier);

            if (claim != null)
            {
                var userId  = claim.Value;
                var picName = "";

                /////checking image
                if (HttpContext.Request.Form.Files.Any())
                {
                    var    img = HttpContext.Request.Form.Files[0];
                    string pic = Path.GetFileName(img.FileName);
                    byte[] array;


                    using (MemoryStream ms = new MemoryStream())
                    {
                        img.CopyTo(ms);
                        array   = ms.GetBuffer();
                        picName = $"{Guid.NewGuid()}.jpg";
                        var str = Path.Combine(Environment.CurrentDirectory, "wwwroot//CommentsPics", picName);
                        System.IO.File.WriteAllBytes(str, array);
                    }
                }
                /////////////////////

                if (HttpContext.Request.Form.Keys.Any())
                {
                    Microsoft.Extensions.Primitives.StringValues cmnt = "";
                    Microsoft.Extensions.Primitives.StringValues PID  = "";
                    HttpContext.Request.Form.TryGetValue("comment", out cmnt);
                    HttpContext.Request.Form.TryGetValue("PostId", out PID);

                    string PostId  = PID.ToString();
                    string Comment = cmnt.ToString();

                    Comment comment = new Comment()
                    {
                        PostID    = int.Parse(PostId),
                        Text      = Comment,
                        Time      = DateTime.Now,
                        UserID    = userId,
                        isRemoved = false
                    };
                    if (picName != "")
                    {
                        comment.PictureURL = picName;
                    }


                    _context.AddComment(comment);

                    var respComment = _context.GetComment(comment.UserID, comment.PostID, comment.Time.ToString());
                    return(PartialView("~/Views/Posts/_Comment.cshtml", respComment));
                }
            }

            return(Json("error"));
        }
 private static string?TransformToString(IFormCollection collection, string key)
 {
     Microsoft.Extensions.Primitives.StringValues value = collection[key];
     return(value.ToString());
 }
Exemplo n.º 19
0
        //[ValidateAntiForgeryToken]
        public IActionResult AddPost(IFormFile file)
        {
            var claimsIdentity = (ClaimsIdentity)this.User.Identity;
            var claim          = claimsIdentity.FindFirst(ClaimTypes.NameIdentifier);

            if (claim != null)
            {
                var userId  = claim.Value;
                var picName = "";

                /////checking image
                if (HttpContext.Request.Form.Files.Any())
                {
                    var    img = HttpContext.Request.Form.Files[0];
                    string pic = Path.GetFileName(img.FileName);
                    byte[] array;


                    using (MemoryStream ms = new MemoryStream())
                    {
                        img.CopyTo(ms);
                        array   = ms.GetBuffer();
                        picName = $"{Guid.NewGuid()}.jpg";
                        var str = Path.Combine(Environment.CurrentDirectory, "wwwroot//PostsPics", picName);
                        System.IO.File.WriteAllBytes(str, array);
                    }
                }
                /////////////////////

                if (HttpContext.Request.Form.Keys.Any())
                {
                    Microsoft.Extensions.Primitives.StringValues post = "";
                    Microsoft.Extensions.Primitives.StringValues PID  = "";
                    HttpContext.Request.Form.TryGetValue("postText", out post);

                    string PostText = post.ToString();

                    Post newpPost = new Post()
                    {
                        Date        = DateTime.Now,
                        isDeleted   = false,
                        Text        = PostText,
                        PublisherId = userId
                    };

                    if (picName != "")
                    {
                        newpPost.PictureURL = picName;
                    }


                    _context.CreatePost(newpPost);

                    var respPost = _context.GetPostByUserAndDate(newpPost.PublisherId, newpPost.Date);



                    return(PartialView("~/Views/Posts/_Post.cshtml", respPost));
                }
            }

            return(Json("error"));
        }
Exemplo n.º 20
0
        public IActionResult EditComment(IFormFile file)
        {
            if (HttpContext.Request.Form.Keys.Any())
            {
                if (HttpContext.Request.Form.Keys.Contains("postId"))
                {
                    Microsoft.Extensions.Primitives.StringValues commentText = "";
                    Microsoft.Extensions.Primitives.StringValues commentTime = "";
                    Microsoft.Extensions.Primitives.StringValues userId      = "";
                    Microsoft.Extensions.Primitives.StringValues PID         = "";
                    Microsoft.Extensions.Primitives.StringValues removeImg   = "";
                    HttpContext.Request.Form.TryGetValue("commentText", out commentText);
                    HttpContext.Request.Form.TryGetValue("commentTime", out commentTime);
                    HttpContext.Request.Form.TryGetValue("userId", out userId);
                    HttpContext.Request.Form.TryGetValue("postId", out PID);
                    HttpContext.Request.Form.TryGetValue("removeImg", out removeImg);



                    string CommentText = commentText.ToString();
                    string CommentTime = commentTime.ToString();
                    string UserId      = userId.ToString();
                    int    PostID      = int.Parse(PID);
                    bool   removeImage = bool.Parse(removeImg);
                    string picName     = "";

                    /////checking image
                    if (HttpContext.Request.Form.Files.Any())
                    {
                        var    img = HttpContext.Request.Form.Files[0];
                        string pic = Path.GetFileName(img.FileName);
                        byte[] array;


                        using (MemoryStream ms = new MemoryStream())
                        {
                            img.CopyTo(ms);
                            array   = ms.GetBuffer();
                            picName = $"{Guid.NewGuid()}.jpg";
                            var str = Path.Combine(Environment.CurrentDirectory, "wwwroot//CommentsPics", picName);
                            if (!Directory.Exists(Path.Combine(Environment.CurrentDirectory, "wwwroot//CommentsPics")))
                            {
                                Directory.CreateDirectory(Path.Combine(Environment.CurrentDirectory, "wwwroot//CommentsPics"));
                            }
                            System.IO.File.WriteAllBytes(str, array);
                        }
                    }
                    /////////////////////

                    var respComment = _context.UpdateComment(PostID, userId, CommentTime, commentText, picName, removeImage);


                    ResponseViewModel response = new ResponseViewModel()
                    {
                        PostId = respComment.PostID,
                        UserId = respComment.UserID,
                        //UserName = respPost.Publisher.FullName,
                        Time   = respComment.Time.ToString().Replace(" ", ""),
                        Text   = respComment.Text,
                        PicURL = respComment.PictureURL,
                        //UserPicURL = respPost.Publisher.PhotoURL
                    };

                    return(Json(response));
                }
            }

            return(Json("error"));
        }