Ejemplo n.º 1
0
        public async Task AmbientSessionContextFlow(int it, int delay)
        {
            var session = new BaseSession(Guid.NewGuid(), 0);
            var user    = new User(new IDPasswordCredentials("a", "b"), new SysAuthToken(), "User1", Rights.None);

            session.DataContextName = "abcd";
            session.User            = user;
            ExecutionContext.__SetThreadLevelSessionContext(session);

            checkAmbientSession("User1");

            for (var i = 0; i < it; i++)
            {
                await Task.Delay(delay)//note: Task.Yield() yields on the same thread if there is no load
                .ContinueWith(a => TaskUtils.LoadAllCoresFor(delay))
                .ContinueWith(a => checkAmbientSession("User1"));
            }

            //---------- switch user in-place --------------------
            "Switching user in-place".See();

            session.User = new User(new IDPasswordCredentials("a", "b"), new SysAuthToken(), "User2", Rights.None);
            checkAmbientSession("User2");

            for (var i = 0; i < it; i++)
            {
                await Task.Delay(delay)
                .ContinueWith(a => TaskUtils.LoadAllCoresFor(delay))
                .ContinueWith(a => checkAmbientSession("User2"));
            }
        }
Ejemplo n.º 2
0
            public FindCommandResult FindCommand(string cmd)
            {
                Debug.Log("Searching for: " + cmd);
                FindCommandResult result = new FindCommandResult();

                string [] envPathSplit = BaseSession.GetEnvValue("PATH").Split(new char[] { ':' });

                for (int i = 0; i < envPathSplit.Length; i++)
                {
                    NixPath path = new NixPath(envPathSplit[i]);
                    path.AppendPath(cmd);
                    if (RootDrive.IsFile(path))
                    {
                        result.Path    = path.ToString();
                        result.Builtin = false;
                        result.Found   = true;
                        return(result);
                    }
                }

                if (BinPrograms.ContainsKey(cmd))
                {
                    result.Path    = cmd;
                    result.Builtin = true;
                    result.Found   = true;
                    return(result);
                }

                result.Found = false;
                return(result);
            }
Ejemplo n.º 3
0
        public void GetIdleTimeMilliseconds_increases_over_time()
        {
            var session = new BaseSession(null);

            Thread.Sleep(20);
            Assert.InRange(session.GetIdleTime().TotalMilliseconds, 15, 100);
        }
Ejemplo n.º 4
0
        public WCFReturnResult ResetPwd(WCFAuthInfoVM entity_WCFAuthInfoVM, LoginUserVM entity_LUVM)
        {
            try
            {
                //Restore Server Session
                WCFReturnResult   returnResult       = new WCFReturnResult();
                WCFSesssionPolicy wcfPolicy          = new WCFSesssionPolicy();
                BaseSession       entity_BaseSession = wcfPolicy.RestoreWCFSesssion(entity_WCFAuthInfoVM);

                //Contruct Login User Respository
                CoolPrivilegeControlContext dbContext      = CoolPrivilegeControlContext.CreateContext();
                LoginUserRespository        loginUserRespo = new LoginUserRespository(dbContext, entity_BaseSession.ID);

                List <string> strList_Error = new List <string>();

                var ret = loginUserRespo.ResetPwd(entity_LUVM, languageKey, ref strList_Error);

                returnResult.IsSuccess = ret;

                if (strList_Error.Count > 0)
                {
                    foreach (var item in strList_Error)
                    {
                        returnResult.StrList_Error.Add(item);
                    }
                }

                return(returnResult);
            }
            catch (Exception ex)
            {
                throw new FaultException <WCFErrorContract>(new WCFErrorContract(ex), ex.Message);
            }
        }
Ejemplo n.º 5
0
        public void DataContextNorm(string dcn, string norm)
        {
            var session = new BaseSession(Guid.NewGuid(), 0);

            session.DataContextName = dcn;
            session.GetNormalizedDataContextName();
        }
Ejemplo n.º 6
0
        private void impersonate(Credentials credentials)
        {
            var session = new BaseSession(Guid.NewGuid(), 1234);

            session.User = m_App.SecurityManager.Authenticate(credentials);
            Azos.Apps.ExecutionContext.__SetThreadLevelSessionContext(session);
        }
Ejemplo n.º 7
0
 /// <summary>
 /// Constructor. Protected because we don't want anyone creating a base class instance.
 /// </summary>
 protected BaseCommand()
 {
     DG200FileLogger.Log("BaseCommand constructor.", 3);
     this._session          = null;
     this._currentResult    = null;
     this._serialConnection = null;
 }
Ejemplo n.º 8
0
        public void DataContextNorm(string dcn, string norm)
        {
            var session = new BaseSession(Guid.NewGuid(), 0);

            session.DataContextName = dcn;
            var got = session.GetNormalizedDataContextName();

            Aver.AreEqual(norm, got);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Shortcut method that creates a temp/mock BaseSession object thus checking permission in mock BaseSession context
        /// </summary>
        public Task <bool> CheckAsync(IApplication app, User user)
        {
            if (user == null || !user.IsAuthenticated)
            {
                return(Task.FromResult(false));
            }
#warning May avoid heap allocation here by implementing SessionStub as struct
            var session = new BaseSession(Guid.NewGuid(), app.Random.NextRandomUnsignedLong);
            session.User = user;
            return(this.CheckAsync(app, session));
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Shortcut method that creates a temp/mock BaseSession object thus checking permission in mock BaseSession context
        /// </summary>
        public bool Check(IApplication app, User user)
        {
            if (user == null || !user.IsAuthenticated)
            {
                return(false);
            }
            var session = new BaseSession(Guid.NewGuid(), app.Random.NextRandomUnsignedLong);

            session.User = user;
            return(this.Check(app, session));
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Shortcut method that creates a temp/mock BaseSession object thus checking permission in mock BaseSession context
        /// </summary>
        public bool Check(User user)
        {
            if (user == null || !user.IsAuthenticated)
            {
                return(false);
            }
            var session = new BaseSession(Guid.NewGuid());

            session.User = user;
            return(this.Check(session));
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Shortcut method that creates a temp/mock BaseSession object thus checking permission in mock BaseSession context
        /// </summary>
        public Task <bool> CheckAsync(ISecurityManager secman, User user)
        {
            secman.NonNull(nameof(secman));
            if (user == null || !user.IsAuthenticated)
            {
                return(Task.FromResult(false));
            }
            var session = new BaseSession(Guid.NewGuid(), secman.App.Random.NextRandomUnsignedLong);

            session.User = user;
            return(this.CheckAsync(secman, session));
        }
Ejemplo n.º 13
0
        /** 处理服务器收到的帧
         */
        public void Execute(BaseSession session, Frame frame)
        {
            byte[] body = null;
            if (frame.IsBodyHasDataInStream() == false && frame.GetTotalBodySize() > 0)
            {
                body = frame.GetBodyBytes();
                string info = Encoding.UTF8.GetString(body, 0, body.Length);
                Console.WriteLine("客户端发过来:" + info + "【CmdHeartbeat】");
            }

            Frame frm_send = new Frame(frame.GetFrameSerialNumber(), GetT(), body); //要发给客户端的帧

            session.Send(frm_send);
        }
Ejemplo n.º 14
0
        /** 处理服务器收到的帧
         */
        public void Execute(BaseSession session, Frame frame)
        {
            if (frame.IsBodyHasDataInStream() == false && frame.GetTotalBodySize() > 0)
            {
                //客户端发过来的是UFT-8字符串
                byte[] body = frame.GetBodyBytes();
                string info = Encoding.UTF8.GetString(body, 0, body.Length);
                Console.WriteLine("客户端发过来:" + info + "【CmdHello】");
            }

            //服务器回应"Hello"字符串
            string replay = "Hello";

            byte[] replay_body = Encoding.UTF8.GetBytes(replay);
            Frame  frm_send    = new Frame(frame.GetFrameSerialNumber(), GetT(), replay_body); //要发给客户端的帧

            session.Send(frm_send);
        }
Ejemplo n.º 15
0
        /// <inheritdoc />
        /// <exception cref="ArgumentNullException">
        /// Thrown if <paramref name="endpointCrypto"/> or <paramref name="handshakeInfo"/> are <see langword="null"/>.
        /// </exception>
        public void Start(EndpointCrypto endpointCrypto, HandshakeInfo handshakeInfo)
        {
            if (endpointCrypto == null)
            {
                throw new ArgumentNullException(nameof(endpointCrypto));
            }
            if (handshakeInfo == null)
            {
                throw new ArgumentNullException(nameof(handshakeInfo));
            }

            ThrowIfNoPacketReceivedSubscriber();

            Crypto = endpointCrypto;

            byte[] handshake = ConstructHandshakePacket(handshakeInfo);
            BaseSession.Start();
            BaseSession.Write(handshake);
        }
Ejemplo n.º 16
0
        public int GetTotalAuthorizationCount(WCFAuthInfoVM entity_WCFAuthInfoVM)
        {
            try
            {
                WCFSesssionPolicy wcfPolicy = new WCFSesssionPolicy();

                CoolPrivilegeControlContext dbContext = CoolPrivilegeControlContext.CreateContext();

                BaseSession entity_BaseSession = wcfPolicy.RestoreWCFSesssion(entity_WCFAuthInfoVM);

                AuthorizedHistoryRespository authorizedHistoryRespo = new AuthorizedHistoryRespository(dbContext, entity_BaseSession.ID);
                int int_Counter = authorizedHistoryRespo.GetTotalAuthorizationCount(OperationType.L);

                return(int_Counter);
            }
            catch (Exception ex)
            {
                throw new FaultException <WCFErrorContract>(new WCFErrorContract(ex), ex.Message);
            }
        }
Ejemplo n.º 17
0
        /** 处理服务器收到的帧
         */
        public void Execute(BaseSession session, Frame frame)
        {
            byte[] body = null;
            if (frame.IsBodyHasDataInStream() == false && frame.GetTotalBodySize() > 0)
            {
                body = frame.GetBodyBytes();
                string info = Encoding.UTF8.GetString(body, 0, body.Length);
                Console.WriteLine("客户端发过来:" + info + "【CmdBye】");
            }

            //服务器回应"Bye"字符串
            string replay = "Bye ! Close session now !";

            byte[] replay_body = Encoding.UTF8.GetBytes(replay);
            Frame  frm_send    = new Frame(frame.GetFrameSerialNumber(), GetT(), replay_body); //要发给客户端的帧

            session.Send(frm_send);

            //服务器关闭Session
            session.SetOffline();
        }
Ejemplo n.º 18
0
        public void LoginAndGetToken()
        {
            string str_Token = "";

            LoginUserMgtHelper loginUserMgtHelper = new LoginUserMgtHelper(postOffice.LoginUserMgtSerPath);

            LoginUserVM entity_LUVM = new LoginUserVM();

            entity_LUVM.LoginName = "admin";
            entity_LUVM.LoginPwd  = "123456";

            LUSerLoginResult loginResult = loginUserMgtHelper.Login(entity_LUVM, LanguageKey.ToString(), "", "");

            if (loginResult != null)
            {
                str_Token = loginResult.Str_ServerToken;

                entity_BaseSession = loginResult.Entity_SessionWUserInfo;
            }
            StrToken = str_Token;
        }
Ejemplo n.º 19
0
 public void GetIdleTimeMilliseconds_increases_over_time()
 {
     var session = new BaseSession(null);
     Thread.Sleep(20);
     Assert.InRange(session.GetIdleTime().TotalMilliseconds, 15, 100);
 }
Ejemplo n.º 20
0
 /// <summary>
 /// Initializes a new instance of the BaseStatement class based on the specified session.
 /// </summary>
 /// <param name="session">The session where the statement will be executed.</param>
 public BaseStatement(BaseSession session)
 {
     Session = session;
 }
Ejemplo n.º 21
0
 public void GetIdleTimeMilliseconds_starts_at_zero()
 {
     var session = new BaseSession(null);
     Assert.InRange(session.GetIdleTime().TotalMilliseconds, 0, 15);
 }
Ejemplo n.º 22
0
 /// <summary>
 /// Initializes a new instance of the BaseStatement class based on the specified session.
 /// </summary>
 /// <param name="session">The session where the statement will be executed.</param>
 public BaseStatement(BaseSession session)
 {
     Session     = session;
     _hasChanged = true;
 }
Ejemplo n.º 23
0
        public void GetIdleTimeMilliseconds_starts_at_zero()
        {
            var session = new BaseSession(null);

            Assert.InRange(session.GetIdleTime().TotalMilliseconds, 0, 15);
        }
Ejemplo n.º 24
0
 private void LimpiarSession()
 {
     BaseSession.Logout();
 }
Ejemplo n.º 25
0
        /// <summary>
        /// Creates a <see cref="FailoverGroup"/> if more than one host is found.
        /// </summary>
        /// <param name="hierPart">A string containing an unparsed list of hosts.</param>
        /// <param name="isXProtocol"><c>true</c> if the connection is X Protocol; otherwise <c>false</c>.</param>
        /// <param name="connectionDataIsUri"><c>true</c> if the connection data is a URI; otherwise <c>false</c>.</param>
        /// <returns>The number of hosts found, -1 if an error was raised during parsing.</returns>
        internal static int ParseHostList(string hierPart, bool isXProtocol, bool connectionDataIsUri = true)
        {
            if (string.IsNullOrWhiteSpace(hierPart))
            {
                return(-1);
            }

            int            hostCount      = -1;
            FailoverMethod failoverMethod = FailoverMethod.Random;

            string[] hostArray             = null;
            List <FailoverServer> hostList = new List <FailoverServer>();

            hierPart = hierPart.Replace(" ", "");

            if (!hierPart.StartsWith("(") && !hierPart.EndsWith(")"))
            {
                hostArray = hierPart.Split(',');
                if (hostArray.Length == 1)
                {
                    return(1);
                }

                foreach (var host in hostArray)
                {
                    hostList.Add(ConvertToFailoverServer(host, connectionDataIsUri: connectionDataIsUri));
                }

                hostCount = hostArray.Length;
            }
            else
            {
                string[] groups          = hierPart.Split(new string[] { "),(" }, StringSplitOptions.RemoveEmptyEntries);
                bool?    allHavePriority = null;
                int      defaultPriority = -1;
                foreach (var group in groups)
                {
                    // Remove leading parenthesis.
                    var normalizedGroup = group;
                    if (normalizedGroup.StartsWith("("))
                    {
                        normalizedGroup = group.Substring(1);
                    }

                    if (normalizedGroup.EndsWith(")"))
                    {
                        normalizedGroup = normalizedGroup.Substring(0, normalizedGroup.Length - 1);
                    }

                    string[] items         = normalizedGroup.Split(',');
                    string[] keyValuePairs = items[0].Split('=');
                    if (keyValuePairs[0].ToLowerInvariant() != "address")
                    {
                        throw new KeyNotFoundException(string.Format(ResourcesX.KeywordNotFound, "address"));
                    }

                    string host = keyValuePairs[1];
                    if (string.IsNullOrWhiteSpace(host))
                    {
                        throw new ArgumentNullException("server");
                    }

                    if (items.Length == 2)
                    {
                        if (allHavePriority != null && allHavePriority == false)
                        {
                            throw new ArgumentException(ResourcesX.PriorityForAllOrNoHosts);
                        }

                        allHavePriority = allHavePriority ?? true;
                        keyValuePairs   = items[1].Split('=');
                        if (keyValuePairs[0].ToLowerInvariant() != "priority")
                        {
                            throw new KeyNotFoundException(string.Format(ResourcesX.KeywordNotFound, "priority"));
                        }

                        if (string.IsNullOrWhiteSpace(keyValuePairs[1]))
                        {
                            throw new ArgumentNullException("priority");
                        }

                        int priority = -1;
                        Int32.TryParse(keyValuePairs[1], out priority);
                        if (priority < 0 || priority > 100)
                        {
                            throw new ArgumentException(ResourcesX.PriorityOutOfLimits);
                        }

                        if (isXProtocol)
                        {
                            hostList.Add(ConvertToFailoverServer(BaseSession.IsUnixSocket(host) ? BaseSession.NormalizeUnixSocket(host) : host, priority, connectionDataIsUri: connectionDataIsUri));
                        }
                        else
                        {
                            hostList.Add(ConvertToFailoverServer(host, priority));
                        }
                    }
                    else
                    {
                        if (allHavePriority != null && allHavePriority == true)
                        {
                            throw new ArgumentException(ResourcesX.PriorityForAllOrNoHosts);
                        }

                        allHavePriority = allHavePriority ?? false;

                        hostList.Add(ConvertToFailoverServer(host, defaultPriority, connectionDataIsUri: connectionDataIsUri));
                    }
                }

                hostCount = groups.Length;
                if (hostList.GroupBy(h => h.Priority).ToList().Count > 1)
                {
                    failoverMethod = FailoverMethod.Priority;
                }
                else
                {
                    failoverMethod = FailoverMethod.Random;
                }
            }

            SetHostList(hostList, failoverMethod);
            return(hostCount);
        }
Ejemplo n.º 26
0
        /** 处理服务器收到的帧
         */
        public void Execute(BaseSession session, Frame frame)
        {
            Console.WriteLine("客户端发过来:上传文件(" + frame.GetTotalBodySize() + "字节)【CmdUploadFile】");

            UInt16 SN = 0;

            //上传文件使用这样的嵌套的 TLV 帧结构,TLV1(V1=TLV2+TLV3):T1=UPLOADFILE,T2=FILENAME,T3=FILEDATA
            UInt16 t_file_name = 0; //T2 - FILENAME(文件名)
            UInt16 t_file_data = 0; //T3 - FILEDATA(文件数据)

            //检查是大型帧(没有字节数组,只有流对象),还是小型帧(只有字节数组,没有流对象)
            BinaryReader br = null;

            if (frame.IsBodyHasDataInStream())
            {
                br = frame.GetBodyStream(); //大型帧
            }
            #region STLV2 - FILENAME(文件名)

            //帧序列号 - 子帧的序列号是0
            if (frame.IsBodyHasDataInStream())
            {
                SN = br.ReadUInt16();
            }
            else
            {
                SN = BitConverter.ToUInt16(frame.GetBodyBytes(), 0);
            }

            //帧类型值
            if (frame.IsBodyHasDataInStream())
            {
                t_file_name = br.ReadUInt16();
            }
            else
            {
                t_file_name = BitConverter.ToUInt16(frame.GetBodyBytes(), 2);
            }
            if (t_file_name != (UInt16)EMyCommand.FILENAME)
            {
                throw new Exception("无文件名子帧");
            }

            //帧体长度
            UInt32 L_file_name = 0;
            if (frame.IsBodyHasDataInStream())
            {
                L_file_name = br.ReadUInt32();
            }
            else
            {
                L_file_name = BitConverter.ToUInt32(frame.GetBodyBytes(), 4);
            }
            byte[] fnb = new byte[L_file_name];

            //帧体
            if (frame.IsBodyHasDataInStream())
            {
                br.Read(fnb, 0, fnb.Length);
            }
            else
            {
                Array.Copy(frame.GetBodyBytes(), 8, fnb, 0, L_file_name);
            }
            string file_name = Encoding.UTF8.GetString(fnb);
            #endregion

            #region 文件保存到当前目录
            string exe_path  = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
            int    pos       = exe_path.LastIndexOf('\\');
            string path      = exe_path.Substring(0, pos + 1);
            string file_path = path + file_name;
            #endregion

            FileStream   fs = new FileStream(file_path, FileMode.Create);
            BinaryWriter bw = new BinaryWriter(fs);

            #region 文件数据

            //帧序列号 - 子帧的序列号是0
            if (frame.IsBodyHasDataInStream())
            {
                SN = br.ReadUInt16();
            }
            else
            {
                SN = BitConverter.ToUInt16(frame.GetBodyBytes(), 8 + (int)L_file_name);
            }

            //帧类型值
            if (frame.IsBodyHasDataInStream())
            {
                t_file_data = br.ReadUInt16();
            }
            else
            {
                t_file_data = BitConverter.ToUInt16(frame.GetBodyBytes(), 10 + (int)L_file_name);
            }
            if (t_file_data != (UInt16)EMyCommand.FILEDATA)
            {
                throw new Exception("无文件数据子帧");
            }

            //帧体
            UInt32 L_file_data = 0;
            if (frame.IsBodyHasDataInStream())
            {
                L_file_data = br.ReadUInt32();
            }
            else
            {
                L_file_data = BitConverter.ToUInt32(frame.GetBodyBytes(), 8 + (int)L_file_name + 4);
            }
            byte[] tmp         = new byte[1024 * 1024]; //每次读1MBytes
            UInt32 block_count = (L_file_data / (UInt32)tmp.Length) + (L_file_data % (UInt32)tmp.Length > 0 ? (UInt32)1 : (UInt32)0);
            for (int i = 0; i < block_count; ++i)
            {
                UInt32 last_block_size = (L_file_data % (UInt32)tmp.Length > 0 ? (L_file_data % (UInt32)tmp.Length) : (UInt32)tmp.Length);
                UInt32 block_size      = (i == block_count - 1 ? last_block_size : (UInt32)tmp.Length);
                if (frame.IsBodyHasDataInStream())
                {
                    br.Read(tmp, 0, (int)block_size);
                }
                else
                {
                    Array.Copy(frame.GetBodyBytes(), 8 + (int)L_file_name + 8 + i * tmp.Length, tmp, 0, block_size);
                }
                bw.Write(tmp, 0, (int)block_size);
            }
            #endregion

            bw.Close();
            bw.Dispose();
            fs.Close();
            fs.Dispose();

            byte[] body     = Encoding.UTF8.GetBytes("OK");
            Frame  frm_send = new Frame(frame.GetFrameSerialNumber(), GetT(), body); //要发给客户端的帧
            session.Send(frm_send);
        }
Ejemplo n.º 27
0
 //private void Load_Settings()
 //{
 //    BaseEntity objBase = new BaseEntity();
 //    DataTable dt = ResourceBL.Instance.Settings_GetAll(ref objBase);
 //    if (objBase.Errors.Count == 0)
 //    {
 //        if (dt != null)
 //        {
 //            foreach (DataRow item in dt.Rows)
 //            {
 //                hfIsVisiableChat.Value = item["ChatOnlineActive"].ToString();
 //            }
 //        }
 //    }
 //}
 protected void btnCloseSession_ServerClick(object sender, EventArgs e)
 {
     BaseSession.Logout();
     Response.Redirect("Index.aspx");
 }
Ejemplo n.º 28
0
 protected void btnCerrarSesion_Click(object sender, EventArgs e)
 {
     BaseSession.Logout();
     Response.Redirect("~/Layout/Login.aspx", false);
 }
Ejemplo n.º 29
0
        public ActionResult Logout()
        {
            #region [ Add data into language combo box ]
            if (TempData.Keys.Contains(StaticContent.LanguageKey))
            {
                LanguageKey temp = (LanguageKey)(TempData[StaticContent.LanguageKey]);

                initLanguageComboBox(temp.ToString());
            }
            else
            {
                initLanguageComboBox();
            }
            #endregion

            string str_IpAddr   = this.HttpContext.Request.UserHostAddress;
            string str_HostName = this.HttpContext.Request.UserHostName;

            string str_MsgBoxTitle = MultilingualHelper.GetStringFromResource("LoginScreentTitle");

            string strError = MultilingualHelper.GetStringFromResource("I003");

            string str_SaveAuthorizedHistory_Error = "";

            if (ViewData.ContainsKey(Bootstrapper.UserClientSessionKey.ToString()))
            {
                ClientSessionInfo entity_ClientSessionInfo = null;
                if (ViewData.ContainsKey(Bootstrapper.UserClientSessionKey.ToString()))
                {
                    entity_ClientSessionInfo = (ClientSessionInfo)ViewData[Bootstrapper.UserClientSessionKey.ToString()];
                }

                if (entity_ClientSessionInfo != null)
                {
                    BaseSession entity_BaseSession = entity_SessionWUserInfo;

                    if (entity_BaseSession != null)
                    {
                        WebCommonHelper webCommonHelper = new WebCommonHelper();

                        webCommonHelper.CallWCFHelper(this, (entity_WCFAuthInfoVM) =>
                        {
                            WCFReturnResult entity = loginUserMgtHelper.Value.Logout(entity_WCFAuthInfoVM);

                            if (!entity.IsSuccess)
                            {
                                str_SaveAuthorizedHistory_Error = string.Join("<br/>", entity.StrList_Error.ToArray());
                            }
                            else
                            {
                                MVCSessionMgt.RemoveServerSideSession(entity_BaseSession);
                            }
                        });
                    }

                    if (ViewData.ContainsKey(Bootstrapper.UserClientSessionKey.ToString()))
                    {
                        ViewData.Remove(Bootstrapper.UserClientSessionKey.ToString());
                    }

                    if (TempData.ContainsKey(Bootstrapper.UserClientSessionKey.ToString()))
                    {
                        TempData.Remove(Bootstrapper.UserClientSessionKey.ToString());
                    }
                }
            }

            if (!string.IsNullOrWhiteSpace(str_SaveAuthorizedHistory_Error))
            {
                MsgInfo errorMsgInfo = new MsgInfo();
                errorMsgInfo.MsgTitle      = str_MsgBoxTitle;
                errorMsgInfo.MsgDesc       = str_SaveAuthorizedHistory_Error;
                errorMsgInfo.MsgType       = MessageType.ValidationError;
                ViewBag.ActionMessage      = errorMsgInfo;
                TempData[ActionMessageKey] = errorMsgInfo;
            }
            else
            {
                MsgInfo errorMsgInfo = new MsgInfo();
                errorMsgInfo.MsgTitle      = str_MsgBoxTitle;
                errorMsgInfo.MsgDesc       = strError;
                errorMsgInfo.MsgType       = MessageType.Success;
                ViewBag.ActionMessage      = errorMsgInfo;
                TempData[ActionMessageKey] = errorMsgInfo;
            }
            return(View("Index"));
        }
Ejemplo n.º 30
0
        public LUSerLoginResult Login(LoginUserVM entityInst, string str_Language, string str_IpAdd, string str_HostName)
        {
            try
            {
                LUSerLoginResult returnResult = new LUSerLoginResult();

                SysParmRespository entityRepository = new SysParmRespository();

                StaticContent.SystemInfoInst = entityRepository.RetrieveSystemInfo();

                LanguageKey languageKey_Input = LanguageKey.en;

                Enum.TryParse <LanguageKey>(str_Language, out languageKey_Input);

                // Login Name cannot be empty
                if (string.IsNullOrWhiteSpace(entityInst.LoginName))
                {
                    string str_E001 = MultilingualHelper.GetStringFromResource(languageKey_Input, "E001");
                    str_E001 = string.Format(str_E001, MultilingualHelper.GetStringFromResource(languageKey_Input, "LoginName"));
                    returnResult.StrList_Error.Add(str_E001);
                }

                // Login Password cannot be empty
                if (string.IsNullOrWhiteSpace(entityInst.LoginPwd))
                {
                    string str_E001 = MultilingualHelper.GetStringFromResource(languageKey_Input, "E001");
                    str_E001 = string.Format(str_E001, MultilingualHelper.GetStringFromResource(languageKey_Input, "LoginPwd"));
                    returnResult.StrList_Error.Add(str_E001);
                }

                if (!string.IsNullOrWhiteSpace(entityInst.LoginName) && !string.IsNullOrWhiteSpace(entityInst.LoginPwd))
                {
                    string str_E008 = MultilingualHelper.GetStringFromResource(languageKey_Input, "E008");
                    str_E008 = string.Format(str_E008, MultilingualHelper.GetStringFromResource(languageKey_Input, "LoginName"), MultilingualHelper.GetStringFromResource(languageKey_Input, "LoginPwd"));

                    string str_E009 = MultilingualHelper.GetStringFromResource(languageKey_Input, "E009");

                    string str_E018 = MultilingualHelper.GetStringFromResource(languageKey_Input, "E018");

                    CoolPrivilegeControlContext dbContext      = CoolPrivilegeControlContext.CreateContext();
                    LoginUserRespository        loginUserRespo = new LoginUserRespository(dbContext, null);

                    LoginUserVM entityVM_exist = loginUserRespo.GetLoginUserInfo(entityInst.LoginName);
                    if (entityVM_exist != null)
                    {
                        PwdPolicy pwdPolicy = new PwdPolicy();

                        if (!entityVM_exist.Status.HasValue || entityVM_exist.Status.Value == 2)
                        {
                            returnResult.StrList_Error.Add(str_E018);
                        }
                        else if (entityVM_exist.Status.HasValue && entityVM_exist.Status.Value == 3)
                        {
                            returnResult.StrList_Error.Add(str_E018);
                        }
                        else
                        {
                            if (entityVM_exist.LoginPwd == pwdPolicy.GetMD5(entityInst.LoginPwd))
                            {
                                DateTime?dt_LastPwdMDT = entityVM_exist.LastPwdMDT;
                                entityVM_exist.FailCount   = 0;
                                entityVM_exist.Status      = 1;
                                entityVM_exist.LastLoginDT = DateTime.Now;
                                entityInst.LastPwdMDT      = entityVM_exist.LastPwdMDT;
                                List <string> strList_UpdateLastLoginDt_Error = new List <string>();
                                loginUserRespo.UpdateLastLoginDt(entityVM_exist, languageKey_Input, ref strList_UpdateLastLoginDt_Error);
                                if (strList_UpdateLastLoginDt_Error.Count > 0)
                                {
                                    foreach (var item in strList_UpdateLastLoginDt_Error)
                                    {
                                        returnResult.StrList_Error.Add(item);
                                    }
                                }
                                else
                                {
                                    AuthorizedHistoryRespository authorityHistoryRespos = new AuthorizedHistoryRespository(dbContext, entityVM_exist.ID);

                                    string str_SaveAuthorizedHistory_Error = "";

                                    //Create Login History
                                    authorityHistoryRespos.Create(new AuthorizedHistoryVM(), languageKey_Input, out str_SaveAuthorizedHistory_Error);

                                    if (!string.IsNullOrWhiteSpace(str_SaveAuthorizedHistory_Error))
                                    {
                                        returnResult.StrList_Error.Add(str_SaveAuthorizedHistory_Error);
                                    }
                                    else
                                    {
                                        string      sessionKey         = Guid.NewGuid().ToString();
                                        BaseSession entity_BaseSession = new BaseSession();
                                        entity_BaseSession.ID              = entityVM_exist.ID;
                                        entity_BaseSession.SessionKey      = sessionKey;
                                        entity_BaseSession.IpAddress       = str_IpAdd;
                                        entity_BaseSession.LastOperationDt = DateTime.Now;

                                        WCFAuthInfoVM entity_WCFAuthInfoVM = new WCFAuthInfoVM(str_IpAdd, str_HostName, "", "", "", "", "");

                                        WCFSesssionPolicy wcfPolicy = new WCFSesssionPolicy();

                                        wcfPolicy.StoreWCFSession(entity_WCFAuthInfoVM, entity_BaseSession);

                                        #region [ Set Client Authorized Info ]
                                        SessionWUserInfo entity_SessionWUserInfo = loginUserRespo.GetLoginUserAccRight(entity_BaseSession.ID);

                                        if (entity_SessionWUserInfo != null)
                                        {
                                            entity_SessionWUserInfo.SessionKey      = Guid.NewGuid().ToString();
                                            entity_SessionWUserInfo.IpAddress       = entity_WCFAuthInfoVM.IpAddress;
                                            entity_SessionWUserInfo.LastOperationDt = DateTime.Now;
                                        }
                                        #endregion

                                        returnResult.Entity_SessionWUserInfo = entity_SessionWUserInfo;

                                        if (entityVM_exist.LastPwdMDT.HasValue)
                                        {
                                            returnResult.IsPWDExpire = entityVM_exist.LastPwdMDT.Value.AddDays(((SystemInfoVM)StaticContent.SystemInfoInst).Password_ExpireDays) <= DateTime.Now.Date;
                                        }

                                        returnResult.Str_ServerToken = entity_WCFAuthInfoVM.WCFAuthorizedKey;
                                    }
                                }
                            }
                            else
                            {
                                List <string> strList_UpdateFailCount_Error = new List <string>();
                                loginUserRespo.UpdateFailCount(entityVM_exist, languageKey_Input, ref strList_UpdateFailCount_Error);

                                returnResult.StrList_Error.Add(str_E008);

                                if (strList_UpdateFailCount_Error.Count > 0)
                                {
                                    foreach (var item in strList_UpdateFailCount_Error)
                                    {
                                        returnResult.StrList_Error.Add(item);
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        returnResult.StrList_Error.Add(str_E008);
                    }
                }
                return(returnResult);
            }
            catch (Exception ex)
            {
                throw new FaultException <WCFErrorContract>(new WCFErrorContract(ex), ex.Message);
            }
        }
Ejemplo n.º 31
0
 public static NXObjectManager GetObjectManager(this BaseSession obj)
 {
     return(null);
 }
Ejemplo n.º 32
0
 public static void AddSession(BaseSession session)
 {
     NewSessions.Enqueue(session);
 }