Ejemplo n.º 1
0
        public override object Authenticate(IServiceBase authService, IAuthSession session, Authenticate request)
        {
            if (string.IsNullOrEmpty(ConsumerKey))
            {
                throw new Exception("oauth.twitter.ConsumerKey is required");
            }

            if (string.IsNullOrEmpty(ConsumerSecret))
            {
                throw new Exception("oauth.twitter.ConsumerSecret is required");
            }

            var tokens = Init(authService, ref session, request);

            //Transferring AccessToken/Secret from Mobile/Desktop App to Server
            if (request.AccessToken != null && request.AccessTokenSecret != null)
            {
                tokens.AccessToken       = request.AccessToken;
                tokens.AccessTokenSecret = request.AccessTokenSecret;

                var validToken = AuthHttpGateway.VerifyTwitterAccessToken(
                    ConsumerKey, ConsumerSecret,
                    tokens.AccessToken, tokens.AccessTokenSecret,
                    out var userId,
                    out var email);

                if (!validToken)
                {
                    return(HttpError.Unauthorized("AccessToken is invalid"));
                }

                if (!string.IsNullOrEmpty(request.UserName) && userId != request.UserName)
                {
                    return(HttpError.Unauthorized("AccessToken does not match UserId: " + request.UserName));
                }

                tokens.UserId           = userId;
                session.IsAuthenticated = true;

                var failedResult = OnAuthenticated(authService, session, tokens, new Dictionary <string, string>());
                var isHtml       = authService.Request.IsHtml();
                if (failedResult != null)
                {
                    return(ConvertToClientError(failedResult, isHtml));
                }

                return(isHtml
                    ? authService.Redirect(SuccessRedirectUrlFilter(this, session.ReferrerUrl.SetParam("s", "1")))
                    : null); //return default AuthenticateResponse
            }

            //Default OAuth logic based on Twitter's OAuth workflow
            if (!tokens.RequestToken.IsNullOrEmpty() && !request.oauth_token.IsNullOrEmpty())
            {
                OAuthUtils.RequestToken          = tokens.RequestToken;
                OAuthUtils.RequestTokenSecret    = tokens.RequestTokenSecret;
                OAuthUtils.AuthorizationToken    = request.oauth_token;
                OAuthUtils.AuthorizationVerifier = request.oauth_verifier;

                if (OAuthUtils.AcquireAccessToken())
                {
                    session.IsAuthenticated  = true;
                    tokens.AccessToken       = OAuthUtils.AccessToken;
                    tokens.AccessTokenSecret = OAuthUtils.AccessTokenSecret;

                    return(OnAuthenticated(authService, session, tokens, OAuthUtils.AuthInfo)
                           ?? authService.Redirect(SuccessRedirectUrlFilter(this, session.ReferrerUrl.SetParam("s", "1")))); //Haz Access
                }

                //No Joy :(
                tokens.RequestToken       = null;
                tokens.RequestTokenSecret = null;
                this.SaveSession(authService, session, SessionExpiry);
                return(authService.Redirect(FailedRedirectUrlFilter(this, session.ReferrerUrl.SetParam("f", "AccessTokenFailed"))));
            }
            if (OAuthUtils.AcquireRequestToken())
            {
                tokens.RequestToken       = OAuthUtils.RequestToken;
                tokens.RequestTokenSecret = OAuthUtils.RequestTokenSecret;
                this.SaveSession(authService, session, SessionExpiry);

                //Redirect to OAuth provider to approve access
                return(authService.Redirect(AccessTokenUrlFilter(this, this.AuthorizeUrl
                                                                 .AddQueryParam("oauth_token", tokens.RequestToken)
                                                                 .AddQueryParam("oauth_callback", session.ReferrerUrl))));
            }

            return(authService.Redirect(FailedRedirectUrlFilter(this, session.ReferrerUrl.SetParam("f", "RequestTokenFailed"))));
        }
        public override object OnGet(OfertaInformeRequest request)
        {
            try{
                var visitor   = ReadExtensions.CreateExpression <OfertaInforme>();
                var predicate = PredicateBuilder.True <OfertaInforme>();

                if (request.Desde != default(DateTime))
                {
                    predicate = q => q.FechaEnvio >= request.Desde || q.FechaAceptacion >= request.Desde;
                }
                else
                {
                    throw HttpError.Unauthorized("Debe Indicar la fecha de inicio del informe (Desde)");
                }

                if (request.Hasta != default(DateTime))
                {
                    predicate = predicate.AndAlso(q => q.FechaEnvio <= request.Hasta || q.FechaAceptacion <= request.Hasta);
                }
                else
                {
                    throw HttpError.Unauthorized("Debe Indicar la fecha de terminacion del informe (Hasta)");
                }

                predicate = predicate.AndAlso(q => q.FechaAnulado == null);

                visitor.Where(predicate);

                return(Factory.Execute(proxy => {
                    var ofertas = proxy.Get(visitor);

                    var resumenPorUsuario = (
                        from o in ofertas
                        group o by o.NombreEnviadoPor into newGroup1
                        from newGroup2 in
                        (
                            from o in newGroup1
                            group o by o.Id into gi
                            select new {
                        FechaEnvio = gi.Max(p => p.FechaEnvio),
                        Valor = gi.Sum(p => p.Valor * p.Cantidad),
                        FechaAceptacion = gi.Max(p => p.FechaAceptacion),
                    }
                        )
                        group newGroup2 by newGroup1.Key into g
                        select new OfertaAgrupada {
                        AgrupadaPor = g.Key,
                        CantidadEnviada = g.Sum(p => (p.FechaEnvio >= request.Desde && p.FechaEnvio <= request.Hasta)?1:0),
                        ValorEnviado = g.Sum(p => (p.FechaEnvio >= request.Desde && p.FechaEnvio <= request.Hasta)?p.Valor:0),
                        CantidadAceptada = g.Sum(p => (p.FechaAceptacion >= request.Desde && p.FechaAceptacion <= request.Hasta)?1:0),
                        ValorAceptado = g.Sum(p => (p.FechaAceptacion >= request.Desde && p.FechaAceptacion <= request.Hasta)?p.Valor:0)
                    }
                        ).ToList();

                    HtmlGrid <OfertaAgrupada> gridUsuario =
                        BuildGridAgrupadoPor(resumenPorUsuario,
                                             string.Format("Ofertas por Asesor Comercial<br/> Desde: {0}  Hasta: {1}",
                                                           request.Desde.Format(), request.Hasta.Format()));


                    var resumenPorProcedimiento =
                        (from o in ofertas
                         group o by o.NombreProcedimiento into g
                         select new  OfertaAgrupada {
                        AgrupadaPor = g.Key,
                        CantidadEnviada = g.Sum(p => (p.FechaEnvio >= request.Desde && p.FechaEnvio <= request.Hasta)?p.Cantidad:0),
                        ValorEnviado = g.Sum(p => (p.FechaEnvio >= request.Desde && p.FechaEnvio <= request.Hasta)?p.Valor * p.Cantidad:0),
                        CantidadAceptada = g.Sum(p => (p.FechaAceptacion >= request.Desde && p.FechaAceptacion <= request.Hasta)?p.Cantidad:0),
                        ValorAceptado = g.Sum(p => (p.FechaAceptacion >= request.Desde && p.FechaAceptacion <= request.Hasta)?p.Valor * p.Cantidad:0)
                    }).ToList();

                    HtmlGrid <OfertaAgrupada> gridProcedimiento =
                        BuildGridAgrupadoPor(resumenPorProcedimiento,
                                             string.Format("Ofertas por Procedimiento<br/>Desde: {0}  Hasta: {1}",
                                                           request.Desde.Format(), request.Hasta.Format()));

                    var resumenPorCliente = (
                        from o in ofertas
                        group o by o.NombreCliente into newGroup1
                        from newGroup2 in
                        (
                            from o in newGroup1
                            group o by o.Id into gi
                            select new {
                        FechaEnvio = gi.Max(p => p.FechaEnvio),
                        Valor = gi.Sum(p => p.Valor * p.Cantidad),
                        FechaAceptacion = gi.Max(p => p.FechaAceptacion),
                    }
                        )
                        group newGroup2 by newGroup1.Key into g
                        select new OfertaAgrupada {
                        AgrupadaPor = g.Key,
                        CantidadEnviada = g.Sum(p => (p.FechaEnvio >= request.Desde && p.FechaEnvio <= request.Hasta)?1:0),
                        ValorEnviado = g.Sum(p => (p.FechaEnvio >= request.Desde && p.FechaEnvio <= request.Hasta)?p.Valor:0),
                        CantidadAceptada = g.Sum(p => (p.FechaAceptacion >= request.Desde && p.FechaAceptacion <= request.Hasta)?1:0),
                        ValorAceptado = g.Sum(p => (p.FechaAceptacion >= request.Desde && p.FechaAceptacion <= request.Hasta)?p.Valor:0)
                    }
                        ).ToList();


                    HtmlGrid <OfertaAgrupada> gridCliente =
                        BuildGridAgrupadoPor(resumenPorCliente,
                                             string.Format("Ofertas por Cliente<br/>Desde: {0}  Hasta: {1}",
                                                           request.Desde.Format(), request.Hasta.Format()));

                    //----------------------------------
                    var empresa = proxy.GetEmpresa();

                    var pedidos = (
                        from p in ofertas
                        group p by p.Id into g
                        select new  OfertaInforme {
                        Valor = g.Sum(f => f.Valor * f.Cantidad),
                        NombreCliente = g.Max(f => f.NombreCliente),
                        Consecutivo = g.Max(f => f.Consecutivo),
                        FechaAceptacion = g.Max(f => f.FechaAceptacion),
                        NombreEnviadoPor = g.Max(f => f.NombreEnviadoPor),
                    }).ToList();



                    HtmlGrid <OfertaInforme> gridOfertas = new HtmlGrid <OfertaInforme>();
                    gridOfertas.DataSource = pedidos.OrderByDescending(f => f.Valor).ToList();
                    gridOfertas.Css = new CayitaGridGrey();
                    gridOfertas.Title = string.Format("Relacion de Ofertas Enviadas<br/>Desde: {0}  Hasta: {1}",
                                                      request.Desde.Format(), request.Hasta.Format());

                    var gc = gridOfertas.CreateGridColumn();
                    gc.HeaderText = "Consecutivo";
                    gc.CellRenderFunc = (row, index) => row.Consecutivo.Format();
                    gc.FooterRenderFunc = () => pedidos.Count.Format();
                    gridOfertas.AddGridColum(gc);


                    gc = gridOfertas.CreateGridColumn();
                    gc.HeaderText = "Cliente";
                    gc.CellRenderFunc = (row, index) => row.NombreCliente;
                    gridOfertas.AddGridColum(gc);

                    gc = gridOfertas.CreateGridColumn();
                    gc.HeaderText = "Valor";
                    gc.CellRenderFunc = (row, index) => row.Valor.Format();
                    gc.FooterRenderFunc = () => pedidos.Sum(f => f.Valor).Format();
                    gridOfertas.AddGridColum(gc);

                    gc = gridOfertas.CreateGridColumn();
                    gc.HeaderText = "Aceptada?";
                    gc.CellRenderFunc = (row, index) => {
                        if (row.FechaAceptacion.HasValue)
                        {
                            var img = new HtmlImage {
                                Url = empresa.ApplicationHost + "/resources/icons/fam/accept.png"
                            };
                            var p = new HtmlParagragh {
                                Style = new HtmlStyle {
                                    TextAlign = "center"
                                }
                            };
                            p.AddHtmlTag(img);
                            return p.ToString();
                        }

                        return "";
                    };
                    gc.FooterRenderFunc = () => pedidos.Count(f => f.FechaAceptacion.HasValue).Format();
                    gridOfertas.AddGridColum(gc);


                    gc = gridOfertas.CreateGridColumn();
                    gc.HeaderText = "Asesor";
                    gc.CellRenderFunc = (row, index) => row.NombreEnviadoPor;
                    gridOfertas.AddGridColum(gc);


                    return new HtmlResponse {
                        Html = gridUsuario.ToString() +
                               "<br/>" + gridCliente.ToString() +
                               "<br/>" + gridOfertas.ToString() +
                               "<br/>" + gridProcedimiento.ToString()
                    };
                }));
            }
            catch (Exception e) {
                return(HttpResponse.ErrorResult <Response <OfertaInforme> >(e, "GetOfertaInformeError"));
            }
        }
        public override object Authenticate(IServiceBase authService, IAuthSession session, Authenticate request)
        {
            var user     = authService.Request.GetUser();
            var userName = user.GetUserName();

            if (!LoginMatchesSession(session, userName))
            {
                authService.RemoveSession();
                session = authService.GetSession();
            }

            if (IsAuthorized(user))
            {
                session.IsAuthenticated = true;
                if (session.UserAuthName == null)
                {
                    session.UserAuthName = userName;
                }

                var aspReq = (HttpRequestBase)authService.Request.OriginalRequest;

                var loginUser    = aspReq.ServerVariables["LOGON_USER"].ToNullIfEmpty();
                var remoteUser   = aspReq.ServerVariables["REMOTE_USER"].ToNullIfEmpty();
                var identityName = aspReq.LogonUserIdentity?.Name;
                session.DisplayName = loginUser
                                      ?? remoteUser
                                      ?? identityName;

                var tokens = new AuthTokens {
                    Provider    = Name,
                    UserName    = userName,
                    DisplayName = session.DisplayName,
                    Items       = new Dictionary <string, string> {
                        { "LOGON_USER", loginUser },
                        { "REMOTE_USER", remoteUser },
                        { "LogonUserIdentityName", identityName },
                    }
                };

                session.ReferrerUrl = GetReferrerUrl(authService, session, request);

                var response = OnAuthenticated(authService, session, tokens, new Dictionary <string, string>());

                if (session.Roles == null)
                {
                    session.Roles = new List <string>();
                }

                PopulateUserRoles(authService.Request, user, session);

                this.SaveSession(authService, session, SessionExpiry);

                if (response != null)
                {
                    return(response);
                }

                return(new AuthenticateResponse
                {
                    UserName = userName,
                    SessionId = session.Id,
                    DisplayName = session.DisplayName,
                    ReferrerUrl = request.Continue
                });
            }

            throw HttpError.Unauthorized(ErrorMessages.WindowsAuthFailed);
        }
Ejemplo n.º 4
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("No configuration was added for OAuth provider '{0}'".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("Not Authenticated");
                }

                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.AddHashParam("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.SetQueryParam("error", ex.Message);
                    return(HttpResult.Redirect(errorReferrerUrl));
                }

                throw;
            }
        }
Ejemplo n.º 5
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
            });
        }
Ejemplo n.º 6
0
        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);
        }
Ejemplo n.º 7
0
        public override object Authenticate(IServiceBase authService, IAuthSession session, Authenticate request)
        {
            var tokens = Init(authService, ref session, request);

            //Transferring AccessToken/Secret from Mobile/Desktop App to Server
            if (request?.AccessToken != null && VerifyAccessToken != null)
            {
                if (!VerifyAccessToken(request.AccessToken))
                {
                    return(HttpError.Unauthorized("AccessToken is not for client_id: " + ConsumerKey));
                }

                var isHtml       = authService.Request.IsHtml();
                var failedResult = AuthenticateWithAccessToken(authService, session, tokens, request.AccessToken);
                if (failedResult != null)
                {
                    return(ConvertToClientError(failedResult, isHtml));
                }

                return(isHtml
                    ? authService.Redirect(SuccessRedirectUrlFilter(this, session.ReferrerUrl.SetParam("s", "1")))
                    : null); //return default AuthenticateResponse
            }

            var httpRequest = authService.Request;
            var error       = httpRequest.QueryString["error_reason"]
                              ?? httpRequest.QueryString["error"]
                              ?? httpRequest.QueryString["error_code"]
                              ?? httpRequest.QueryString["error_description"];

            var hasError = !error.IsNullOrEmpty();

            if (hasError)
            {
                Log.Error($"OAuth2 Error callback. {httpRequest.QueryString}");
                return(authService.Redirect(FailedRedirectUrlFilter(this, session.ReferrerUrl.SetParam("f", error))));
            }

            var code = httpRequest.QueryString[Keywords.Code];
            var isPreAuthCallback = !code.IsNullOrEmpty();

            if (!isPreAuthCallback)
            {
                var oauthstate = session.Id;
                var preAuthUrl = AuthorizeUrl
                                 .AddQueryParam("response_type", "code")
                                 .AddQueryParam("client_id", ConsumerKey)
                                 .AddQueryParam("redirect_uri", this.CallbackUrl)
                                 .AddQueryParam("scope", string.Join(" ", Scopes))
                                 .AddQueryParam(Keywords.State, oauthstate);

                if (session is AuthUserSession authSession)
                {
                    (authSession.Meta ?? (authSession.Meta = new Dictionary <string, string>()))["oauthstate"] = oauthstate;
                }

                this.SaveSession(authService, session, SessionExpiry);
                return(authService.Redirect(PreAuthUrlFilter(this, preAuthUrl)));
            }

            try
            {
                var state = httpRequest.QueryString[Keywords.State];
                if (state != null && session is AuthUserSession authSession)
                {
                    if (authSession.Meta == null)
                    {
                        authSession.Meta = new Dictionary <string, string>();
                    }

                    if (authSession.Meta.TryGetValue("oauthstate", out var oauthState) && state != oauthState)
                    {
                        return(authService.Redirect(FailedRedirectUrlFilter(this, session.ReferrerUrl.SetParam("f", "InvalidState"))));
                    }

                    authSession.Meta.Remove("oauthstate");
                }

                var contents = GetAccessTokenJson(code);
                var authInfo = JsonObject.Parse(contents);

                var accessToken = authInfo["access_token"];

                var redirectUrl = SuccessRedirectUrlFilter(this, session.ReferrerUrl.SetParam("s", "1"));

                var errorResult = AuthenticateWithAccessToken(authService, session, tokens, accessToken);
                if (errorResult != null)
                {
                    return(errorResult);
                }

                //Haz Access!

                if (HostContext.Config?.UseSameSiteCookies == true)
                {
                    // Workaround Set-Cookie HTTP Header not being honoured in 302 Redirects
                    var redirectHtml = HtmlTemplates.GetHtmlRedirectTemplate(redirectUrl);
                    return(new HttpResult(redirectHtml, MimeTypes.Html));
                }

                return(authService.Redirect(redirectUrl));
            }
            catch (WebException we)
            {
                string errorBody  = we.GetResponseBody();
                var    statusCode = ((HttpWebResponse)we.Response).StatusCode;
                if (statusCode == HttpStatusCode.BadRequest)
                {
                    return(authService.Redirect(FailedRedirectUrlFilter(this, session.ReferrerUrl.SetParam("f", "AccessTokenFailed"))));
                }
            }

            //Shouldn't get here
            return(authService.Redirect(FailedRedirectUrlFilter(this, session.ReferrerUrl.SetParam("f", "Unknown"))));
        }
Ejemplo n.º 8
0
        public static Response <Pedido> Put(this Pedido request,
                                            Factory factory,
                                            IHttpRequest httpRequest)
        {
            factory.Execute(proxy => {
                using (proxy.AcquireLock(request.GetLockKey(), BL.LockSeconds))
                {
                    var old = proxy.FirstOrDefaultById <Pedido>(request.Id);

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

                    if (old.FechaEnvio.HasValue)
                    {
                        throw HttpError.Unauthorized(string.Format("Oferta '{0}' Id:'{1} No puede ser Actualizada. Estado:Enviado ", request.Consecutivo, request.Id));
                    }

                    if (old.FechaAnulado.HasValue)
                    {
                        throw HttpError.Unauthorized(string.Format("Oferta '{0}' Id:'{1} No puede ser Actualizada. Estado:Anulado ", request.Consecutivo, 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 actualizar las ofertas creadas por:'{1}' ",
                                                                   userSesssion.UserName, old.NombreCreadoPor));
                    }

                    request.FechaActualizacion = DateTime.Today;

                    if (request.IdCiudadDestinatario != default(int) &&
                        request.IdCiudadDestinatario != old.IdCiudadDestinatario)
                    {
                        var ciudad           = CheckCiudad(proxy, request);
                        request.NombreCiudad = ciudad.Nombre;
                        request.CodigoCiudad = ciudad.Codigo;
                    }


                    if (request.IdFormaPago != default(int) &&
                        request.IdFormaPago != old.IdFormaPago)
                    {
                        var fp = proxy.CheckExistAndActivo <FormaPago>(request.IdFormaPago, f => f.Descripcion);
                        request.DescripcionFormaPago = fp.Descripcion;
                    }

                    if (request.IdContacto != default(int) &&
                        request.IdContacto != old.IdContacto)
                    {
                        var contacto           = proxy.CheckExistAndActivo <Contacto>(request.IdContacto, f => f.Nombre);
                        request.NombreContacto = contacto.Nombre;

                        var cliente           = proxy.CheckExistAndActivo <Cliente>(contacto.IdCliente, f => f.Nombre);
                        request.NitCliente    = cliente.Nit;
                        request.NombreCliente = cliente.Nombre;
                    }

                    proxy.Update(request, ev => ev.Update(f =>
                                                          new {
                        f.IncluyeGastosEnvio, f.Observacion,
                        f.CargoDestinatario, f.CelularDestinatario, f.DiasDeVigencia,
                        f.DireccionDestinatario, f.FaxDestinatario, f.IdCiudadDestinatario, f.IdContacto,
                        f.IdFormaPago, f.MailDestinatario, f.NitCliente, f.NombreDestinatario, f.TelefonoDestinatario,
                        f.FechaActualizacion
                    }).Where(q => q.Id == request.Id)
                                 );
                }
            });

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

            data.Add(request);

            return(new Response <Pedido>()
            {
                Data = data
            });
        }
Ejemplo n.º 9
0
 public void Post(UpdateAddressVoid request)
 {
     //throw new UnauthorizedAccessException("Unauthorized UserId");
     throw HttpError.Unauthorized(request.Address ?? "Unauthorized UserId");
     //return HttpError.Unauthorized(request.Address ?? "Unauthorized UserId");
 }
Ejemplo n.º 10
0
        public override object Authenticate(IServiceBase authService, IAuthSession session, Authenticate request)
        {
            var tokens = this.Init(authService, ref session, request);

            //Transferring AccessToken/Secret from Mobile/Desktop App to Server
            if (request?.AccessToken != null)
            {
                if (VerifyAccessToken == null)
                {
                    throw new NotImplementedException($"VerifyAccessToken is not implemented by {Provider}");
                }

                if (!VerifyAccessToken(request.AccessToken))
                {
                    return(HttpError.Unauthorized($"AccessToken is not for the configured {Provider} App"));
                }

                var failedResult = AuthenticateWithAccessToken(authService, session, tokens, request.AccessToken);
                var isHtml       = authService.Request.IsHtml();
                if (failedResult != null)
                {
                    return(ConvertToClientError(failedResult, isHtml));
                }

                return(isHtml
                    ? authService.Redirect(SuccessRedirectUrlFilter(this, session.ReferrerUrl.SetParam("s", "1")))
                    : null); //return default AuthenticateResponse
            }

            var authServer = new AuthorizationServerDescription {
                AuthorizationEndpoint = new Uri(this.AuthorizeUrl), TokenEndpoint = new Uri(this.AccessTokenUrl)
            };

            AuthServerFilter?.Invoke(authServer);

            var authClient = new WebServerClient(authServer, this.ConsumerKey)
            {
                ClientCredentialApplicator = ClientCredentialApplicator.PostParameter(this.ConsumerSecret),
            };

            AuthClientFilter?.Invoke(authClient);

            var authState = ProcessUserAuthorization(authClient, authServer, authService);

            if (authState == null)
            {
                try
                {
                    var authReq         = authClient.PrepareRequestUserAuthorization(this.Scopes, new Uri(this.CallbackUrl));
                    var authContentType = authReq.Headers[HttpHeaders.ContentType];
                    var httpResult      = new HttpResult(authReq.ResponseStream, authContentType)
                    {
                        StatusCode = authReq.Status, StatusDescription = "Moved Temporarily"
                    };
                    foreach (string header in authReq.Headers)
                    {
                        httpResult.Headers[header] = authReq.Headers[header];
                    }

                    foreach (string name in authReq.Cookies)
                    {
                        var cookie = authReq.Cookies[name];
                        if (cookie != null)
                        {
                            httpResult.Cookies.Add(cookie.ToCookie());
                        }
                    }

                    this.SaveSession(authService, session, SessionExpiry);
                    return(httpResult);
                }
                catch (ProtocolException ex)
                {
                    Log.Error("Failed to login to {0}".Fmt(this.Provider), ex);
                    return(authService.Redirect(FailedRedirectUrlFilter(this, session.ReferrerUrl.SetParam("f", "Unknown"))));
                }
            }

            var accessToken = authState.AccessToken;

            if (accessToken != null)
            {
                tokens.RefreshToken       = authState.RefreshToken;
                tokens.RefreshTokenExpiry = authState.AccessTokenExpirationUtc;
            }

            if (accessToken != null)
            {
                try
                {
                    return(AuthenticateWithAccessToken(authService, session, tokens, accessToken)
                           ?? authService.Redirect(SuccessRedirectUrlFilter(this, session.ReferrerUrl.SetParam("s", "1"))));
                }
                catch (WebException we)
                {
                    var statusCode = ((HttpWebResponse)we.Response).StatusCode;
                    if (statusCode == HttpStatusCode.BadRequest)
                    {
                        return(authService.Redirect(FailedRedirectUrlFilter(this, session.ReferrerUrl.SetParam("f", "AccessTokenFailed"))));
                    }
                }
            }

            return(authService.Redirect(FailedRedirectUrlFilter(this, session.ReferrerUrl.SetParam("f", "RequestTokenFailed"))));
        }
Ejemplo n.º 11
0
        public override object Authenticate(IServiceBase authService, IAuthSession session, Authenticate request)
        {
            var tokens      = Init(authService, ref session, request);
            var httpRequest = authService.Request;

            //https://developer.github.com/v3/oauth/#common-errors-for-the-authorization-request
            var error = httpRequest.QueryString["error"]
                        ?? httpRequest.QueryString["error_uri"]
                        ?? httpRequest.QueryString["error_description"];

            var hasError = !error.IsNullOrEmpty();

            if (hasError)
            {
                Log.Error("GitHub error callback. {0}".Fmt(httpRequest.QueryString));
                throw HttpError.Unauthorized(error);
            }

            var code = httpRequest.QueryString["code"];
            var isPreAuthCallback = !code.IsNullOrEmpty();

            if (!isPreAuthCallback)
            {
                string url = PreAuthUrl + "?client_id={0}&redirect_uri={1}&scope={2}&state={3}"
                             .Fmt(ClientId, CallbackUrl.UrlEncode(), Scopes.Join(","), Guid.NewGuid().ToString("N"));

                authService.SaveSession(session, SessionExpiry);
                return(authService.Redirect(url));
            }

            string accessTokenUrl = AccessTokenUrl + "?client_id={0}&redirect_uri={1}&client_secret={2}&code={3}"
                                    .Fmt(ClientId, CallbackUrl.UrlEncode(), ClientSecret, code);

            try
            {
                var contents = accessTokenUrl.GetStringFromUrl();
                var authInfo = HttpUtility.ParseQueryString(contents);

                //GitHub does not throw exception, but just return error with descriptions
                //https://developer.github.com/v3/oauth/#common-errors-for-the-access-token-request
                var accessTokenError = authInfo["error"]
                                       ?? authInfo["error_uri"]
                                       ?? authInfo["error_description"];

                if (!accessTokenError.IsNullOrEmpty())
                {
                    Log.Error("GitHub access_token error callback. {0}".Fmt(authInfo.ToString()));
                    return(authService.Redirect(session.ReferrerUrl.AddParam("f", "AccessTokenFailed")));
                }
                tokens.AccessTokenSecret = authInfo["access_token"];

                session.IsAuthenticated = true;

                return(OnAuthenticated(authService, session, tokens, authInfo.ToDictionary())
                       ?? authService.Redirect(session.ReferrerUrl.AddParam("s", "1"))); //Haz Access!
            }
            catch (WebException webException)
            {
                //just in case GitHub will start throwing exceptions
                var statusCode = ((HttpWebResponse)webException.Response).StatusCode;
                if (statusCode == HttpStatusCode.BadRequest)
                {
                    return(authService.Redirect(session.ReferrerUrl.AddParam("f", "AccessTokenFailed")));
                }
            }
            return(authService.Redirect(session.ReferrerUrl.AddParam("f", "Unknown")));
        }
Ejemplo n.º 12
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("Referer")
                                  ?? authProvider.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,
                };

                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("Referer");
                if (isHtml && errorReferrerUrl != null)
                {
                    errorReferrerUrl = errorReferrerUrl.SetParam("f", ex.Message.Localize(Request));
                    return(HttpResult.Redirect(errorReferrerUrl));
                }

                throw;
            }
        }
Ejemplo n.º 13
0
        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>();

            if (tech.IsLocked && !(tech.OwnerId == session.UserAuthId || session.HasRole(RoleNames.Admin)))
            {
                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;
            }

            Db.Save(tech);

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

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

            ContentCache.ClearAll();

            var response = new UpdateTechnologyResponse
            {
                Result = tech
            };

            if (postUpdate)
            {
                var url = new ClientTechnology {
                    Slug = tech.Slug
                }.ToAbsoluteUri();
                response.ResponseStatus = new ResponseStatus
                {
                    Message = PostTwitterUpdate(
                        "Who's using #{0}? {1}".Fmt(tech.Slug.Replace("-", ""), 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);
        }
        public object Post(Authenticate request)
        {
            var validateRes = ValidateFn?.Invoke(this, Request.Verb, request);

            if (validateRes != null)
            {
                return(validateRes);
            }

            if (AuthProviders == null || AuthProviders.Length == 0)
            {
                throw new Exception("No auth providers have been registered in your app host.");
            }

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

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

            var authProvider = GetAuthProvider(provider);

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

            if (request.RememberMe)
            {
                Request.AddSessionOptions(SessionOptions.Permanent);
            }

            if (AuthProviderCatageries.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 = 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 referrerUrl = request.Continue
                                  ?? session.ReferrerUrl
                                  ?? 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,
                };

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

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

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

                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 = Request.GetHeader(HttpHeaders.Referer);
                if (isHtml && errorReferrerUrl != null)
                {
                    errorReferrerUrl = errorReferrerUrl.SetParam("f", ex.Message.Localize(Request));
                    return(HttpResult.Redirect(errorReferrerUrl));
                }

                throw;
            }
        }
Ejemplo n.º 15
0
        public override async Task <object> AuthenticateAsync(IServiceBase authService, IAuthSession session, Authenticate request, CancellationToken token = default)
        {
            var tokens = Init(authService, ref session, request);
            var ctx    = CreateAuthContext(authService, session, tokens);

            //Transferring AccessToken/Secret from Mobile/Desktop App to Server
            if (request.AccessToken != null && request.AccessTokenSecret != null)
            {
                tokens.AccessToken       = request.AccessToken;
                tokens.AccessTokenSecret = request.AccessTokenSecret;

                var validToken = await AuthHttpGateway.VerifyTwitterAccessTokenAsync(
                    ConsumerKey, ConsumerSecret,
                    tokens.AccessToken, tokens.AccessTokenSecret, token).ConfigAwait();

                if (validToken == null)
                {
                    return(HttpError.Unauthorized("AccessToken is invalid"));
                }

                if (!string.IsNullOrEmpty(request.UserName) && validToken.UserId != request.UserName)
                {
                    return(HttpError.Unauthorized("AccessToken does not match UserId: " + request.UserName));
                }

                tokens.UserId           = validToken.UserId;
                session.IsAuthenticated = true;

                var failedResult = await OnAuthenticatedAsync(authService, session, tokens, new Dictionary <string, string>(), token).ConfigAwait();

                var isHtml = authService.Request.IsHtml();
                if (failedResult != null)
                {
                    return(ConvertToClientError(failedResult, isHtml));
                }

                return(isHtml
                    ? await authService.Redirect(SuccessRedirectUrlFilter(ctx, session.ReferrerUrl.SetParam("s", "1"))).SuccessAuthResultAsync(authService, session).ConfigAwait()
                    : null); //return default AuthenticateResponse
            }

            //Default OAuth logic based on Twitter's OAuth workflow
            if (!tokens.RequestTokenSecret.IsNullOrEmpty() && !request.oauth_token.IsNullOrEmpty())
            {
                if (OAuthUtils.AcquireAccessToken(tokens.RequestTokenSecret, request.oauth_token, request.oauth_verifier))
                {
                    session.IsAuthenticated  = true;
                    tokens.AccessToken       = OAuthUtils.AccessToken;
                    tokens.AccessTokenSecret = OAuthUtils.AccessTokenSecret;

                    //Haz Access
                    return(await OnAuthenticatedAsync(authService, session, tokens, OAuthUtils.AuthInfo, token).ConfigAwait()
                           ?? await authService.Redirect(SuccessRedirectUrlFilter(ctx, session.ReferrerUrl.SetParam("s", "1"))).SuccessAuthResultAsync(authService, session).ConfigAwait());
                }

                //No Joy :(
                tokens.RequestToken       = null;
                tokens.RequestTokenSecret = null;
                await this.SaveSessionAsync(authService, session, SessionExpiry, token).ConfigAwait();

                return(authService.Redirect(FailedRedirectUrlFilter(ctx, session.ReferrerUrl.SetParam("f", "AccessTokenFailed"))));
            }
            if (OAuthUtils.AcquireRequestToken())
            {
                tokens.RequestToken       = OAuthUtils.RequestToken;
                tokens.RequestTokenSecret = OAuthUtils.RequestTokenSecret;
                await this.SaveSessionAsync(authService, session, SessionExpiry, token).ConfigAwait();

                //Redirect to OAuth provider to approve access
                return(authService.Redirect(AccessTokenUrlFilter(ctx, this.AuthorizeUrl
                                                                 .AddQueryParam("oauth_token", tokens.RequestToken)
                                                                 .AddQueryParam("oauth_callback", session.ReferrerUrl)
                                                                 .AddQueryParam(Keywords.State, session.Id) // doesn't support state param atm, but it's here when it does
                                                                 )));
            }

            return(authService.Redirect(FailedRedirectUrlFilter(ctx, session.ReferrerUrl.SetParam("f", "RequestTokenFailed"))));
        }
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
                                  ?? $"{session.FirstName} {session.LastName}".Trim(),
                    ReferrerUrl = request.Continue,
                });
            }
        }
Ejemplo n.º 17
0
        public override async Task <object> AuthenticateAsync(IServiceBase authService, IAuthSession session, Authenticate request, CancellationToken token = default)
        {
            IAuthTokens tokens      = Init(authService, ref session, request);
            IRequest    httpRequest = authService.Request;

            if (request?.AccessToken != null && request?.AccessTokenSecret != null)
            {
                var authInfo = await GetUserInfoAsync(request.AccessToken, request.AccessTokenSecret).ConfigAwait();

                if (authInfo == null || !(authInfo.Get("error") ?? authInfo.Get("error_description")).IsNullOrEmpty())
                {
                    Log.Error($"VK access_token error callback. {authInfo}");
                    return(HttpError.Unauthorized("AccessToken is not for App: " + ApplicationId));
                }

                tokens.AccessToken       = request.AccessToken;
                tokens.AccessTokenSecret = request.AccessTokenSecret;

                var isHtml       = authService.Request.IsHtml();
                var failedResult = await AuthenticateWithAccessTokenAsync(authService, session, tokens, request.AccessToken).ConfigAwait();

                if (failedResult != null)
                {
                    return(ConvertToClientError(failedResult, isHtml));
                }

                return(isHtml
                    ? authService.Redirect(SuccessRedirectUrlFilter(this, session.ReferrerUrl.SetParam("s", "1")))
                    : null); //return default AuthenticateResponse
            }

            string error = httpRequest.QueryString["error_reason"]
                           ?? httpRequest.QueryString["error_description"]
                           ?? httpRequest.QueryString["error"];

            bool hasError = !error.IsNullOrEmpty();

            if (hasError)
            {
                Log.Error($"VK error callback. {httpRequest.QueryString}");
                return(authService.Redirect(FailedRedirectUrlFilter(this, session.ReferrerUrl.SetParam("f", error))));
            }

            string code = httpRequest.QueryString["code"];
            bool   isPreAuthCallback = !code.IsNullOrEmpty();

            if (!isPreAuthCallback)
            {
                string preAuthUrl = $"{PreAuthUrl}?client_id={ApplicationId}&scope={Scope}&redirect_uri={CallbackUrl.UrlEncode()}&response_type=code&v={ApiVersion}";

                await this.SaveSessionAsync(authService, session, SessionExpiry, token).ConfigAwait();

                return(authService.Redirect(PreAuthUrlFilter(this, preAuthUrl)));
            }

            try {
                code = EnsureLatestCode(code);

                string accessTokeUrl = $"{AccessTokenUrl}?client_id={ApplicationId}&client_secret={SecureKey}&code={code}&redirect_uri={CallbackUrl.UrlEncode()}";

                string contents = await AccessTokenUrlFilter(this, accessTokeUrl).GetStringFromUrlAsync("*/*", RequestFilter).ConfigAwait();

                var authInfo = JsonObject.Parse(contents);

                //VK does not throw exception, but returns error property in JSON response
                string accessTokenError = authInfo.Get("error") ?? authInfo.Get("error_description");

                if (!accessTokenError.IsNullOrEmpty())
                {
                    Log.Error($"VK access_token error callback. {authInfo}");
                    return(authService.Redirect(session.ReferrerUrl.SetParam("f", "AccessTokenFailed")));
                }
                tokens.AccessTokenSecret = authInfo.Get("access_token");
                tokens.UserId            = authInfo.Get("user_id");

                session.IsAuthenticated = true;

                var accessToken = authInfo["access_token"];

                return(await OnAuthenticatedAsync(authService, session, tokens, authInfo.ToDictionary(), token).ConfigAwait()
                       ?? authService.Redirect(SuccessRedirectUrlFilter(this, session.ReferrerUrl.SetParam("s", "1"))));
            }
            catch (WebException webException)
            {
                //just in case VK will start throwing exceptions
                HttpStatusCode statusCode = ((HttpWebResponse)webException.Response).StatusCode;
                if (statusCode == HttpStatusCode.BadRequest)
                {
                    return(authService.Redirect(FailedRedirectUrlFilter(this, session.ReferrerUrl.SetParam("f", "AccessTokenFailed"))));
                }
            }
            return(authService.Redirect(FailedRedirectUrlFilter(this, session.ReferrerUrl.SetParam("f", "Unknown"))));
        }
Ejemplo n.º 18
0
 public static Response <Pedido> Delete(this Pedido request,
                                        Factory factory,
                                        IHttpRequest httpRequest)
 {
     throw HttpError.Unauthorized("Operacion Borrar no autorizada para Ofertas");
 }
Ejemplo n.º 19
0
        public override object Authenticate(IServiceBase authService, IAuthSession session, Authenticate request)
        {
            var tokens = Init(authService, ref session, request);

            //Transferring AccessToken/Secret from Mobile/Desktop App to Server
            if (request?.AccessToken != null)
            {
                if (!AuthHttpGateway.VerifyFacebookAccessToken(AppId, request.AccessToken))
                {
                    return(HttpError.Unauthorized("AccessToken is not for App: " + AppId));
                }

                var isHtml       = authService.Request.IsHtml();
                var failedResult = AuthenticateWithAccessToken(authService, session, tokens, request.AccessToken);
                if (failedResult != null)
                {
                    return(ConvertToClientError(failedResult, isHtml));
                }

                return(isHtml
                    ? authService.Redirect(SuccessRedirectUrlFilter(this, session.ReferrerUrl.SetParam("s", "1")))
                    : null); //return default AuthenticateResponse
            }

            var httpRequest = authService.Request;
            var error       = httpRequest.QueryString["error_reason"]
                              ?? httpRequest.QueryString["error"]
                              ?? httpRequest.QueryString["error_code"]
                              ?? httpRequest.QueryString["error_description"];

            var hasError = !error.IsNullOrEmpty();

            if (hasError)
            {
                Log.Error($"Facebook error callback. {httpRequest.QueryString}");
                return(authService.Redirect(FailedRedirectUrlFilter(this, session.ReferrerUrl.SetParam("f", error))));
            }

            var code = httpRequest.QueryString[Keywords.Code];
            var isPreAuthCallback = !code.IsNullOrEmpty();

            if (!isPreAuthCallback)
            {
                var preAuthUrl = $"{PreAuthUrl}?client_id={AppId}&redirect_uri={this.CallbackUrl.UrlEncode()}&scope={string.Join(",", Permissions)}&{Keywords.State}={session.Id}";

                this.SaveSession(authService, session, SessionExpiry);
                return(authService.Redirect(PreAuthUrlFilter(this, preAuthUrl)));
            }

            try
            {
                var accessTokenUrl = $"{AccessTokenUrl}?client_id={AppId}&redirect_uri={this.CallbackUrl.UrlEncode()}&client_secret={AppSecret}&code={code}";
                var contents       = AccessTokenUrlFilter(this, accessTokenUrl).GetJsonFromUrl();
                var authInfo       = JsonObject.Parse(contents);

                var accessToken = authInfo["access_token"];

                return(AuthenticateWithAccessToken(authService, session, tokens, accessToken)
                       ?? authService.Redirect(SuccessRedirectUrlFilter(this, session.ReferrerUrl.SetParam("s", "1")))); //Haz Access!
            }
            catch (WebException we)
            {
                var statusCode = ((HttpWebResponse)we.Response).StatusCode;
                if (statusCode == HttpStatusCode.BadRequest)
                {
                    return(authService.Redirect(FailedRedirectUrlFilter(this, session.ReferrerUrl.SetParam("f", "AccessTokenFailed"))));
                }
            }

            //Shouldn't get here
            return(authService.Redirect(FailedRedirectUrlFilter(this, session.ReferrerUrl.SetParam("f", "Unknown"))));
        }
Ejemplo n.º 20
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 (session.UserAuthId != null && authFeature != null)
                    {
                        if (authFeature.IncludeRolesInAuthenticateResponse)
                        {
                            authResponse.Roles ??= (manageRoles != null
                                ? manageRoles.GetRoles(session.UserAuthId)?.ToList()
                                : session.Roles);
                            authResponse.Permissions ??= (manageRoles != null
                                ? manageRoles.GetPermissions(session.UserAuthId)?.ToList()
                                : session.Permissions);
                        }
                        if (authFeature.IncludeOAuthTokensInAuthenticateResponse && AuthRepository != null)
                        {
                            var authDetails = AuthRepository.GetUserAuthDetails(session.UserAuthId);
                            if (authDetails?.Count > 0)
                            {
                                authResponse.Meta ??= new Dictionary <string, string>();
                                foreach (var authDetail in authDetails.Where(x => x.AccessTokenSecret != null))
                                {
                                    authResponse.Meta[authDetail.Provider + "-tokens"] = authDetail.AccessTokenSecret +
                                                                                         (authDetail.AccessToken != null ? ':' + authDetail.AccessToken : "");
                                }
                            }
                        }
                    }

                    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.GetReturnUrl() ?? this.Request.GetHeader(HttpHeaders.Referer);
                    if (isHtml && errorReferrerUrl != null && Request.GetParam(Keywords.NoRedirect) == null)
                    {
                        errorReferrerUrl = errorReferrerUrl.SetParam("f", ex.Message.Localize(Request));
                        return(HttpResult.Redirect(errorReferrerUrl));
                    }
                }

                throw;
            }
        }
Ejemplo n.º 21
0
        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);
        }