Ejemplo n.º 1
0
 public IVirtualFile AssertFile(IVirtualPathProvider vfs, string virtualPath) =>
 AppHost.VirtualFileSources.GetMemoryVirtualFiles().GetFile(virtualPath)
 ?? vfs.GetFile(virtualPath)
 ?? throw HttpError.NotFound($"{virtualPath} does not exist");
Ejemplo n.º 2
0
        public override void ProcessRequest(IRequest request, IResponse response, string operationName)
        {
            HostContext.ApplyCustomHandlerRequestFilters(request, response);
            if (response.IsClosed)
            {
                return;
            }

            response.EndHttpHandlerRequest(skipClose: true, afterHeaders: r =>
            {
                var node = request.GetVirtualNode();
                var file = node as IVirtualFile;
                if (file == null)
                {
                    var dir = node as IVirtualDirectory;
                    if (dir != null)
                    {
                        file = dir.GetDefaultDocument();
                        if (file != null && HostContext.Config.RedirectToDefaultDocuments)
                        {
                            r.Redirect(request.GetPathUrl() + '/' + file.Name);
                            return;
                        }
                    }

                    if (file == null)
                    {
                        var fileName         = request.PathInfo;
                        var originalFileName = fileName;

                        if (Env.IsMono)
                        {
                            //Create a case-insensitive file index of all host files
                            if (allFiles == null)
                            {
                                allFiles = CreateFileIndex(HostContext.VirtualPathProvider.RootDirectory.RealPath);
                            }
                            if (allDirs == null)
                            {
                                allDirs = CreateDirIndex(HostContext.VirtualPathProvider.RootDirectory.RealPath);
                            }

                            if (allFiles.TryGetValue(fileName.ToLower(), out fileName))
                            {
                                file = HostContext.VirtualPathProvider.GetFile(fileName);
                            }
                        }

                        if (file == null)
                        {
                            var msg = "Static File '" + request.PathInfo + "' not found.";
                            log.WarnFormat("{0} in path: {1}", msg, originalFileName);
                            throw HttpError.NotFound(msg);
                        }
                    }
                }

                TimeSpan maxAge;
                if (r.ContentType != null && HostContext.Config.AddMaxAgeForStaticMimeTypes.TryGetValue(r.ContentType, out maxAge))
                {
                    r.AddHeader(HttpHeaders.CacheControl, "max-age=" + maxAge.TotalSeconds);
                }

                if (request.HasNotModifiedSince(file.LastModified))
                {
                    r.ContentType = MimeTypes.GetMimeType(file.Name);
                    r.StatusCode  = 304;
                    return;
                }

                try
                {
                    r.AddHeaderLastModified(file.LastModified);
                    r.ContentType = MimeTypes.GetMimeType(file.Name);

                    if (file.VirtualPath.EqualsIgnoreCase(this.DefaultFilePath))
                    {
                        if (file.LastModified > this.DefaultFileModified)
                        {
                            SetDefaultFile(this.DefaultFilePath, file.ReadAllBytes(), file.LastModified); //reload
                        }
                        r.OutputStream.Write(this.DefaultFileContents, 0, this.DefaultFileContents.Length);
                        r.Close();
                        return;
                    }

                    if (HostContext.Config.AllowPartialResponses)
                    {
                        r.AddHeader(HttpHeaders.AcceptRanges, "bytes");
                    }
                    long contentLength = file.Length;
                    long rangeStart, rangeEnd;
                    var rangeHeader = request.Headers[HttpHeaders.Range];
                    if (HostContext.Config.AllowPartialResponses && rangeHeader != null)
                    {
                        rangeHeader.ExtractHttpRanges(contentLength, out rangeStart, out rangeEnd);

                        if (rangeEnd > contentLength - 1)
                        {
                            rangeEnd = contentLength - 1;
                        }

                        r.AddHttpRangeResponseHeaders(rangeStart: rangeStart, rangeEnd: rangeEnd, contentLength: contentLength);
                    }
                    else
                    {
                        rangeStart = 0;
                        rangeEnd   = contentLength - 1;
                        r.SetContentLength(contentLength); //throws with ASP.NET webdev server non-IIS pipelined mode
                    }
                    var outputStream = r.OutputStream;
                    using (var fs = file.OpenRead())
                    {
                        if (rangeStart != 0 || rangeEnd != file.Length - 1)
                        {
                            fs.WritePartialTo(outputStream, rangeStart, rangeEnd);
                        }
                        else
                        {
                            fs.CopyTo(outputStream, BufferSize);
                            outputStream.Flush();
                        }
                    }
                }
                catch (System.Net.HttpListenerException ex)
                {
                    if (ex.ErrorCode == 1229)
                    {
                        return;
                    }
                    //Error: 1229 is "An operation was attempted on a nonexistent network connection"
                    //This exception occures when http stream is terminated by web browser because user
                    //seek video forward and new http request will be sent by browser
                    //with attribute in header "Range: bytes=newSeekPosition-"
                    throw;
                }
                catch (Exception ex)
                {
                    log.ErrorFormat("Static file {0} forbidden: {1}", request.PathInfo, ex.Message);
                    throw new HttpException(403, "Forbidden.");
                }
            });
        }
Ejemplo n.º 3
0
        public override object OnPut(PedidoItem request)
        {
            try{
                var factory = Factory;
                factory.Execute(proxy => {
                    var pedido = proxy.FirstOrDefaultById <Pedido>(request.IdPedido);

                    if (pedido == default(Pedido))
                    {
                        throw HttpError.NotFound(string.Format("Item no puede ser actualizado. No existe Pedido con Id: '{0}'", request.IdPedido));
                    }

                    if (pedido.FechaEnvio.HasValue)
                    {
                        throw HttpError.Unauthorized(string.Format("Item no puede ser actualizado. Pedido '{0}' Id:'{1} No puede ser Actualizado. Estado:Enviado ", pedido.Consecutivo, pedido.Id));
                    }

                    if (pedido.FechaAnulado.HasValue)
                    {
                        throw HttpError.Unauthorized(string.Format("Item no puede ser actualizado. Pedido '{0}' Id:'{1} No puede ser Actualizado. Estado:Anulado ", pedido.Consecutivo, pedido.Id));
                    }

                    var old = proxy.FirstOrDefaultById <PedidoItem>(request.Id);

                    if (old == default(PedidoItem))
                    {
                        throw HttpError.NotFound(string.Format("No existe Item con Id: '{0}'", request.Id));
                    }


                    var servicio           = proxy.CheckExistAndActivo <Servicio>(request.IdServicio, f => f.Nombre);
                    request.NombreServicio = servicio.Nombre;


                    var procedimiento = proxy.CheckExistAndActivo <Procedimiento>(request.IdProcedimiento, f => f.Nombre);
                    var empresa       = proxy.GetEmpresa();
                    if (!empresa.CambiarPrecio)
                    {
                        request.ValorUnitario = procedimiento.ValorUnitario;
                    }
                    request.PorcentajeIva = procedimiento.PorcentajeIva;

                    request.Descripcion = request.Descripcion.Encode();
                    request.Nota        = request.Nota.Encode();
                    proxy.Update(request);
                    request.Descripcion = request.Descripcion.Decode();
                    request.Nota        = request.Nota.Decode();
                });

                List <PedidoItem> data = new List <PedidoItem>();
                data.Add(request);

                return(new Response <PedidoItem>()
                {
                    Data = data
                });
            }
            catch (Exception e) {
                return(HttpResponse.ErrorResult <Response <PedidoItem> >(e, "PutPedidoItemError"));
            }
        }
        public object Put(UpdateTechnology request)
        {
            var tech = Db.SingleById <Technology>(request.Id);

            if (tech == null)
            {
                throw HttpError.NotFound("Tech not found");
            }

            var session  = SessionAs <AuthUserSession>();
            var authRepo = HostContext.AppHost.GetAuthRepository(Request);

            using (authRepo as IDisposable)
            {
                if (tech.IsLocked && !(tech.OwnerId == session.UserAuthId || session.HasRole(RoleNames.Admin, authRepo)))
                {
                    throw HttpError.Unauthorized(
                              "This Technology is locked and can only be modified by its Owner or Admins.");
                }
            }

            //Only Post an Update if there was no other update today
            var postUpdate = AppSettings.EnableTwitterUpdates() &&
                             tech.LastStatusUpdate.GetValueOrDefault(DateTime.MinValue) < DateTime.UtcNow.Date;

            tech.PopulateWith(request);
            tech.LastModifiedBy = session.UserName;
            tech.LastModified   = DateTime.UtcNow;

            if (postUpdate)
            {
                tech.LastStatusUpdate = tech.LastModified;
            }

            if (Request.Files.Length > 0)
            {
                tech.LogoUrl = Request.Files[0].UploadToImgur(AppSettings.GetString("oauth.imgur.ClientId"),
                                                              nameof(tech.LogoUrl), minWidth: 100, minHeight: 50, maxWidth: 2000, maxHeight: 1000);
            }

            if (string.IsNullOrEmpty(tech.LogoUrl))
            {
                throw new ArgumentException("Logo is Required", nameof(request.LogoUrl));
            }

            Db.Save(tech);

            var history = tech.ConvertTo <TechnologyHistory>();

            history.TechnologyId = tech.Id;
            history.Operation    = "UPDATE";
            Db.Insert(history);

            Cache.FlushAll();

            var response = new UpdateTechnologyResponse
            {
                Result = tech
            };

            if (postUpdate)
            {
                var url = TwitterUpdates.BaseUrl.CombineWith(new ClientTechnology {
                    Slug = tech.Slug
                }.ToUrl());
                var twitterSlug = tech.Slug.Replace("-", "");

                response.ResponseStatus = new ResponseStatus
                {
                    Message = PostTwitterUpdate(
                        $"Who's using #{twitterSlug}? {url}",
                        Db.ColumnDistinct <long>(Db.From <TechnologyChoice>()
                                                 .Where(x => x.TechnologyId == tech.Id)
                                                 .Select(x => x.TechnologyStackId)).ToList(),
                        maxLength: 140 - (TweetUrlLength - url.Length))
                };
            }

            return(response);
        }
Ejemplo n.º 5
0
        public object Any(Answers request)
        {
            TableRepository tableRepository = new TableRepository();
            CloudTable      questionTable   = tableRepository.GetTable(Tables.Questions);

            Guid questionId = Guid.Parse(request.Id);

            TableQuery <QuestionEntry> questionQuery = questionTable.CreateQuery <QuestionEntry>();

            QuestionEntry questionEntry = (from k in questionQuery
                                           where k.RowKey == questionId.ToString()
                                           select k).SingleOrDefault();

            if (questionEntry == null)
            {
                throw HttpError.NotFound("Such question do not exist");
            }

            questionEntry.Views++;
            tableRepository.InsertOrMerge(questionEntry, Tables.Questions);

            CloudTable answerTable = tableRepository.GetTable(Tables.Answers);
            TableQuery <AnswerEntry> answerQuery = answerTable.CreateQuery <AnswerEntry>();

            AnswerEntry[] answerEntries = (from k in answerQuery
                                           where k.PartitionKey == questionId.ToString()
                                           select k).ToArray();


            UserQuestionEntry userQuestionEntry = UserSession.IsAuthenticated
                                            ? tableRepository.Get <UserQuestionEntry>(Tables.UserQuestion, questionId, UserSession.GetUserId())
                                            : null;

            HashSet <string> votesUp   = new HashSet <string>(userQuestionEntry?.VotesUp?.Split('|') ?? new string[] { });
            HashSet <string> votesDown = new HashSet <string>(userQuestionEntry?.VotesDown?.Split('|') ?? new string[] { });

            Func <Guid, VoteKind> getVoteKind = ownerId =>
            {
                if (votesUp.Contains(ownerId.ToString()))
                {
                    return(VoteKind.Up);
                }

                if (votesDown.Contains(ownerId.ToString()))
                {
                    return(VoteKind.Down);
                }

                return(VoteKind.None);
            };

            AnswersResponse answersResponse = new AnswersResponse
            {
                Id             = questionEntry.GetId(),
                Creation       = questionEntry.Creation,
                Owner          = CreateUserCard(tableRepository, questionEntry.GetOwnerId()),
                Detail         = questionEntry.Detail,
                Tags           = questionEntry.Tags.SplitAndTrimOn(new char[] { ',' }),
                Title          = questionEntry.Title,
                Views          = questionEntry.Views,
                Votes          = questionEntry.Votes,
                SelectedAnswer = questionEntry.SelectedAnswer,
                Answers        = answerEntries.Select(k => new AnswerResult
                {
                    Owner    = CreateUserCard(tableRepository, k.GetAnswerOwnerId()),
                    Creation = k.Creation,
                    Content  = k.Content,
                    Votes    = k.Votes,
                    VoteKind = getVoteKind(k.GetAnswerOwnerId())
                }).ToArray()
            };

            // quest user vote for this question
            answersResponse.VoteKind = getVoteKind(questionId);
            answersResponse.Love     = userQuestionEntry?.Love ?? false;

            return(answersResponse);
        }
Ejemplo n.º 6
0
 public static Exception BatchNotFound(string batchId) =>
 HttpError.NotFound(ErrMsg.BatchNotFound(batchId));
Ejemplo n.º 7
0
        //this is the only request that does not require admin role
        public JarsUserResponse Any(GetJarsUser request)
        {
            if (request.EmailOrUserName.IsNullOrEmpty())
            {
                return(null);
            }

            var             sessionUserName  = Request.GetSession().UserName;
            var             sessionUserEmail = Request.GetSession().Email;
            IAuthRepository ssAuthRepo       = ServiceStackHost.Instance.GetAuthRepository();
            IUserAuth       ssUser           = ssAuthRepo.GetUserAuthByUserName(request.EmailOrUserName);

            if (ssUser == null)
            {
                throw HttpError.NotFound("User not found");
            }
            if (ssUser.LockedDate != null)
            {
                throw HttpError.Unauthorized("User account locked");
            }

            if (ssUser.Roles.Count == 0 || ssUser.Permissions.Count == 0)
            {
                IUserAuth newUserA = new UserAuth();
                newUserA.PopulateWith(ssUser);
                if (ssUser.Roles.Count == 0)
                {
                    newUserA.Roles.Add("Guest");
                }
                if (ssUser.Permissions.Count == 0)
                {
                    newUserA.Permissions.Add("ViewOnly");
                }
                ssUser = ssAuthRepo.UpdateUserAuth(ssUser, newUserA);
            }

            IJarsUserRepository repository = _DataRepositoryFactory.GetDataRepository <IJarsUserRepository>();
            JarsUser            acc        = repository.Where(u => u.UserName == ssUser.UserName || u.Email == ssUser.Email, request.FetchEagerly).SingleOrDefault();

            if (acc == null)
            {
                acc    = ssUser.ConvertTo <JarsUser>();
                acc.Id = 0;
                acc    = repository.CreateUpdate(acc, sessionUserName);
            }
            else
            {
                //we have to change the id because the 2 tables differ and id's wont match.
                int accId = acc.Id;
                acc.PopulateWith(ssUser);
                acc.Id = accId;
                acc    = repository.CreateUpdate(acc, sessionUserName);
            }

            JarsUserResponse response = new JarsUserResponse
            {
                UserAccount = acc.ConvertTo <JarsUserDto>()
            };

            //response.jarsUserAccount = FakeDataHelper.FakeUserAccount;
            return(response);
        }
Ejemplo n.º 8
0
        public object Post(Auth request)
        {
            AssertAuthProviders();

            if (ValidateFn != null)
            {
                var validationResponse = ValidateFn(this, HttpMethods.Get, request);
                if (validationResponse != null)
                {
                    return(validationResponse);
                }
            }

            if (request.RememberMe.HasValue)
            {
                var opt = request.RememberMe.GetValueOrDefault(false)
                    ? SessionOptions.Permanent
                    : SessionOptions.Temporary;

                base.RequestContext.Get <IHttpResponse>()
                .AddSessionOptions(base.RequestContext.Get <IHttpRequest>(), opt);
            }

            var provider    = request.provider ?? AuthProviders[0].Provider;
            var oAuthConfig = GetAuthProvider(provider);

            if (oAuthConfig == null)
            {
                throw HttpError.NotFound("No configuration was added for OAuth provider '{0}'".Fmt(provider));
            }

            if (request.provider == LogoutAction)
            {
                return(oAuthConfig.Logout(this, request));
            }

            var session = this.GetSession();

            var isHtml = base.RequestContext.ResponseContentType.MatchesContentType(ContentType.Html);

            try
            {
                var response = Authenticate(request, provider, session, oAuthConfig);

                // The above Authenticate call may end an existing session and create a new one so we need
                // to refresh the current session reference.
                session = this.GetSession();

                var referrerUrl = request.Continue
                                  ?? session.ReferrerUrl
                                  ?? this.RequestContext.GetHeader("Referer")
                                  ?? oAuthConfig.CallbackUrl;

                var alreadyAuthenticated = response == null;
                response = response ?? new AuthResponse {
                    UserName    = session.UserAuthName,
                    SessionId   = session.Id,
                    ReferrerUrl = referrerUrl,
                };

                if (isHtml)
                {
                    if (alreadyAuthenticated)
                    {
                        return(this.Redirect(referrerUrl.AddHashParam("s", "0")));
                    }

                    if (!(response is IHttpResult) && !String.IsNullOrEmpty(referrerUrl))
                    {
                        return(new HttpResult(response)
                        {
                            Location = referrerUrl
                        });
                    }
                }

                return(response);
            }
            catch (HttpError ex)
            {
                var errorReferrerUrl = this.RequestContext.GetHeader("Referer");
                if (isHtml && errorReferrerUrl != null)
                {
                    errorReferrerUrl = errorReferrerUrl.SetQueryParam("error", ex.Message);
                    return(HttpResult.Redirect(errorReferrerUrl));
                }

                throw;
            }
        }
        public object Put(UpdateTechnologyStack request)
        {
            var techStack = Db.SingleById <TechnologyStack>(request.Id);

            if (techStack == null)
            {
                throw HttpError.NotFound("Tech stack not found");
            }

            var session = SessionAs <AuthUserSession>();

            if (techStack.IsLocked && !(techStack.OwnerId == session.UserAuthId || session.HasRole(RoleNames.Admin)))
            {
                throw HttpError.Unauthorized("This TechStack is locked and can only be modified by its Owner or Admins.");
            }

            var techIds = (request.TechnologyIds ?? new List <long>()).ToHashSet();

            //Only Post an Update if there was no other update today and Stack as TechCount >= 4
            var postUpdate = AppSettings.EnableTwitterUpdates() &&
                             techStack.LastStatusUpdate.GetValueOrDefault(DateTime.MinValue) < DateTime.UtcNow.Date &&
                             techIds.Count >= 4;

            techStack.PopulateWith(request);
            techStack.LastModified   = DateTime.UtcNow;
            techStack.LastModifiedBy = session.UserName;

            if (postUpdate)
            {
                techStack.LastStatusUpdate = techStack.LastModified;
            }

            using (var trans = Db.OpenTransaction())
            {
                Db.Save(techStack);

                var existingTechChoices = Db.Select <TechnologyChoice>(q => q.TechnologyStackId == request.Id);
                var techIdsToAdd        = techIds.Except(existingTechChoices.Select(x => x.TechnologyId)).ToHashSet();
                var techChoices         = techIdsToAdd.Map(x => new TechnologyChoice
                {
                    TechnologyId      = x,
                    TechnologyStackId = request.Id,
                    CreatedBy         = techStack.CreatedBy,
                    LastModifiedBy    = techStack.LastModifiedBy,
                    OwnerId           = techStack.OwnerId,
                });

                var unusedTechChoices = Db.From <TechnologyChoice>().Where(x => x.TechnologyStackId == request.Id);
                if (techIds.Count > 0)
                {
                    unusedTechChoices.And(x => !techIds.Contains(x.TechnologyId));
                }

                Db.Delete(unusedTechChoices);

                Db.InsertAll(techChoices);

                trans.Commit();
            }

            var history = techStack.ConvertTo <TechnologyStackHistory>();

            history.TechnologyStackId = techStack.Id;
            history.Operation         = "UPDATE";
            history.TechnologyIds     = techIds.ToList();
            Db.Insert(history);

            Cache.FlushAll();

            var response = new UpdateTechnologyStackResponse
            {
                Result = techStack.ConvertTo <TechStackDetails>()
            };

            if (postUpdate)
            {
                var url = new ClientTechnologyStack {
                    Slug = techStack.Slug
                }.ToAbsoluteUri();
                response.ResponseStatus = new ResponseStatus
                {
                    Message = PostTwitterUpdate(
                        "{0}'s Stack! {1} ".Fmt(techStack.Name, url),
                        request.TechnologyIds,
                        maxLength: 140 - (TweetUrlLength - url.Length))
                };
            }

            return(response);
        }
Ejemplo n.º 10
0
        public async Task <HotReloadPageResponse> Any(HotReloadPage request)
        {
            var pathInfo = request.Path ?? "/";
            var page     = Pages.GetPage(pathInfo);

            if (page == null)
            {
                var matchingRoute = RestHandler.FindMatchingRestPath(
                    HttpMethods.Get, pathInfo, out var contentType);

                var feature = HostContext.AppHost.AssertPlugin <TemplatePagesFeature>();

                if (matchingRoute != null)
                {
                    page = feature.GetViewPage(matchingRoute.RequestType.Name);

                    if (page == null)
                    {
                        var responseType = HostContext.AppHost.Metadata.GetResponseTypeByRequest(matchingRoute.RequestType);
                        page = feature.GetViewPage(responseType.Name);
                    }
                }

                if (page == null)
                {
                    page = feature.GetRoutingPage(pathInfo, out var args);
                }
            }

            if (page == null)
            {
                throw HttpError.NotFound("Page not found: " + request.Path);
            }

            if (!page.HasInit)
            {
                await page.Init();
            }

            var startedAt       = DateTime.UtcNow;
            var eTagTicks       = string.IsNullOrEmpty(request.ETag) ? (long?)null : long.Parse(request.ETag);
            var maxLastModified = DateTime.MinValue;
            var shouldReload    = false;

            while (DateTime.UtcNow - startedAt < LongPollDuration)
            {
                maxLastModified = Pages.GetLastModified(page);

                if (eTagTicks == null)
                {
                    return new HotReloadPageResponse {
                               ETag = maxLastModified.Ticks.ToString()
                    }
                }
                ;

                shouldReload = maxLastModified.Ticks > eTagTicks;
                if (shouldReload)
                {
                    await Task.Delay(ModifiedDelay);

                    break;
                }

                await Task.Delay(CheckDelay);
            }

            return(new HotReloadPageResponse {
                Reload = shouldReload, ETag = maxLastModified.Ticks.ToString()
            });
        }
    }
Ejemplo n.º 11
0
        public async Task <object> Any(ApiPages request)
        {
            if (string.IsNullOrEmpty(request.PageName))
            {
                throw new ArgumentNullException(nameof(request.PageName));
            }

            var parts = string.IsNullOrEmpty(request.PathInfo)
                ? TypeConstants.EmptyStringArray
                : request.PathInfo.SplitOnLast('.');

            var hasPathContentType = parts.Length > 1 && Host.ContentTypes.KnownFormats.Contains(parts[1]);
            var pathInfo           = hasPathContentType
                ? parts[0]
                : request.PathInfo;

            var pathArgs = string.IsNullOrEmpty(pathInfo)
                ? TypeConstants.EmptyStringArray
                : pathInfo.Split('/');

            parts = request.PageName.SplitOnLast('.');
            var hasPageContentType = pathArgs.Length == 0 && parts.Length > 1 && Host.ContentTypes.KnownFormats.Contains(parts[1]);
            var pageName           = hasPageContentType
                ? parts[0]
                : request.PageName;

            // Change .csv download file name
            base.Request.OperationName = pageName + (pathArgs.Length > 0 ? "_" + string.Join("_", pathArgs) : "");

            var feature = HostContext.GetPlugin <TemplatePagesFeature>();

            if (feature.ApiDefaultContentType != null &&
                !hasPathContentType &&
                !hasPageContentType &&
                base.Request.QueryString[TemplateConstants.Format] == null && base.Request.ResponseContentType == MimeTypes.Html)
            {
                base.Request.ResponseContentType = feature.ApiDefaultContentType;
            }

            var pagePath = feature.ApiPath.CombineWith(pageName).TrimStart('/');
            var page     = base.Request.GetPage(pagePath);

            if (page == null)
            {
                throw HttpError.NotFound($"No API Page was found at '{pagePath}'");
            }

            var requestArgs = base.Request.GetTemplateRequestParams(importRequestParams: feature.ImportRequestParams);

            requestArgs[TemplateConstants.PathInfo] = request.PathInfo;
            requestArgs[TemplateConstants.PathArgs] = pathArgs;

            var pageResult = new PageResult(page)
            {
                NoLayout          = true,
                RethrowExceptions = true,
                Args = requestArgs
            };

            var discardedOutput = await pageResult.RenderToStringAsync();

            if (!pageResult.Args.TryGetValue(TemplateConstants.Return, out var response))
            {
                throw HttpError.NotFound($"The API Page did not specify a response. Use the 'return' filter to set a return value for the page.");
            }

            if (response is Task <object> responseTask)
            {
                response = await responseTask;
            }
            if (response is IRawString raw)
            {
                response = raw.ToRawString();
            }

            var httpResult = ToHttpResult(pageResult, response);

            return(httpResult);
        }
Ejemplo n.º 12
0
        public static Response <User> Put(this User request,
                                          Factory factory,
                                          IHttpRequest httpRequest)
        {
            var userSession = httpRequest.GetSession();

            if (!(userSession.HasRole(RoleNames.Admin) ||
                  userSession.HasPermission("User.update")))
            {
                throw HttpError.Unauthorized("Usuario no autorizado para actualizar");
            }


            var authRepo = httpRequest.TryResolve <IUserAuthRepository>();

            if (authRepo == null)
            {
                throw HttpError.NotFound("AuthRepository NO configurado");
            }

            var user = authRepo.GetUserAuth(request.Id.ToString());

            if (!(request.Id == int.Parse(userSession.UserAuthId) ||
                  userSession.HasRole(RoleNames.Admin)))
            {
                throw HttpError.Unauthorized("No puede cambiar los datos de otro usuario");
            }

            if (user == default(UserAuth))
            {
                throw HttpError.NotFound(
                          string.Format("Usuario con Id:'{0}' NO encontrado", request.Id));
            }


            var newUser = new UserAuth
            {
                Id           = request.Id,
                FirstName    = request.FirstName,
                LastName     = request.LastName,
                Email        = request.Email,
                UserName     = request.UserName,
                DisplayName  = request.FirstName + " " + request.LastName,
                ModifiedDate = System.DateTime.Now,
            };

            newUser.Set <UserMeta>(new UserMeta {
                Cargo     = request.Cargo,
                Activo    = request.Activo,
                ExpiresAt = request.ExpiresAt
            });

            if (request.Password.IsNullOrEmpty() ||
                request.IsDummyPassword())
            {
                factory.Execute(proxy => {
                    proxy.Update <UserAuth>(
                        newUser,
                        ev => ev.Where(q => q.Id == request.Id).
                        Update(f => new {
                        f.UserName, f.FirstName, f.LastName, f.Email, f.Meta,
                        f.DisplayName,
                        f.ModifiedDate
                    }));
                });
            }

            else
            {
                user = authRepo.UpdateUserAuth(user, newUser, request.Password);
            }

            request.SetDummyPassword();

            List <User> data = new List <User>();

            data.Add(request);

            return(new Response <User>()
            {
                Data = data
            });
        }
        public async Task <UpdateTechnologyStackResponse> Put(UpdateTechnologyStack request)
        {
            var techStack = await Db.SingleByIdAsync <TechnologyStack>(request.Id);

            if (techStack == null)
            {
                throw HttpError.NotFound("Tech stack not found");
            }

            if (string.IsNullOrEmpty(request.AppUrl) || request.AppUrl.IndexOf("://", StringComparison.Ordinal) == -1)
            {
                throw new ArgumentException("A valid URL to the Website or App is required");
            }

            if (string.IsNullOrEmpty(request.Description) || request.Description.Length < 100)
            {
                throw new ArgumentException("Summary needs to be a min of 100 chars");
            }

            var session  = SessionAs <AuthUserSession>();
            var authRepo = HostContext.AppHost.GetAuthRepository(Request);

            using (authRepo as IDisposable)
            {
                if (techStack.IsLocked && !(techStack.OwnerId == session.UserAuthId || session.HasRole(RoleNames.Admin, authRepo)))
                {
                    throw HttpError.Unauthorized(
                              "This TechStack is locked and can only be modified by its Owner or Admins.");
                }
            }

            var techIds = (request.TechnologyIds ?? new List <long>()).ToHashSet();

            //Only Post an Update if there was no other update today and Stack as TechCount >= 4
            var postUpdate = AppSettings.EnableTwitterUpdates() &&
                             techStack.LastStatusUpdate.GetValueOrDefault(DateTime.MinValue) < DateTime.UtcNow.Date &&
                             techIds.Count >= 4;

            if (techStack.Details != request.Details)
            {
                techStack.DetailsHtml = await Markdown.TransformAsync(request.Details, session.GetGitHubToken());
            }

            techStack.PopulateWith(request);
            techStack.LastModified   = DateTime.UtcNow;
            techStack.LastModifiedBy = session.UserName;

            if (postUpdate)
            {
                techStack.LastStatusUpdate = techStack.LastModified;
            }

            if (Request.Files.Length > 0)
            {
                techStack.ScreenshotUrl = Request.Files[0].UploadToImgur(AppSettings.GetString("oauth.imgur.ClientId"),
                                                                         nameof(techStack.ScreenshotUrl), minWidth: 858, minHeight: 689, maxWidth: 2600, maxHeight: 2600);
            }

            if (string.IsNullOrEmpty(techStack.ScreenshotUrl))
            {
                throw new ArgumentException("Screenshot is Required", nameof(techStack.ScreenshotUrl));
            }

            using (var trans = Db.OpenTransaction())
            {
                await Db.SaveAsync(techStack);

                var existingTechChoices = await Db.SelectAsync <TechnologyChoice>(q => q.TechnologyStackId == request.Id);

                var techIdsToAdd = techIds.Except(existingTechChoices.Select(x => x.TechnologyId)).ToHashSet();
                var techChoices  = techIdsToAdd.Map(x => new TechnologyChoice
                {
                    TechnologyId      = x,
                    TechnologyStackId = request.Id,
                    CreatedBy         = techStack.CreatedBy,
                    LastModifiedBy    = techStack.LastModifiedBy,
                    OwnerId           = techStack.OwnerId,
                });

                var unusedTechChoices = Db.From <TechnologyChoice>().Where(x => x.TechnologyStackId == request.Id);
                if (techIds.Count > 0)
                {
                    unusedTechChoices.And(x => !techIds.Contains(x.TechnologyId));
                }

                await Db.DeleteAsync(unusedTechChoices);

                await Db.InsertAllAsync(techChoices);

                trans.Commit();
            }

            var history = techStack.ConvertTo <TechnologyStackHistory>();

            history.TechnologyStackId = techStack.Id;
            history.Operation         = "UPDATE";
            history.TechnologyIds     = techIds.ToList();
            await Db.InsertAsync(history);

            Cache.FlushAll();

            var response = new UpdateTechnologyStackResponse
            {
                Result = techStack.ConvertTo <TechStackDetails>()
            };

            if (postUpdate)
            {
                var url = TwitterUpdates.BaseUrl.CombineWith(new ClientTechnologyStack {
                    Slug = techStack.Slug
                }.ToUrl());
                response.ResponseStatus = new ResponseStatus
                {
                    Message = PostTwitterUpdate(
                        $"{techStack.Name}'s Stack! {url} ",
                        request.TechnologyIds,
                        maxLength: 140 - (TweetUrlLength - url.Length))
                };
            }

            return(response);
        }
 public override object OnDelete(ClienteContacto request)
 {
     return(HttpError.NotFound("DeleteClienteContacto No Implementado"));
 }
Ejemplo n.º 15
0
 public static Exception CommandVariableNotFound(string VariableName) =>
 HttpError.NotFound(ErrMsg.CommandVariableNotFound(VariableName));
Ejemplo n.º 16
0
        public override object Authenticate(IServiceBase authService, IAuthSession session, Authenticate request)
        {
            var authRepo = HostContext.AppHost.GetAuthRepository(authService.Request);

            using (authRepo as IDisposable)
            {
                var apiRepo = (IManageApiKeys)authRepo;

                var apiKey = apiRepo.GetApiKey(request.Password);
                if (apiKey == null)
                {
                    throw HttpError.NotFound("ApiKey does not exist");
                }

                if (apiKey.CancelledDate != null)
                {
                    throw HttpError.Forbidden("ApiKey has been cancelled");
                }

                if (apiKey.ExpiryDate != null && DateTime.UtcNow > apiKey.ExpiryDate.Value)
                {
                    throw HttpError.Forbidden("ApiKey has expired");
                }

                var userAuth = authRepo.GetUserAuth(apiKey.UserAuthId);
                if (userAuth == null)
                {
                    throw HttpError.Unauthorized("User for ApiKey does not exist");
                }

                if (IsAccountLocked(authRepo, userAuth))
                {
                    throw new AuthenticationException(ErrorMessages.UserAccountLocked);
                }

                PopulateSession(authRepo as IUserAuthRepository, userAuth, session);

                if (session.UserAuthName == null)
                {
                    session.UserAuthName = userAuth.UserName ?? userAuth.Email;
                }

                var response = OnAuthenticated(authService, session, null, null);
                if (response != null)
                {
                    return(response);
                }

                authService.Request.Items[Keywords.ApiKey] = apiKey;

                return(new AuthenticateResponse
                {
                    UserId = session.UserAuthId,
                    UserName = session.UserName,
                    SessionId = session.Id,
                    DisplayName = session.DisplayName
                                  ?? session.UserName
                                  ?? "{0} {1}".Fmt(session.FirstName, session.LastName).Trim(),
                    ReferrerUrl = request.Continue,
                });
            }
        }
Ejemplo n.º 17
0
 public static Exception CommandOptionNotFound(string OptionName) =>
 HttpError.NotFound(ErrMsg.CommandOptionNotFound(OptionName));
Ejemplo n.º 18
0
 public static Exception BatchOptionNotFound(string OptionName) =>
 HttpError.NotFound(ErrMsg.BatchOptionNotFound(OptionName));
Ejemplo n.º 19
0
 public object Any(Throw404 request)
 {
     throw HttpError.NotFound(request.Message ?? "Custom Status Description");
 }
Ejemplo n.º 20
0
 public static Exception BatchArtifactNotFound(string ArtifactName) =>
 HttpError.NotFound(ErrMsg.BatchArtifactNotFound(ArtifactName));
Ejemplo n.º 21
0
 public object Any(CompressError request)
 {
     throw HttpError.NotFound("Always NotFound");
 }
Ejemplo n.º 22
0
 public static Exception StepNotFound(string StepName) =>
 HttpError.NotFound(ErrMsg.StepNotFound(StepName));
Ejemplo n.º 23
0
        public object Post(Authenticate request)
        {
            AssertAuthProviders();

            if (ValidateFn != null)
            {
                var validationResponse = ValidateFn(this, Request.Verb, request);
                if (validationResponse != null)
                {
                    return(validationResponse);
                }
            }

            var authFeature = GetPlugin <AuthFeature>();

            if (request.RememberMe.HasValue)
            {
                var opt = request.RememberMe.GetValueOrDefault(false)
                    ? SessionOptions.Permanent
                    : SessionOptions.Temporary;

                base.Request.AddSessionOptions(opt);
            }

            var provider = request.provider ?? AuthProviders[0].Provider;

            if (provider == CredentialsAliasProvider)
            {
                provider = CredentialsProvider;
            }

            var authProvider = GetAuthProvider(provider);

            if (authProvider == null)
            {
                throw HttpError.NotFound(ErrorMessages.UnknownAuthProviderFmt.Fmt(provider.SafeInput()));
            }

            if (LogoutAction.EqualsIgnoreCase(request.provider))
            {
                return(authProvider.Logout(this, request));
            }

            if (authProvider is IAuthWithRequest && !base.Request.IsInProcessRequest())
            {
                //IAuthWithRequest normally doesn't call Authenticate directly, but they can to return Auth Info
                //But as AuthenticateService doesn't have [Authenticate] we need to call it manually
                new AuthenticateAttribute().ExecuteAsync(base.Request, base.Response, request).Wait();
                if (base.Response.IsClosed)
                {
                    return(null);
                }
            }

            var session = this.GetSession();

            var isHtml = base.Request.ResponseContentType.MatchesContentType(MimeTypes.Html);

            try
            {
                var response = Authenticate(request, provider, session, authProvider);

                // The above Authenticate call may end an existing session and create a new one so we need
                // to refresh the current session reference.
                session = this.GetSession();

                if (request.provider == null && !session.IsAuthenticated)
                {
                    throw HttpError.Unauthorized(ErrorMessages.NotAuthenticated.Localize(Request));
                }

                var returnUrl   = Request.GetReturnUrl();
                var referrerUrl = returnUrl
                                  ?? session.ReferrerUrl
                                  ?? base.Request.GetQueryStringOrForm(Keywords.ReturnUrl)
                                  ?? this.Request.GetHeader(HttpHeaders.Referer)
                                  ?? authProvider.CallbackUrl;

                if (authFeature != null)
                {
                    if (!string.IsNullOrEmpty(returnUrl))
                    {
                        authFeature.ValidateRedirectLinks(Request, referrerUrl);
                    }
                }

                var manageRoles = AuthRepository as IManageRoles;

                var alreadyAuthenticated = response == null;
                response ??= new AuthenticateResponse {
                    UserId      = session.UserAuthId,
                    UserName    = session.UserAuthName,
                    DisplayName = session.DisplayName
                                  ?? session.UserName
                                  ?? $"{session.FirstName} {session.LastName}".Trim(),
                    SessionId   = session.Id,
                    ReferrerUrl = referrerUrl,
                };

                if (response is AuthenticateResponse authResponse)
                {
                    authResponse.ProfileUrl ??= session.GetProfileUrl();

                    if (authFeature?.IncludeRolesInAuthenticateResponse == true && session.UserAuthId != null)
                    {
                        authResponse.Roles ??= (manageRoles != null
                            ? manageRoles.GetRoles(session.UserAuthId)?.ToList()
                            : session.Roles);
                        authResponse.Permissions ??= (manageRoles != null
                            ? manageRoles.GetPermissions(session.UserAuthId)?.ToList()
                            : session.Permissions);
                    }

                    var authCtx = new AuthFilterContext {
                        AuthService          = this,
                        AuthProvider         = authProvider,
                        AuthRequest          = request,
                        AuthResponse         = authResponse,
                        ReferrerUrl          = referrerUrl,
                        Session              = session,
                        AlreadyAuthenticated = alreadyAuthenticated,
                        DidAuthenticate      = Request.Items.ContainsKey(Keywords.DidAuthenticate),
                    };

                    foreach (var responseFilter in AuthResponseFilters)
                    {
                        responseFilter.Execute(authCtx);
                    }

                    if (AuthResponseDecorator != null)
                    {
                        var authDecoratorResponse = AuthResponseDecorator(authCtx);
                        if (authDecoratorResponse != response)
                        {
                            return(authDecoratorResponse);
                        }
                    }
                }

                if (isHtml && request.provider != null)
                {
                    if (alreadyAuthenticated)
                    {
                        return(this.Redirect(referrerUrl.SetParam("s", "0")));
                    }

                    if (!(response is IHttpResult) && !string.IsNullOrEmpty(referrerUrl))
                    {
                        return(new HttpResult(response)
                        {
                            Location = referrerUrl
                        });
                    }
                }

                return(response);
            }
            catch (Exception ex)
            {
                if (isHtml && Request.GetErrorView() != null)
                {
                    return(ex);
                }

                if (ex is HttpError)
                {
                    var errorReferrerUrl = this.Request.GetHeader(HttpHeaders.Referer);
                    if (isHtml && errorReferrerUrl != null)
                    {
                        errorReferrerUrl = errorReferrerUrl.SetParam("f", ex.Message.Localize(Request));
                        return(HttpResult.Redirect(errorReferrerUrl));
                    }
                }

                throw;
            }
        }
Ejemplo n.º 24
0
 public static Exception StepVariableNotFound(string VariableName) =>
 HttpError.NotFound(ErrMsg.StepVariableNotFound(VariableName));
Ejemplo n.º 25
0
        public object Any(GetAccessToken request)
        {
            var jwtAuthProvider = (JwtAuthProvider)AuthenticateService.GetRequiredJwtAuthProvider();

            if (jwtAuthProvider.RequireSecureConnection && !Request.IsSecureConnection)
            {
                throw HttpError.Forbidden(ErrorMessages.JwtRequiresSecureConnection.Localize(Request));
            }

            if (string.IsNullOrEmpty(request.RefreshToken))
            {
                throw new ArgumentNullException(nameof(request.RefreshToken));
            }

            JsonObject jwtPayload;

            try
            {
                jwtPayload = jwtAuthProvider.GetVerifiedJwtPayload(Request, request.RefreshToken.Split('.'));
            }
            catch (ArgumentException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new ArgumentException(ex.Message);
            }

            jwtAuthProvider.AssertJwtPayloadIsValid(jwtPayload);

            if (jwtAuthProvider.ValidateRefreshToken != null && !jwtAuthProvider.ValidateRefreshToken(jwtPayload, Request))
            {
                throw new ArgumentException(ErrorMessages.RefreshTokenInvalid.Localize(Request), nameof(request.RefreshToken));
            }

            var userId = jwtPayload["sub"];

            IAuthSession         session;
            IEnumerable <string> roles = null, perms = null;

            var userSessionSource = AuthenticateService.GetUserSessionSource();

            if (userSessionSource != null)
            {
                session = userSessionSource.GetUserSession(userId);
                if (session == null)
                {
                    throw HttpError.NotFound(ErrorMessages.UserNotExists.Localize(Request));
                }

                roles = session.Roles;
                perms = session.Permissions;
            }
            else if (AuthRepository is IUserAuthRepository userRepo)
            {
                var userAuth = userRepo.GetUserAuth(userId);
                if (userAuth == null)
                {
                    throw HttpError.NotFound(ErrorMessages.UserNotExists.Localize(Request));
                }

                if (jwtAuthProvider.IsAccountLocked(userRepo, userAuth))
                {
                    throw new AuthenticationException(ErrorMessages.UserAccountLocked.Localize(Request));
                }

                session = SessionFeature.CreateNewSession(Request, SessionExtensions.CreateRandomSessionId());
                jwtAuthProvider.PopulateSession(userRepo, userAuth, session);

                if (userRepo is IManageRoles manageRoles && session.UserAuthId != null)
                {
                    roles = manageRoles.GetRoles(session.UserAuthId);
                    perms = manageRoles.GetPermissions(session.UserAuthId);
                }
            }
            else
            {
                throw new NotSupportedException("JWT RefreshTokens requires a registered IUserAuthRepository or an AuthProvider implementing IUserSessionSource");
            }

            var accessToken = jwtAuthProvider.CreateJwtBearerToken(Request, session, roles, perms);

            return(new GetAccessTokenResponse
            {
                AccessToken = accessToken
            });
        }
Ejemplo n.º 26
0
 public static Exception StepArtifactOptionNotFound(string OptionName) =>
 HttpError.NotFound(ErrMsg.StepArtifactOptionNotFound(OptionName));
Ejemplo n.º 27
0
        public object Post(Authenticate request)
        {
            AssertAuthProviders();

            if (ValidateFn != null)
            {
                var validationResponse = ValidateFn(this, Request.Verb, request);
                if (validationResponse != null)
                {
                    return(validationResponse);
                }
            }

            if (request.RememberMe.HasValue)
            {
                var opt = request.RememberMe.GetValueOrDefault(false)
                    ? SessionOptions.Permanent
                    : SessionOptions.Temporary;

                base.Request.AddSessionOptions(opt);
            }

            var provider = request.provider ?? AuthProviders[0].Provider;

            if (provider == CredentialsAliasProvider)
            {
                provider = CredentialsProvider;
            }

            var authProvider = GetAuthProvider(provider);

            if (authProvider == null)
            {
                throw HttpError.NotFound(ErrorMessages.UnknownAuthProviderFmt.Fmt(provider));
            }

            if (LogoutAction.EqualsIgnoreCase(request.provider))
            {
                return(authProvider.Logout(this, request));
            }

            var authWithRequest = authProvider as IAuthWithRequest;

            if (authWithRequest != null && !base.Request.IsInProcessRequest())
            {
                //IAuthWithRequest normally doesn't call Authenticate directly, but they can to return Auth Info
                //But as AuthenticateService doesn't have [Authenticate] we need to call it manually
                new AuthenticateAttribute().Execute(base.Request, base.Response, request);
                if (base.Response.IsClosed)
                {
                    return(null);
                }
            }

            var session = this.GetSession();

            var isHtml = base.Request.ResponseContentType.MatchesContentType(MimeTypes.Html);

            try
            {
                var response = Authenticate(request, provider, session, authProvider);

                // The above Authenticate call may end an existing session and create a new one so we need
                // to refresh the current session reference.
                session = this.GetSession();

                if (request.provider == null && !session.IsAuthenticated)
                {
                    throw HttpError.Unauthorized(ErrorMessages.NotAuthenticated);
                }

                var referrerUrl = request.Continue
                                  ?? session.ReferrerUrl
                                  ?? this.Request.GetHeader(HttpHeaders.Referer)
                                  ?? authProvider.CallbackUrl;

                var alreadyAuthenticated = response == null;
                response = response ?? new AuthenticateResponse {
                    UserId      = session.UserAuthId,
                    UserName    = session.UserAuthName,
                    DisplayName = session.DisplayName
                                  ?? session.UserName
                                  ?? $"{session.FirstName} {session.LastName}".Trim(),
                    SessionId   = session.Id,
                    ReferrerUrl = referrerUrl,
                };

                var authResponse = response as AuthenticateResponse;
                if (authResponse != null)
                {
                    foreach (var responseFilter in AuthResponseFilters)
                    {
                        authResponse = responseFilter.Execute(this, authProvider, session, authResponse) ?? authResponse;
                    }

                    if (AuthResponseDecorator != null)
                    {
                        return(AuthResponseDecorator(this, request, authResponse));
                    }
                }

                if (isHtml && request.provider != null)
                {
                    if (alreadyAuthenticated)
                    {
                        return(this.Redirect(referrerUrl.SetParam("s", "0")));
                    }

                    if (!(response is IHttpResult) && !string.IsNullOrEmpty(referrerUrl))
                    {
                        return(new HttpResult(response)
                        {
                            Location = referrerUrl
                        });
                    }
                }

                return(response);
            }
            catch (HttpError ex)
            {
                var errorReferrerUrl = this.Request.GetHeader(HttpHeaders.Referer);
                if (isHtml && errorReferrerUrl != null)
                {
                    errorReferrerUrl = errorReferrerUrl.SetParam("f", ex.Message.Localize(Request));
                    return(HttpResult.Redirect(errorReferrerUrl));
                }

                throw;
            }
        }
Ejemplo n.º 28
0
 public static Exception CommandNotFound(string CommandName) =>
 HttpError.NotFound(ErrMsg.CommandNotFound(CommandName));
Ejemplo n.º 29
0
        public object Post(Authenticate request)
        {
            AssertAuthProviders();

            if (ValidateFn != null)
            {
                var validationResponse = ValidateFn(this, Request.Verb, request);
                if (validationResponse != null)
                {
                    return(validationResponse);
                }
            }

            if (request.RememberMe.HasValue)
            {
                var opt = request.RememberMe.GetValueOrDefault(false)
                    ? SessionOptions.Permanent
                    : SessionOptions.Temporary;

                base.Request.AddSessionOptions(opt);
            }

            var provider = request.provider ?? AuthProviders[0].Provider;

            if (provider == CredentialsAliasProvider)
            {
                provider = CredentialsProvider;
            }

            var oAuthConfig = GetAuthProvider(provider);

            if (oAuthConfig == null)
            {
                throw HttpError.NotFound(ErrorMessages.UnknownAuthProviderFmt.Fmt(provider));
            }

            if (LogoutAction.EqualsIgnoreCase(request.provider))
            {
                return(oAuthConfig.Logout(this, request));
            }

            var session = this.GetSession();

            var isHtml = base.Request.ResponseContentType.MatchesContentType(MimeTypes.Html);

            try
            {
                var response = Authenticate(request, provider, session, oAuthConfig);

                // The above Authenticate call may end an existing session and create a new one so we need
                // to refresh the current session reference.
                session = this.GetSession();

                if (request.provider == null && !session.IsAuthenticated)
                {
                    throw HttpError.Unauthorized(ErrorMessages.NotAuthenticated);
                }

                var referrerUrl = request.Continue
                                  ?? session.ReferrerUrl
                                  ?? this.Request.GetHeader("Referer")
                                  ?? oAuthConfig.CallbackUrl;

                var alreadyAuthenticated = response == null;
                response = response ?? new AuthenticateResponse {
                    UserId      = session.UserAuthId,
                    UserName    = session.UserAuthName,
                    DisplayName = session.DisplayName
                                  ?? session.UserName
                                  ?? "{0} {1}".Fmt(session.FirstName, session.LastName).Trim(),
                    SessionId   = session.Id,
                    ReferrerUrl = referrerUrl,
                };

                if (isHtml && request.provider != null)
                {
                    if (alreadyAuthenticated)
                    {
                        return(this.Redirect(referrerUrl.SetParam("s", "0")));
                    }

                    if (!(response is IHttpResult) && !string.IsNullOrEmpty(referrerUrl))
                    {
                        return(new HttpResult(response)
                        {
                            Location = referrerUrl
                        });
                    }
                }

                return(response);
            }
            catch (HttpError ex)
            {
                var errorReferrerUrl = this.Request.GetHeader("Referer");
                if (isHtml && errorReferrerUrl != null)
                {
                    errorReferrerUrl = errorReferrerUrl.SetParam("f", ex.Message.Localize(Request));
                    return(HttpResult.Redirect(errorReferrerUrl));
                }

                throw;
            }
        }
Ejemplo n.º 30
0
        public static Response <Pedido> Patch(this Pedido request,
                                              Factory factory,
                                              IHttpRequest httpRequest)
        {
            List <string> actions = new List <string>(new string[] { "ENVIAR", "ACEPTAR", "ANULAR" });

            var action = httpRequest.PathInfo.Substring(httpRequest.PathInfo.LastIndexOf("/") + 1).ToUpper();

            if (actions.IndexOf(action) < 0)
            {
                throw HttpError.Unauthorized(string.Format("Operacion: '{0}' no autorizada en Ofertas", action));
            }

            var session = httpRequest.GetSession();

            factory.Execute(proxy => {
                using (proxy.AcquireLock(request.GetLockKey(), BL.LockSeconds))
                {
                    var old = proxy.FirstOrDefaultById <Pedido>(request.Id);

                    var userSesssion = httpRequest.GetSession();

                    if (!(old.IdCreadoPor == int.Parse(userSesssion.UserAuthId) ||
                          userSesssion.HasRole(BL.RoleCoordinador)))
                    {
                        throw HttpError.Unauthorized(string.Format("Usuario '{0}' No puede  ejecutar '{1}' en las ofertas creadas por:'{2}' ",
                                                                   userSesssion.UserName, action, old.NombreCreadoPor));
                    }


                    if (old == default(Pedido))
                    {
                        throw HttpError.NotFound(string.Format("No existe Oferta con Id: '{0}'", request.Id));
                    }

                    if (old.FechaAnulado.HasValue)
                    {
                        throw HttpError.Unauthorized(string.Format("Operacion:'{0}' No permitida. Oferta '{1}' Id:'{2} se encuentra anulada", action, request.Consecutivo, request.Id));
                    }



                    request.PopulateWith(old);

                    if (action == "ENVIAR")
                    {
                        if (old.FechaEnvio.HasValue)
                        {
                            throw HttpError.Conflict("Oferta ya se encuentra en estado Enviada");
                        }
                        request.FechaEnvio   = DateTime.Today;
                        request.IdEnviadoPor = int.Parse(session.UserAuthId);
                    }
                    else if (action == "ACEPTAR")
                    {
                        if (old.FechaAceptacion.HasValue)
                        {
                            throw HttpError.Conflict("Oferta ya se encuentra en estado Aceptada");
                        }

                        if (!old.FechaEnvio.HasValue)
                        {
                            throw HttpError.Conflict("La Oferta primero debe ser enviada");
                        }

                        request.FechaAceptacion = DateTime.Today;
                        request.IdAceptadoPor   = int.Parse(session.UserAuthId);
                    }
                    else
                    {
                        request.FechaAnulado = DateTime.Today;
                        request.IdAnuladoPor = int.Parse(session.UserAuthId);
                    }

                    proxy.Update(request, ev => ev.Update(
                                     f => new {
                        f.FechaEnvio, f.FechaAceptacion, f.FechaAnulado, f.VigenteHasta,
                        f.IdAceptadoPor, f.IdAnuladoPor, f.IdEnviadoPor
                    }).Where(q => q.Id == request.Id));
                }
            });

            List <Pedido> data = new List <Pedido>();

            data.Add(request);

            return(new Response <Pedido>()
            {
                Data = data
            });
        }