Example #1
0
        public void GetCurrentActiveItem_given_empty_list_returns_option_none()
        {
            var input  = new List <ItemDTO>();
            var result = SessionUtils.GetCurrentActiveItem(input, 0);

            Assert.False(result.HasValue);
        }
Example #2
0
        public static bool Login(string strAccountName, string strPassword)
        {
            AccountInfo model = BizBase.dbo.GetModel <AccountInfo>(string.Concat(new string[]
            {
                " select top 1 * from sys_Account where AccountName='",
                strAccountName,
                "' and [Password]='",
                strPassword,
                "' "
            }));
            bool result;

            if (model != null)
            {
                SessionUtils.SetSession("Account", model);
                new LogManager().AddLoginLog(model.AccountName, true);
                model.LoginCount++;
                BizBase.dbo.UpdateModel <AccountInfo>(model);
                result = true;
            }
            else
            {
                new LogManager().AddLoginLog(strAccountName, false);
                result = false;
            }
            return(result);
        }
Example #3
0
        public void GetCurrentActiveItem_given_list_that_contains_consensus_but_not_enough_votes_returns_option_some()
        {
            var input = new List <ItemDTO>
            {
                new ItemDTO
                {
                    Id     = 42,
                    Rounds = new List <RoundDTO>
                    {
                        new RoundDTO
                        {
                            Id    = 1,
                            Votes = new List <VoteDTO>
                            {
                                new VoteDTO {
                                    Estimate = 13
                                },
                                new VoteDTO {
                                    Estimate = 8
                                }
                            }
                        }
                    }
                }
            };

            var result = SessionUtils.GetCurrentActiveItem(input, 5);

            Assert.True(result.HasValue);
            Assert.Equal(42, result.ValueOrFailure().Id);
            Assert.Equal(1, result.ValueOrFailure().Rounds.Count);
        }
        public string LoginValidate(string token)
        {
            string result = "";

            try
            {
                var json = u_JurisdictionUtils.UserValidationApi(token);
                UserValidateResult userValidateResult = JsonConvert.DeserializeObject <UserValidateResult>(json);
                UserValidate       userValidate       = userValidateResult.uservaliDate;

                SessionUtils.Add("userCode", userValidate.UserCode);
                SessionUtils.Add("departmentId", userValidate.DepartmentId);
                SessionUtils.Add("token", token);
                SessionUtils.Add("token_r", userValidate.Token_R);

                string responsibleDepartment = u_JurisdictionUtils.ResponsibleDepartmentApi(userValidate.Token_R, userValidate.UserCode);  ///负责部门
                if (u_TypeJudgmentUtils.IsNullOrEmptyObj(responsibleDepartment) == false)
                {
                    SessionUtils.Add("responsibleDepartment", responsibleDepartment);
                }
            }
            catch (Exception ex)
            {
                result = "{\"code\":\"0\",\"msg\":\"后台出错" + ex + "\"}";
            }
            return(result);
        }
        public async Task <ActionResult <RoundDTO> > NextRound([FromHeader(Name = "PPAuthorization")] string authToken, string sessionKey)
        {
            if (!SecurityFilter.RequestIsValid(authToken, sessionKey, this.userStateManager))
            {
                return(this.Unauthorized());
            }

            var session = await this.sessionRepository.FindByKeyAsync(sessionKey);

            if (session == null)
            {
                return(this.NotFound());
            }

            var currentItem = SessionUtils.GetCurrentActiveItem(session.Items, session.Users.Count);

            if (!currentItem.HasValue)
            {
                return(this.BadRequest());
            }

            var newRound = this.sessionRepository.AddRoundToSessionItem(currentItem.ValueOrDefault().Id);

            return(newRound);
        }
Example #6
0
        /// <summary>
        /// 初期化处理
        /// </summary>
        private void Initialize()
        {
            this.uservo = (LoginUserInfoVo)SessionUtils.GetSession(SessionUtils.COMMON_LOGIN_USER_INFO);
            if (string.IsNullOrEmpty(strMode))
            {
                this.strMode = Constant.MODE_ADD;
            }

            this.SetToolBar(this.strMode);
            this.SetLayout(this.strMode);
            this.removeAllClickEvent();
            this.addAllClickEvent();

            this.txtCompany.Text = this.uservo.CompanyCondition.ICompanyCd;
            #region Company delete
            this.lblCompany.Visible   = false;
            this.lblStar2.Visible     = false;
            this.txtCompany.Visible   = false;
            this.txtCompany.Enabled   = false;
            this.txtCompany.TabStop   = false;
            this.lblCompanyNM.Visible = false;
            this.btnCompany.Visible   = false;
            this.btnCompany.TabStop   = false;
            #endregion

            this.Activate();
            this.GotFocus += new EventHandler(FrmFactory_GotFocus);
        }
Example #7
0
        public static void LoadSessions()
        {
            string fileName = SessionsFileName;

            Log.InfoFormat("Loading all sessions.  file={0}", fileName);

            try
            {
                if (File.Exists(fileName))
                {
                    List <SessionBase> sessions = SessionUtils.LoadSessionsFromFile(fileName);
                    // remove old
                    sessionsMap.Clear();

                    foreach (SessionBase session in sessions)
                    {
                        sessionsMap.Add(session.SessionId, session);
                    }
                }
                else
                {
                    Log.WarnFormat("Sessions file does not exist, nothing loaded.  file={0}", fileName);
                }
            }
            catch (Exception ex)
            {
                Log.Error("Error while loading sessions from " + fileName, ex);
            }
        }
        public IActionResult Index()
        {
            Client client    = new Client(SessionUtils.FromJson(HttpContext.Session).ClientId);
            int    nProjects = client.Projects.Capacity;

            List <Project> clientProjects = new List <Project>(nProjects);

            string message = "";

            if (nProjects == 0)
            {
                message = "Vous n'avez aucun projet en cours.";
            }
            else
            {
                message = "Vous avez " + nProjects + " projets en cours.";
                List <Project> allProjects = BTPBCommon.Platform.Projects;
                clientProjects.AddRange(allProjects.Where(p =>
                                                          p.Owner.Id == SessionUtils.GetSessionClientId(HttpContext.Session)));
            }

            ViewData["Projects"] = clientProjects;
            ViewData["Message"]  = message;

            return(View("Projects"));
        }
Example #9
0
    /// <summary>
    /// 获取用户信息
    /// </summary>
    /// <returns></returns>
    public static UserInfo GetUserInfo()
    {
        UserInfo userInfo = null;

        if (HttpContext.Current.Session == null)
        {
            return(userInfo);
        }
        if (SessionUtils.GetSession(SessionName) != null)
        {
            userInfo = (UserInfo)SessionUtils.GetSession(SessionName);
        }
        if (userInfo != null)
        {
            return(userInfo);
        }
        // 从 Session 读取 当前操作员信息
        if (HttpContext.Current.Session["UserInfo"] == null)
        {
            userInfo = new UserInfo();
            // 获得IP 地址
            //string clientIPAddress = System.Net.Dns.GetHostByName(System.Net.Dns.GetHostName()).AddressList[0].ToString();
            string clientIPAddress = RDIFramework.WebCommon.RequestHelper.GetIP();
            userInfo.Id        = clientIPAddress;
            userInfo.RealName  = clientIPAddress;
            userInfo.UserName  = clientIPAddress;
            userInfo.IPAddress = clientIPAddress;
            // 设置操作员类型,防止出现错误,因为不小心变成系统管理员就不好了
            // if (string.IsNullOrEmpty(userInfo.RoleId))
            // {
            //     userInfo.RoleId = DefaultRole.User.ToString();
            // }
        }
        return(userInfo);
    }
Example #10
0
        public IActionResult Confirmed(AccountMyProfileEditVM account)
        {
            MyShoppingCartVM myCartVM;

            if (User.Identity.IsAuthenticated)
            {
                string userID     = signInManager.UserManager.GetUserId(HttpContext.User);
                int    customerID = webShopDBContext.User.First(u => u.Uid == userID).Id;
                myCartVM = SessionUtils.GetArticles(this, webShopDBContext);
                webShopDBContext.AddOrder(customerID, myCartVM, webShopDBContext);
            }
            else
            {
                webShopDBContext.User.Add(new User {
                    Firstname   = account.FirstName,
                    Lastname    = account.LastName,
                    Phonenumber = account.PhoneNumber,
                    Email       = account.Email,
                    Addressline = account.AddressLine,
                    Zipcode     = account.ZipCode,
                    City        = account.City
                });
                webShopDBContext.SaveChanges();

                int customerID = webShopDBContext.User.First(u => u.Email == account.Email).Id;
                myCartVM = SessionUtils.GetArticles(this, webShopDBContext);
                webShopDBContext.AddOrder(customerID, myCartVM, webShopDBContext);
            }
            HttpContext.Session.Clear();

            return(View());
        }
        public void AddRequest(Fiddler.Session req, string stepName)
        {
            bool isPrimary = SessionUtils.IsPrimaryReq(req);
            var  reqCode   = new RequestSection(req, ParentScript, stepName, ParentScript.ParametrizedValues, isPrimary);

            _sections.Add(reqCode);
        }
Example #12
0
        /// <summary>
        /// Overrides the SSO.
        /// </summary>
        /// <param name="userID">The user ID.</param>
        /// <param name="username">The username.</param>
        /// <param name="parentID">The parent ID.</param>
        public User OverrideSSO(long userID, string username, long parentID)
        {
            User user = new User(userID, username, parentID, FCMConfig.Security.OverrideSSOProvGroupID,
                                 FCMConfig.Security.OverrideSSORoleID)
            {
                IsSuperUser = FCMConfig.Security.OverrideSSOIsSuperUser
            };

            // TODO: Disabled temporary!
            // user.Firstname = "Testko";

            //bool synchronised = SynchronizeUser(user.UserID, user.Username, user.ParentID, user.ProvisioningGroupID,"Testkeeeeeeeeo", "Testic");

            //if (!synchronised)
            //{
            //    Logger.Log(LogLevels.Debug, string.Format("User synchronisation error | user.UserID:'{0}'", user.UserID));
            //    return null;
            //}

            if (user.IsChildUser)
            {
                user.ChildUserID = user.UserID;
                user.UserID      = user.ParentID;
            }

            UserID       = user.UserID;
            SSOAuthToken = "GISDATA-HC";
            SessionUtils.SetValue(SessionHelper.BuildSessionKey("LastSSOSessionRefreshTime"), DateTimeHelper.GetSvcProvDateTimeNow());

            return(user);
        }
Example #13
0
        private static void UploadTest()
        {
            AuthInfo authInfo = AuthInfo.ReadAuthInfo();
            ISession session  = SessionUtils.CreateSession(authInfo.serviceUrl, authInfo.username, authInfo.password);
            //IFolder rootFolder = session.GetRootFolder();
            IFolder userHomeFolder = GetUserFolder(session, authInfo.username);

            // document name
            string formattedName = "Home Page.pdf";

            // define dictionary
            IDictionary <string, object> properties = new Dictionary <string, object>();

            properties.Add(PropertyIds.Name, formattedName);

            // define object type as document, as we wanted to create document
            properties.Add(PropertyIds.ObjectTypeId, "cmis:document");

            // read a empty document with empty bytes
            // fileUpload1: is a .net file upload control
            byte[]        datas         = File.ReadAllBytes("C:\\Users\\KVM\\Home Page.pdf");
            ContentStream contentStream = new ContentStream
            {
                FileName = formattedName,
                MimeType = "application/pdf",
                Length   = datas.Length,
                Stream   = new MemoryStream(datas)
            };

            // this statment would create document in default repository
            userHomeFolder.CreateDocument(properties, contentStream, null);
            Debug.WriteLine("OK");
        }
Example #14
0
        public void GetCurrentActiveItem_given_list_that_contains_consensus_returns_option_none()
        {
            var input = new List <ItemDTO>
            {
                new ItemDTO
                {
                    Id     = 42,
                    Rounds = new List <RoundDTO>
                    {
                        new RoundDTO
                        {
                            Id    = 1,
                            Votes = new List <VoteDTO>
                            {
                                new VoteDTO {
                                    Estimate = 13
                                },
                                new VoteDTO {
                                    Estimate = 13
                                }
                            }
                        }
                    }
                }
            };

            var result = SessionUtils.GetCurrentActiveItem(input, 2);

            Assert.False(result.HasValue);
        }
Example #15
0
        public Boolean SaveDataToStp(String strMode, TFactoryMs facVo)
        {
            Boolean         rtnValue = true;
            LoginUserInfoVo uservo   = (LoginUserInfoVo)SessionUtils.GetSession(SessionUtils.COMMON_LOGIN_USER_INFO);

            TFcConditionStp facStp = new TFcConditionStp();

            PropertiesCopier.CopyProperties(facVo, facStp);
            facStp.Id.IJournalNo = 10001;
            facStp.Id.ICompanyCd = facVo.ICompanyCd;
            facStp.IPrcsCls      = CommonUtil.GET_I_PRCS_CLS(strMode);
            facStp.IUserId       = uservo.Userid;
            facStp.IPrcsDate     = DateTime.Now;
            facStp.IPrcsTime     = DateTime.Now.ToShortTimeString();
            facStp.IUpdCls       = "0";

            facStp.IConditionCd = "000001";
            //facStp.IDlCurrCd = card.C4_DL_CURR_CD;//取引通貨
            facStp.IDelWhInCd         = "";
            facStp.IDelWhOutCd        = "";
            facStp.IRjtWhCd           = "";
            facStp.INonAllocLocation  = "";
            facStp.IOsWhCd            = "";
            facStp.IInspectonLocation = "";
            facStp.IPlanCycCls        = CommonUtil.NullToSpace(facStp.IPlanCycCls);
            facStp.IWkTime            = CommonUtil.NullToZero(facStp.IWkTime);
            facStp.IPoCreateCls       = CommonUtil.NullToSpace(facStp.IPoCreateCls);
            facStp.ISalesCls          = CommonUtil.NullToSpace(facStp.ISalesCls);
            facStp.IPoSlcCls          = CommonUtil.NullToSpace(facStp.IPoSlcCls);
            facStp.IMrpCls            = CommonUtil.NullToSpace(facStp.IMrpCls);
            facStp.ILinkFlg           = CommonUtil.NullToSpace(facStp.ILinkFlg);
            facStp.IShipInvCls        = CommonUtil.NullToSpace(facStp.IShipInvCls);
            facStp.IAcpInvCls         = CommonUtil.NullToSpace(facStp.IAcpInvCls);
            facStp.IAmtRecalcCls      = CommonUtil.NullToSpace(facStp.IAmtRecalcCls);
            facStp.IReserve1          = null;
            facStp.IReserve2          = null;
            facStp.IReserve3          = null;
            facStp.ISys1Cls           = " ";
            facStp.ISys2Cls           = " ";
            facStp.ISys3Cls           = " ";
            facStp.IUsr1Cls           = " ";
            facStp.IUsr2Cls           = " ";
            facStp.IUsr3Cls           = " ";
            facStp.IInqItem           = null;
            //facStp.IObjectId = card.C4_OBJECT_ID;//オブジェクトID???
            //facStp.IEntryDate = ServerFunction.GetDateTime();//登録日
            //facStp.IUpdDate = ServerFunction.GetDateTime();//更新日
            facStp.IEntryDate = DateTime.Now;
            facStp.IUpdDate   = DateTime.Now;
            //facStp.IPgId = PE002201PgInfo._PROGRAM_ID; ;//プログラムID
            //facStp.IUpdTimestamp = wk_upd_timestamp;//更新タイムスタンプ

            ITFcConditionStpDao td = ComponentLocator.Instance().Resolve <ITFcConditionStpDao>();

            rtnValue = td.Insert(facStp);
            rtnValue = true;

            return(rtnValue);
        }
Example #16
0
        public IActionResult ConfirmOrder(AccountMyProfileEditVM account)
        {
            OrderConfirmOrderVM thingsNeededToCompletePurchase = new OrderConfirmOrderVM();

            thingsNeededToCompletePurchase.Account            = account;
            thingsNeededToCompletePurchase.ProductsToPurchase = SessionUtils.GetArticles(this, webShopDBContext);
            return(View(thingsNeededToCompletePurchase));
        }
Example #17
0
    //
    // 二 判断用户是否已登录部分
    //

    #region public static bool UserIsLogOn() 判断用户是否已登录
    /// <summary>
    /// 判断用户是否已登录
    /// </summary>
    /// <returns>已登录</returns>
    public static bool UserIsLogOn()
    {
        // 先判断 Session 里是否有用户
        if (SessionUtils.GetSession(SessionName) == null)
        {
            // 检查是否有Cookie?
            CheckCookie();
        }
        return(HttpContext.Current.Session != null && SessionUtils.GetSession(SessionName) != null);
    }
        public IActionResult Index()
        {
            /*
             * net core不自带httpcontext 需要在 Startup 注入
             * 1、在ConfigureServices 中 services.AddStaticHttpContext();
             * 2、在Configure 中 app.UseStaticHttpContext();
             */

            var builder = new StringBuilder("测试如下:\r\n");

            //Post
            builder.Append($"Post值:{WebUtils.GetFormVal<string>("a")}\r\n");

            //IP
            builder.Append($"IP:{IPUtils.GetIP()}\r\n");

            //WebUtils
            builder.Append($"pid:{WebUtils.GetQueryVal<int>("pid")}\r\n");                                  //?pid=1
            builder.Append($"date:{WebUtils.GetQueryVal<DateTime>("date", new DateTime(1900, 1, 1))}\r\n"); //?date=2020-12-31
            //全url
            builder.Append($"全URL:{WebUtils.GetAbsoluteUri()}\r\n");

            //CacheUtils 缓存
            DateTime dateTime = DateTime.Now;
            var      cache    = new CacheUtils();

            var cacheDT = DateTime.Now;

            if (cache.ContainKey("time"))
            {
                cacheDT = cache.Get <DateTime>("time");
            }
            else
            {
                cache.Insert <DateTime>("time", dateTime, 3600);
            }

            builder.Append($"当前时间:{dateTime.ToFormatString()} \r\n");
            builder.Append($"缓存时间:{cacheDT.ToFormatString()} \r\n");

            //当前网站目录
            builder.Append($"当前网站目录:{SystemUtils.GetMapPath()} \r\n");
            builder.Append($"upload目录:{SystemUtils.GetMapPath("/upload")} \r\n");

            //cookie
            CookieUtils.SetCookie("username", "jsonlee");
            builder.Append($"username cookie: {CookieUtils.GetCookie("username")} \r\n");

            //session
            SessionUtils.SetSession("username", System.Web.HttpUtility.UrlEncode("刘备"));
            builder.Append($"username session: {System.Web.HttpUtility.UrlDecode(SessionUtils.GetSession("username"))} \r\n");

            return(Content(builder.ToString()));
        }
Example #19
0
 /// <summary>
 /// 授权校验
 /// </summary>
 /// <param name="context"></param>
 public void OnAuthorization(AuthorizationFilterContext context)
 {
     if (((AuthorizeValue >> (int)AuthorizeType.CheckLogin) & 0x01) > 0)
     {
         OperatorVo key = SessionUtils.Get <OperatorVo>(LoginSessionKey);
         if (key == null)
         {
             context.Result = new JsonResult(new JsonResponses("未登录"));
             return;
         }
     }
 }
Example #20
0
        /// <summary>
        /// Refreshes the session.
        /// </summary>
        public bool RefreshSession()
        {
            try
            {
                bool   refreshed  = false;
                string sessionKey = SessionHelper.BuildSessionKey("LastSSOSessionRefreshTime");

                if (SessionUtils.GetValue(sessionKey) != null && !StringUtils.IsNullOrEmptyOrWS(SSOAuthToken))
                {
                    DateTime lastSSOSessionRefreshTime = DateTimeHelper.GetDateTime(SessionUtils.GetValue(sessionKey), DateTime.MinValue);
                    TimeSpan timeDiff = DateTimeHelper.GetSvcProvDateTimeNow().Subtract(lastSSOSessionRefreshTime);

                    if ((timeDiff.TotalMinutes + 2) > FCMConfig.Security.SSOSessionTimeout)
                    {
                        string newSSOAuthToken;
                        refreshed =
                            SSOAuthWS.RefreshSession(GetSSOAuthData(FCMConfig.Security.SSOApplicationID, SSOAuthToken),
                                                     out newSSOAuthToken);

                        SSOAuthToken = newSSOAuthToken;

                        if (refreshed && !StringUtils.IsNullOrEmptyOrWS(newSSOAuthToken))
                        {
                            SessionUtils.SetValue(sessionKey, DateTimeHelper.GetSvcProvDateTimeNow());
                        }
                        else
                        {
                            Logger.Log(LogLevels.Debug, "Refresh session failed!");
                            throw new AuthenticationException("Refresh session error!");
                        }
                    }
                }

                return(refreshed);
            }
            catch (SoapException ex)
            {
                Logger.Log(LogLevels.Error, exception: ex);

                if (!StringUtils.IsNullOrEmptyOrWS(ex.Message) && ex.Message.Contains("00401"))
                {
                    FCMBusiness.ClearSSOCache();
                    return(RefreshSession());
                }

                return(false);
            }
            catch (Exception ex)
            {
                Logger.Log(LogLevels.Error, exception: ex);
                return(false);
            }
        }
Example #21
0
        public IActionResult MyCart()
        {
            string[]         tempArr  = SessionUtils.GetArticleNumbersInCart(this);
            MyShoppingCartVM myCartVM = SessionUtils.GetArticles(this, webShopDBContext);

            if (User.Identity.IsAuthenticated)
            {
                myCartVM.IsLoggedIn = true;
            }

            return(View(myCartVM));
        }
Example #22
0
        /// <summary>
        /// Validate if we can open the session
        /// </summary>
        /// <param name="serverUrl"></param>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <returns>True, if could open Encompass Session</returns>
        public static bool Validate(string serverUrl, string userName, string password)
        {
            var session = SessionUtils.GetEncompassSession(serverUrl, userName, password);

            if (session == null || !session.IsConnected)
            {
                return(false);
            }

            session.End();
            return(true);
        }
        public ActionResult ChangePasswordPost(string currentPassword, string newPassword, string confirmPassword)
        {
            bool isSuccess = true;

            try
            {
                if (string.Equals(currentPassword, newPassword))
                {
                    throw new Exception("New password should not be the same as current password.");
                }

                if (!string.Equals(newPassword, confirmPassword))
                {
                    throw new Exception("Password does not matched.");
                }

                var session = SessionUtils.GetUserAccount();
                var account = this._service.Get(session.ID);

                if (!string.Equals(currentPassword, PasswordEncryption.Decrypt(account.Password)))
                {
                    throw new Exception("Current password is incorrect.");
                }

                account.Password = PasswordEncryption.Encrypt(newPassword);

                this._auditTrailService.Insert(
                    new AuditTrail
                {
                    ObjectName  = "UserAccount",
                    ObjectID    = SessionUtils.GetUserAccount().ID,
                    Message     = "User Account password was changed successfully.",
                    UserAccount = new UserAccount
                    {
                        ID = SessionUtils.GetUserAccount().ID
                    },
                    CreateDate = SessionUtils.GetCurrentDateTime()
                });

                this._service.UpdateUserAccount(account);
            }
            catch (Exception ex)
            {
                TempData.Add("ErrorMessage", ex.Message);
                isSuccess = false;
            }
            finally
            {
                TempData.Add("IsSuccess", isSuccess);
            }

            return(RedirectToRoute("ChangePassword"));
        }
        private void HandleTransaction(object state)
        {
            lock (_syncLock)
            {
                _transactions.TryDequeue(out var transaction);
                if (transaction == null)
                {
                    return;
                }

                var ownerId         = transaction.OwnerId;
                var accountId       = transaction.AccountId;
                var transactionType = transaction.Type;
                var amount          = transaction.Amount;

                var dbManager = DbManager.GetInstance();
                _user    = dbManager.GetUserDataBase().Get(ownerId);
                _account = dbManager.GetAccountDatabase().Get(accountId);

                TransactionStatus status;

                try
                {
                    MakeTransaction(transactionType, amount);
                    status = TransactionStatus.Success;
                }
                catch (NotEnoughMoneyException e)
                {
                    status = TransactionStatus.Error;
                    transaction.ErrorMessage = e.Message;
                }
                catch (UnknowTransactionException e)
                {
                    status = TransactionStatus.Error;
                    transaction.ErrorMessage = e.Message;
                }
                catch (Exception)
                {
                    status = TransactionStatus.Error;
                    transaction.ErrorMessage = "Unknown error";
                }

                transaction.Status        = status;
                transaction.Time          = GetCurrentTime();
                transaction.TransactionId = GenerateId();


                SessionUtils.RegisterTransaction(_account.Id, transaction);

                OnTransactionFinished?.Invoke(transaction);
            }
        }
Example #25
0
        public ActionResult Login(string username, string password)
        {
            try
            {
                if (Membership.ValidateUser(username, password))
                {
                    var userAccount = this._managementUserAccountService.GetByUsername(username).FirstOrDefault();

                    FormsAuthentication.SetAuthCookie($"{userAccount.ID} {username} {userAccount.FirstName} {userAccount.LastName} {userAccount.Roles}", false);

                    this._auditTrailService.Insert(
                        new AuditTrail
                    {
                        ObjectName  = "UserAccount",
                        ObjectID    = userAccount.ID,
                        Message     = "User Account logged in.",
                        UserAccount = new UserAccount
                        {
                            ID = userAccount.ID
                        },
                        CreateDate = SessionUtils.GetCurrentDateTime()
                    });

                    return(RedirectToAction("Index", "Home"));
                }

                throw new ApplicationException(ValidationMessages.USERACCOUNT_INVALID);
            }
            catch (ApplicationException appEx)
            {
                if (TempData.ContainsKey("username"))
                {
                    TempData.Remove("username");
                }

                if (TempData.ContainsKey("errorMessage"))
                {
                    TempData.Remove("errorMessage");
                }

                TempData.Add("username", username);
                TempData.Add("errorMessage", appEx.Message);

                return(RedirectToAction("Index"));
            }
            catch (Exception ex)
            {
                //write exception

                return(RedirectToAction("Index"));
            }
        }
Example #26
0
        static void Main(string[] args)
        {
            if (SessionUtils.Session == null)
            {
                AuthInfo authInfo = AuthInfo.ReadAuthInfo();

                if (!string.IsNullOrWhiteSpace(authInfo.username) && !string.IsNullOrWhiteSpace(authInfo.password))
                {
                    SessionUtils.Session = SessionUtils.CreateSession(authInfo.serviceUrl, authInfo.username, authInfo.password);
                }
            }
            StartApp(args);
        }
        public void GetEncompassSession_with_invalid_url_throws_connection_exception()
        {
            // arrange
            var encompassUrl = "https://TExxx.ea.elliemae.net$TExxx";
            var login        = "******";
            var pw           = "password";

            // act
            Assert.Throws <ServerConnectionException>(() =>
            {
                var actual = SessionUtils.GetEncompassSession(encompassUrl, login, pw);
            });
        }
        public ActionResult AccountInformation()
        {
            var session = SessionUtils.GetUserAccount();

            var userAccount = this._service.Get(session.ID);
            var model       = new VMModel <UserAccount>
            {
                Record   = userAccount,
                PageMode = PageMode.View
            };

            return(View("AccountInformationView", model));
        }
        /// <summary>
        /// 画面跳转到编辑画面
        /// </summary>
        private void TransferTo()
        {
            this.Cursor = Cursors.WaitCursor;
            Hashtable ht = (Hashtable)SessionUtils.GetSession(this.baseform.SessionKey);

            ht.Add("FRMMATERIAL_SEARCH", this);
            FrmMaterialEdit frmMaterialEdit = new FrmMaterialEdit(this.baseform.Parentdockpanel, this.baseform);
            ResourceManager fr = new ResourceManager(typeof(FrmMaterialEdit));

            frmMaterialEdit.DockTitle = frmMaterialEdit.Text;
            frmMaterialEdit.ShowContent(false);
            this.Cursor = Cursors.Default;
        }
Example #30
0
    /// <summary>
    /// 保存Session
    /// </summary>
    /// <param name="userInfo">当前用户</param>
    public static void SetSession(UserInfo userInfo)
    {
        // 检查是否有效用户
        if (userInfo != null && !string.IsNullOrEmpty(userInfo.Id))
        {
            // if (userInfo.RoleId.Length == 0)
            // {
            //     userInfo.RoleId = DefaultRole.User.ToString();
            // }
            // 操作员

            SessionUtils.SetSession(SessionName, userInfo);
        }
    }