Beispiel #1
0
        public ActionResult UpdateMe()
        {
            VisitUserModel cuser = this.AppSiteUser();

            cuser.FirstName = "update nem";
            this.SiteAppRunner().SiteUser.Then(c => cuser).Cached(this.SessionId());

            return(Content("cahceuser:{0}".Fmt((new { cuser = this.AppSiteUser(), SfUser = this.SfUser() }).SerializeToString())));
        }
Beispiel #2
0
        private void ContextOperationEvent(IContextOperationEvent evt)
        {
            // 403 evnt
            var optContext             = new RequestContextEndEvent(HttpContext.Current);
            var reqUrl                 = optContext.OperationKey;
            NameValueCollection qryDic = null;
            var currentId              = Telerik.Sitefinity.Security.Claims.ClaimsManager.GetCurrentIdentity();

#if DEBUG
            log.DebugFormat("request for:{0}, status:{1}", reqUrl, optContext.Status);
#endif
            //log.Debug("status code from opt event:{0}".Fmt());
            //var optEvent = new MatrixGroup.Framework.SFEvents.RequestContextEndEvent().PopulateWith(evt);
            if (optContext.Status == "403")
            {
                VisitUserModel vuser = MxAppHost.Instance.Container.Resolve <ISiteUser>() as VisitUserModel ?? new VisitUserModel();
#if DEBUG
                log.Info("403-isAuth:{0}, usfid:{1}".Fmt(currentId.IsAuthenticated, vuser.UserId));
#endif
                //if (vuser.UserId.IsNullOrEmptyGuid())
                if (!currentId.IsAuthenticated)
                {
                    HttpContext.Current.Response.Redirect("{0}?ReturnUrl={1}".Fmt(GetLoginPage, reqUrl.UrlEncode()));
                }
                else
                {
                    HttpContext.Current.Response.Redirect("{0}?ReturnUrl={1}".Fmt("~/account/not-authorized", reqUrl.UrlEncode()));
                }
            }
            if (optContext.Status == "404")
            {
                //HttpContext.Current.Response.Redirect("~/common/404?ReturnUrl={0}".Fmt(reqUrl.UrlEncode()));
            }

            //var n = new MatrixGroup.Framework.SFEvents.RequestContextEndEvent(HttpContext.Current);
            //log.Debug("status code from opt event:{0}".Fmt(new {resp= RespStatus, hstatus = n.Status}.SerializeToString()));
        }
Beispiel #3
0
        public override void Configure(Container container)
        {
            log = LogManager.GetLogger(typeof(ServiceBootstrap));
            JsConfig.IncludeNullValues = true;
            //JsConfig<DateTime>.SerializeFn = time => new DateTime(time.Ticks, DateTimeKind.Local).ToString();

            //ServiceStack.Text.JsConfig.EmitCamelCaseNames = true; <- cause an issue with SF module do not turn on

            //ServiceStack.Text.JsConfig<Guid>.SerializeFn = guid => guid.ToString();
            container.Register <ICacheClient>(new MemoryCacheClient());

            /*CommonServiceConnectionModel initConfigSv = FluentSiteUser<CommonServiceConnectionModel>
             *  .InitFromCacheOrDefault(new CommonServiceConnectionModel()
             * {
             *  ClientId = "29192542",
             *  EndpointUrl = "https://test.myhelix.org/App",
             *  SecretKey = "Bi4IB9Yhh5PrOa3y7PykntuQKg90ZNDiNes7tDNfwwKDgYIz4v",
             *  RedirectUrl = "https://iafc.matrixdev.net/Mxg/AuthService" //"https://iafc.matrixdev.net"
             * }, "siteConn").Instance();*/
            /*CommonServiceConnectionModel initConfigSv = new CommonServiceConnectionModel()
             * {
             *  ClientId = "29192542",
             *  EndpointUrl = "https://test.myhelix.org/App",
             *  SecretKey = "Bi4IB9Yhh5PrOa3y7PykntuQKg90ZNDiNes7tDNfwwKDgYIz4v",
             *  RedirectUrl = "https://iafc.matrixdev.net/Mxg/AuthService" //"https://iafc.matrixdev.net"
             * };
             *
             * VisitUserModel stateUser = this.GetCurrentUser.Instance() as VisitUserModel;
             * container.Register<ISiteAppRunner<HelixServiceClient>>(c =>
             * {
             *  var sruner = new SiteAppRunner<HelixServiceClient>(initConfigSv)
             *  {
             *      // should site user always reflect the current state or get default?
             *      SiteUser = this.GetCurrentUser,
             *      AppServiceClient = new AppServiceClient<HelixServiceClient>(),
             *      ServiceConnection = initConfigSv
             *  };
             *
             *  /*FluentSiteUser<ISiteUser>.Init(this.GetCurrentUser.Instance()).Cached("siteUser");
             *  FluentSiteUser<IServiceConnection>.Init(initConfigSv).Cached("siteConn");#1#
             *
             *  return sruner;
             * });*/
            //SfAppSettingsConfig mappconf =Telerik.Sitefinity.Configuration.Config.Get<SfAppSettingsConfig>();//["DomainName"];

            CommonServiceConnectionModel initConn = new CommonServiceConnectionModel()
            {
                ClientId    = "29192542",
                EndpointUrl = System.Configuration.ConfigurationManager.AppSettings["helixApp"],
                SecretKey   = "Bi4IB9Yhh5PrOa3y7PykntuQKg90ZNDiNes7tDNfwwKDgYIz4v",
                //RedirectUrl = "https://{0}/Mxg/AuthService".Fmt("iafc.matrixdev.net"), //"https://iafc.matrixdev.net"
                RedirectUrl = "https://{0}/Mxg/AuthService".Fmt(System.Configuration.ConfigurationManager.AppSettings["domainName"]), //"https://iafc.matrixdev.net"
            };

            initConn.SignInUrl = "{0}/OAuth/Authorize?client_id={1}&redirect_uri={2}&scope=basic,membership&state=blah&response_type=code"
                                 .Fmt(System.Configuration.ConfigurationManager.AppSettings["helixApp"], initConn.ClientId, initConn.RedirectUrl);
            initConn.SignOutUrl = "{0}/logout/{1}".Fmt(initConn.EndpointUrl, initConn.ClientId);


            container.Register <IServiceConnection>(c => initConn);
            //
            container.Register <IDbConnectionFactory>(
                c =>
                new OrmLiteConnectionFactory(
                    System.Configuration.ConfigurationManager.ConnectionStrings[
                        "Simple.Data.Properties.Settings.DefaultConnectionString"].ConnectionString,
                    SqlServerDialect.Provider));

            using (var db = container.Resolve <IDbConnectionFactory>().Open())
            {
                //db.DropAndCreateTable<GenericResultSerialized>();
                db.CreateTableIfNotExists <GenericResultSerialized>();
            }

            //Database.OpenConnection(DatabaseHelper.ConnectionString)

            /*using (SqlConnection cnn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Simple.Data.Properties.Settings.DefaultConnectionString"].ConnectionString))
             * {
             *  var cmd = cnn.CreateCommand();
             *  cnn.Open();
             *  cmd.CommandText = @"
             *  --if (OBJECT_ID('Mx_GenericResult') is not null)
             * --begin
             * --    TRUNCATE TABLE Mx_GenericResult
             * --end
             *  if (OBJECT_ID('Mx_GenericResult') is null)
             *  begin
             *          create table Mx_GenericResult(
             *          Id int identity primary key,
             * SessionId varchar(200),
             *          [Data] varchar(max),
             * [User] varchar(max),
             * [Message] varchar(250),
             *          CreationDate datetime not null,
             *          LastChangeDate datetime not null)
             *      end
             *  ";
             *  cmd.Connection = cnn;
             *  cmd.ExecuteNonQuery();
             * }
             * dynamic db = Database.Open();
             * //db.Mx_GenericResult.Insert(User: VisitUser.SerializeToString(), Message: "init", Data: "", CreationDate: DateTime.UtcNow, LastChangeDate:DateTime.UtcNow);
             * //db.Mx_GenericResult.Insert(new GenericResultSerialized() {User = new VisitUserModel().SerializeToString(), Message = "init", CreationDate = DateTime.UtcNow, LastChangeDate = DateTime.UtcNow});
             * log.Info("mxapp: get frpm db");
             * //Simple.Data.ObjectReference
             * object genresult = db.Mx_GenericResult.FindbyId(1);
             *  log.Info("mxapp: get :{0}".Fmt(genresult.SerializeToString()));*/

            VisitUserModel vUser = new VisitUserModel()
            {
                UserId       = Guid.Empty.OneGuid(),
                ClientId     = "", //System.Web.Security.Membership.GeneratePassword(16,6),
                SignInStatus = SfSignInStatus.Unknown,
                ReturnUrl    = "~/",
                FirstName    = "initUser"
            };


            // lazy load within the container
            container.Register <ISiteAppRunner>(m =>
            {
                var sessionId = System.Web.HttpContext.Current.GetCkSessionId();
                return(new SiteAppRunner(initConn)
                {
                    //this potential to create multiple cache user
                    SiteUser = FluentSiteUser <ISiteUser>
                               .InitFromCacheOrDefault(vUser, sessionId)
                               .Then(c =>
                    {
                        VisitUserModel usr = c as VisitUserModel;
                        var ck = HttpContext.Current.Request;
                        Guid uid = ClaimsManager.GetCurrentIdentity().UserId;
                        SiteVisitorSessionCmd scmd = new SiteVisitorSessionCmd();
                        //get from db is have one
                        //dynamic db = Database.Open();
                        GenericResultSerialized _vuser = scmd.GetVisitorBySessionId(sessionId);     //db.Mx_GenericResult.FindBySessionId(sessionId);
#if DEBUG
                        log.Warn("mxapp: in container for user: {0}, cacheID:{1}, user:{2}".Fmt(uid, sessionId, usr.SerializeToString()));
#endif
                        if (_vuser != null)
                        {
                            vUser = _vuser.User.FromJson <VisitUserModel>();
#if DEBUG
                            log.Info("mxapp: from db: {0}".Fmt(vUser.SerializeToString()));
#endif
                            return vUser;
                        }
                        // only for Auth session, but missing user email then prepopulate

                        /*if (!uid.IsNullOrEmptyGuid() && String.IsNullOrEmpty(usr.Email))
                         * {
                         *  vUser = new HelixServiceClient(initConn, new SFAuthenServiceByHelixResponse(
                         *      UserManager.GetManager(UserManager.GetDefaultProviderName()),
                         *      UserProfileManager.GetManager(UserProfileManager.GetDefaultProviderName())
                         *      ), vUser).InitUserByUserId(uid, ref usr).Entity as VisitUserModel;
                         * }*/
                        // update session id
                        if (!String.IsNullOrEmpty(sessionId) && usr.SessionId != sessionId)
                        {
                            usr.UpdateSessionId(sessionId);
                        }

                        /*db.Mx_GenericResult.Insert(new GenericResultSerialized()
                         * {
                         *  SessionId = sessionId,
                         *  CreationDate = DateTime.UtcNow,
                         *  LastChangeDate = DateTime.UtcNow,
                         *  Message = "new init from site app",
                         *  User = usr.SerializeToString()
                         * });*/
                        scmd.UpdateBySessionId(sessionId, new GenericResultSerialized()
                        {
                            SessionId = sessionId,
                            CreationDate = DateTime.UtcNow,
                            LastChangeDate = DateTime.UtcNow,
                            Message = "new init from site app",
                            User = usr.SerializeToString()
                        });
                        return usr;
                    }),

                    ServiceConnection = initConn,
                    AppServiceClient = FluentSiteUser <IAppServiceClient> .Init(new HelixServiceClient(initConn,
                                                                                                       new SFAuthenServiceByHelixResponse(
                                                                                                           UserManager.GetManager(UserManager.GetDefaultProviderName()),
                                                                                                           UserProfileManager.GetManager(UserProfileManager.GetDefaultProviderName())
                                                                                                           ), vUser))
                });
            }).ReusedWithin(ReuseScope.Container);
            container.Register <IServiceConnection>(c => initConn).ReusedWithin(ReuseScope.Request);

            /*container.Register<IAuthServiceResponse>(c =>
             * {
             *  SFAuthenServiceByHelixResponse ss = new SFAuthenServiceByHelixResponse(
             *      UserManager.GetManager(UserManager.GetDefaultProviderName()),
             *      UserProfileManager.GetManager(UserProfileManager.GetDefaultProviderName()));
             *  return ss;
             * }).ReusedWithin(ReuseScope.Request);*/

            container.Register <UserManager>(c => UserManager.GetManager(UserManager.GetDefaultProviderName())).ReusedWithin(ReuseScope.Request);
            container.Register <UserProfileManager>(c => UserProfileManager.GetManager()).ReusedWithin(ReuseScope.Request);
            container.Register <ISiteUser>(c => new VisitUserModel());

            //container.Register<ISoapConnection>(c => new IndividualSoapCmd("http://iafcimisapp1.iafc.org/webservicestest/wscontacts.asmx"));
        }
Beispiel #4
0
        public ActionResult Index(string code = "")
        {
            //return Content(String.Format("access code: {0}", code));
            if (SystemManager.IsDesignMode || SystemManager.IsPreviewMode)
            {
                return(View("Index"));
            }
            this.CreateOrUpdateCookie("cd", code);

            QueryDataResponse <HelixIndividual> qryIndv = new QueryDataResponse <HelixIndividual>()
            {
                ResponseStatus = ResponseStatus.Warning
            };
            //VisitUserModel bfAuth = this.GetSetAppSiteUser();
            VisitUserModel authUser  = new VisitUserModel(); //this.GetSessionInforByUserId(this.MyId()).ToVisitUserModel();
            string         returnUrl = this.GetCookieValue("reqUri");

#if DEBUG
            log.InfoFormat("myId in login:{0}, code:{1}", this.MyId(), code);
#endif

            // if not login & have a code then do authentication
            if ((this.MyId().IsNullOrEmptyGuid() || this.MyId().IsOneGuid()) && !String.IsNullOrEmpty(code))
            {
                this.SiteAppRunner().AppServiceClient
                .Then(cl =>
                {
                    HelixServiceClient client = cl as HelixServiceClient;
                    HelixIndividual helixIndv = new HelixIndividual();

                    client.ActivateHelixbyCode(code);
                    qryIndv = client.DataResponse();
                    if (qryIndv.ResponseStatus.Is(ResponseStatus.Success))
                    {
                        helixIndv = qryIndv.Result;

                        // RWB 20171013 Test
                        this.CreateOrUpdateCookie("IAFC", $"ContactId={helixIndv.MembershipId}&Password=H5erUjDICjI7EM4zJG3%2byg%3d%3d");
                        // RWB 20171013 Test

                        // RWB 20171012 - Username must be an email address for new accounts
                        helixIndv.UserName   = helixIndv.Email;
                        VisitUserModel _vusr = helixIndv;     // derived from the same class base
                        _vusr.ClientId       = helixIndv.Client_id;
                        _vusr.Title          = helixIndv.Title;
                        _vusr.ClientToken    = new ServiceTokenModel()
                        {
                            ClientId      = helixIndv.MembershipId,
                            ClientName    = helixIndv.Email,
                            Token         = helixIndv.access_token,
                            IssueTime     = DateTime.UtcNow,
                            ExpireTime    = DateTime.UtcNow.AddMinutes(12),
                            Refresh_token = helixIndv.Refresh_token,
                            Message       = (new HelixIndividual()
                            {
                                Title = helixIndv.Title, Client_id = helixIndv.Client_id, MembershipId = helixIndv.MembershipId
                            }).SerializeToString()
                                            //Message = (new { Title = helixIndv.Title, MembershipId = helixIndv.MembershipId, Client_id = helixIndv.Client_id }).ToJson()
                        };
                        _vusr.ReturnUrl = returnUrl;
                        _vusr.Profile   = new VisitorProfile()
                        {
                            Roles = new List <UserRole>()
                            {
                                new UserRole()
                                {
                                    Name = "NonMember"
                                }
                            }
                        };

                        /*if (!String.IsNullOrEmpty(helixIndv.MembershipId))
                         * {
                         *  _vusr.Profile.Roles = new List<UserRole>() { new UserRole() { Name = "Member" } };
                         * }*/
                        if (!String.IsNullOrEmpty(helixIndv.roles) && helixIndv.roles.ToLower().IndexOf("iafcmember") >= 0)
                        {
                            _vusr.Profile.Roles = new List <UserRole>()
                            {
                                new UserRole()
                                {
                                    Name = "Member"
                                }
                            };
                        }


#if DEBUG
                        log.InfoFormat("convert user from Helix is: {0}",
                                       (new
                        {
                            helix = helixIndv,
                            Vuser = _vusr,
                            ActivateMis = String.Format("{0}/{1}/{2}/true", ConfigurationManager.AppSettings["iMiSLoginBaseUri"]?.ToString(),
                                                        ConfigurationManager.AppSettings["iMiSLogin"], _vusr.UserName),
                        }).SerializeToString());
#endif

                        /*client
                         * .LoginToIMis(System.Web.HttpContext.Current, ConfigurationManager.AppSettings["iMiSLoginBaseUri"],
                         * ConfigurationManager.AppSettings["iMiSLogin"], ((VisitorModel)_vusr).UserName);*/


                        this.CreateOrUpdateCookie("ud", _vusr.ClientId);


                        QueryDataResponse <VisitUserModel> sfResponse = new QueryDataResponse <VisitUserModel>();
                        client.AuthenticateBy((cnn, _srv) =>
                        {
                            sfResponse = _srv.GetAuthResponse(_vusr);

                            if (sfResponse.ResponseStatus.Is(ResponseStatus.Success))
                            {
                                // login to iMIS

                                /*client
                                 * .LoginToIMis(ConfigurationManager.AppSettings["iMiSLoginBaseUri"],
                                 * ConfigurationManager.AppSettings["iMiSLogin"], ((VisitorModel)_vusr).UserName);*/

                                //this.CreateOrUpdate("hlsession", sfResponse.Result.ClientId);
                                //this.SiteAppRunner().SiteUser = FluentSiteUser<ISiteUser>.Init(sfResponse.Result).Cached(this.SessionId());
                                var _updateModel = sfResponse.Result;
                                var _cacheUser   = new GenericResultSerialized()
                                {
                                    User           = _updateModel.SerializeToString(),
                                    SessionId      = "123",//this.SessionId(),
                                    UserId         = _updateModel.UserId,
                                    Message        = "init from Auth",
                                    CreationDate   = DateTime.UtcNow,
                                    LastChangeDate = DateTime.UtcNow,
                                    // RWB 20170911 - Removed contactID ContactId = helixIndv.MembershipId,
                                    Data = helixIndv.ToJson <HelixIndividual>(),
                                };
                                //_updateModel.UpdateSessionId(this.SessionId());
                                //this.GetSetAppSiteUser(sfResponse.Result);
                                //this.SetAppSiteUser(_updateModel.UserId, _cacheUser);

#if DEBUG
                                log.Info("update user to cache:{0} by id:".Fmt(new
                                {
                                    cache    = _cacheUser,
                                    sessonid = "123",    //this.SessionId(),
                                    data     = _updateModel
                                }.SerializeToString()));
#endif
                            }
                            else
                            {
                                log.Warn("issue with auth with SF:{0}".Fmt(sfResponse.Message));
                            }
                            authUser = _vusr;
                            return(_vusr);
                        });
                    }
                    return(cl);
                });
            }

            // to show as a button then this need to be checked
            if (ShowLoginForm)
            {
                return(View("Index"));
            }
            // or last step is to redirect back

            if (!SystemManager.IsDesignMode || !SystemManager.IsPreviewMode)
            {
                //return Redirect(authUser.ReturnUrl.DefaultIfNullEmpty("/"));
                if (this.MyId().IsNullOrEmptyGuid())
                {
                    log.InfoFormat("auth-noCode:{0}", HttpContext.Request?.Url?.AbsolutePath);
                    return(Redirect("/"));
                }
                return(Redirect(returnUrl.DefaultIfNullEmpty("/")));
                //return Redirect("http://members.iafc.org/helix/MembershipSignIn/ktomko/true");
            }

            return(View("Index"));
        }