Esempio n. 1
0
    protected void btnAdd_Click(object sender, ImageClickEventArgs e)
    {
        lblMsg.Text = "";
        string id = txtId.Text;
        string pw = txtPw.Text;
        string pw2 = txtPw2.Text;
        string userName = txtName.Text;

        LoginUser user = authService.Get_LoginUser_ByUserId(id);

        if (user != null)
        {
            //lblMsg.Text = MsgVO.USER_ALREADY_EXIST;
            lblMsg.Text = MsgVO.EXIST_USER_ACCOUNT;
            return;
        }
        else
        {
            LoginUser newUser = new LoginUser();
            newUser.UserId = id;
            newUser.Password = id;
            newUser.Name = userName;
            authService.myService.DaoInsert(newUser);
            lblMsg.Text = MsgVO.INSERT_OK;
            clearInput();
            initGV();
        }

    }
Esempio n. 2
0
        public HttpResponseMessage PutLoginUser(LoginUser userToLogin)
        {
            // validate username passowrd combination for existense
            User dbUser = ApiValidator.ValidateLogin(userToLogin.Username, userToLogin.CryptPass);
            string sessionKey = SessionKeyGenerator.GetSessionKey(dbUser.Username);
            dbUser.SessionKey = sessionKey;

            this.repo.LoginUser(dbUser.Username, dbUser.SessionKey);

            return this.Request.CreateResponse(HttpStatusCode.OK, sessionKey);
        }
Esempio n. 3
0
        public void Insert(LoginUser item)
        {
            string InsSql = @"Insert Into LoginUser(UserId, Password, Name, Description) "
                            + "values(@UserId,@Password, @Name, @Description)";

            MySqlParameter[] parameter = new MySqlParameter[]
                {
                    new MySqlParameter("@UserId",item.UserId),
                    new MySqlParameter("@Password",item.Password),
                    new MySqlParameter("@Name",item.Name),
                    new MySqlParameter("@Description",item.Description)
                };
                dbHelper.ExecuteNonQuery(InsSql, parameter);
        }
Esempio n. 4
0
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        LoginUser user = new LoginUser();
        user.Name = txtName.Text.Trim();
        user.Email = txtEmail.Text.Trim();
        user.UserId = txtUserId.Text.Trim();
        user.Password = EncryptUtil.GetMD5(txtPassword.Text.Trim());
        user.IsEnable = Convert.ToBoolean(rdoIsEnable.SelectedValue);
        SetLoginRoles(user);
        authService.myService.DaoInsert(user);

        string JsStr = JavascriptUtil.AlertJSAndRedirect("新增成功", LIST_URL);
        ScriptManager.RegisterClientScriptBlock(lblMsg, lblMsg.GetType(), "data", JsStr, false);
    }
Esempio n. 5
0
        public static List<LoginUser> GetLoginUsers()
        {
            var loginUsers = new List<LoginUser>();

            var roles = IdDb.Roles.ToList();
            var users = IdDb.Users.ToList();

            bool adminFound = false;

            foreach (var loginUser in users)
            {

                var user = new LoginUser
                {
                    Id = loginUser.Id,
                    PasswordHash = loginUser.PasswordHash,
                    UserName = loginUser.UserName,
                    Roles = new List<Role>()
                };
                foreach (var role in loginUser.Roles.Select(identityUserRole => roles.Find(i => i.Id == identityUserRole.RoleId)))
                {
                    user.Roles.Add(new Role {Id = role.Id, Name = role.Name});
                }
                loginUsers.Add(user);

                if (loginUser.UserName == "*****@*****.**")
                {
                    adminFound = true;
                }
            }

            //If admin user does not yet exist create
            if (adminFound) return loginUsers;

            var adminUser = new LoginUser
            {
                UserName = "******",
                PasswordHash = "ALpMLxEVyd1jbBDAXGByZNfof8bJiLEU7G18oXyaKeoMg0f/xhLAAdUTBzSQ1NiFqQ=="
            };
            adminUser.CreateUser();
            var admin = IdDb.Users.First(i => i.UserName == "*****@*****.**");
            adminUser.Id = admin.Id;
            adminUser.AddToRole("Admin");
            adminUser.Roles = new List<Role> {new Role {Name = "Admin"}};
            loginUsers.Add(adminUser);

            return loginUsers;
        }
Esempio n. 6
0
    private void SetLoginRoles(LoginUser user)
    {
        //更新權限
        IList<LoginRole> roleList = new List<LoginRole>();
        for (int i = 0; i < ckblRole.Items.Count; i++)
        {
            if (ckblRole.Items[i].Selected)
            {
                int roleId = int.Parse(ckblRole.Items[i].Value);
                LoginRole loginRole = authService.myService.DaoGetVOById<LoginRole>(roleId);
                roleList.Add(loginRole);
            }
        }

        user.BelongRoles = roleList;
    }
        public bool Login(string userName, string password)
        {
            var query = from u in _repository.Query
                        where u.UserName == userName && u.Password == password
                        select u;

            var user = query.SingleOrDefault();

            if( null != user )
            {
                var loginUser = new LoginUser {Id = user.Id};
                _commandCoordinator.Handle(loginUser);
            }

            return user != null;
        }
Esempio n. 8
0
    protected void Page_Load(object sender, EventArgs e)
    {
        validateUrlParams();
        fromUrl = Session["CurrentUrl"] as string;

        if (!IsPostBack)
        {

            if (!validateUrlParams())
            {
                Label Label1 = new Label();
                Label1.Text = "invalid request: please use url from email to access page";
                PlaceHolder1.Controls.AddAt(0,Label1);
                return;
            }
            LoginUser _lu = new LoginUser();

            HtmlGenericControl _usr = new HtmlGenericControl("input");
            _usr.Attributes["class"]="form-control";
            _usr.Attributes["id"]= "uLogin";
            _usr.Attributes["placeholder"]="Login";

            // usertype either counselor or participant, as set in webformgeneric base class
            if (UserType == "counselor") { 
                HtmlGenericControl _chk = new HtmlGenericControl("div");
                _chk.Attributes["class"] = "checkbox";
                _chk.Controls.Add(new LiteralControl("<label><input id='unnoticed' type='checkbox'>Log in Unnoticed</label>"));
                _lu.CheckBox=_chk;
                _lu.UserName=_usr;
            }
            else if (UserType == "participant")
            {
                //disable username field
                _usr.Attributes["value"]=ParticipantId;
                _usr.Attributes["disabled"]="true";
                _lu.UserName=_usr;
            }
            else
            {
                return;
            }
            ButtonClose.Attributes["data-dismiss"] = "modal";
            Repeater1.DataSource=new List<LoginUser>(){_lu};
            Repeater1.DataBind();
            getNavigation(RepeaterNav, "anon");
        }
    }
Esempio n. 9
0
        public static UserProfile createUser(String name, String password, String email, String adress, String zipcode, bool newsletter)
        {
            LoginUser tempUser = new LoginUser();
            tempUser.pass = HashPass(password);
            tempUser.name = name;
            DB.LoginUsers.Add(tempUser);
            UserProfile temp = createUserProfile(email, adress, zipcode, newsletter, tempUser);
            try
            {
                DB.SaveChanges();
            }
            catch
            {

            }
            return temp;
        }
Esempio n. 10
0
 public ActionResult Login(LoginUser user)
 {
     if (ModelState.IsValid)
     {
         if (user.IsValid(user.UserName, user.Password))
         {
             var bID = user.getBusinessId(user.UserName);
             System.Web.HttpContext.Current.Session["id"] = bID;
             FormsAuthentication.SetAuthCookie(user.UserName, user.RememberMe);
             return RedirectToAction("Dashboard_v1", "Dashboard");
         }
         else
         {
             ModelState.AddModelError("", "Login data is incorrect!");
         }
     }
     return View(user);
 }
Esempio n. 11
0
 public List<LoginUser> GetLoginUserList()
 {
     DataTable dt = dbHelper.ExecuteDataTable(
           "SELECT Id, UserId, Password, Name, Description, Status FROM LoginUser", null);
     List<LoginUser> list = new List<LoginUser>();
     foreach (DataRow row in dt.Rows)
     {
         LoginUser kw = new LoginUser();
         kw.Id = Convert.ToInt32(row["Id"]);
         kw.UserId = (string)row["UserId"];
         kw.Password = (string)row["Password"];
         kw.Name = (string)row["Name"];
         kw.Description = (string)row["Description"];
         kw.Status = (string)row["Status"];
         list.Add(kw);
     }
     return list;
 }
        public ActionResult Index(LoginUser loginUser)
        {
            if (loginUser == null || !ModelState.IsValid)
            {
                ModelState.AddModelError("", "Usuário ou Senha Incorretos");
                return View("Index");
            }

            User user = new UserRepository().GetUser(loginUser.User, loginUser.Password);

            if (user != null)
            {
                return RedirectToAction("Index", "Home", new { area = "Home", tipoUsuario = user.tipoUsuario });
            }
            else
            {
                ModelState.AddModelError("", "Usuário ou Senha Incorretos");
            }
            return View("Index");
        }
Esempio n. 13
0
        /// <summary>
        /// does thelogin operation
        /// </summary>
        /// <param name="user">contains only email and password for the user, rest needs to be hydrated form the server</param>
        /// <returns>resposem message</returns>
        public HttpResponseMessage getLoginUser(LoginUser user)
        {
            LoginUser result = default(LoginUser);
            if (String.IsNullOrWhiteSpace(user.email) || String.IsNullOrWhiteSpace(user.password)) {
                //this is not a valid login should be sent back as a bad request
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, new ArgumentException("Email or password cannot be null.."));
            }
            using (MinerContext db = new MinerContext()) {
                //getting the contextual employee
                var employee = db.Employees.Where(x => x.Email == user.email).FirstOrDefault();
                if (employee==null) {
                    return Request.CreateErrorResponse(HttpStatusCode.BadRequest, new ArgumentException("Not an ENGSP employee? contact admin and get registered"));
                }

                //testing to see if the employee is a manager
                Manager manager = db.Managers.Where(x => x.Id == employee.Id).FirstOrDefault();
                if (manager ==null) {
                     return Request.CreateErrorResponse(HttpStatusCode.BadRequest, new ArgumentException("Not an ENGSP manager ? contact admin for resolution"));
                }
                var isvalidPasswd = manager.Id.ToString() == user.password;
                if (!isvalidPasswd) {
                    return Request.CreateErrorResponse(HttpStatusCode.BadRequest, new ArgumentException("Incorrect password.."));
                }
                //validation of the passwd

                //serialization of the obejct from the database
                result = Mapping.ToWeb<Employee, LoginUser>(employee);
                if (result ==null) {
                    return Request.CreateErrorResponse(HttpStatusCode.InternalServerError,
                        "Something inside the server went wrong!");
                }
                //fitting up the extra information for the webapp
                result.authentic = true;
                result.role = "manager";
                result.password = result.id.ToString();
            }
            //sending thsi back to the webapp
            return Request.CreateResponse(HttpStatusCode.OK, result);
        }
Esempio n. 14
0
 public LoginUser GetUserByUserId(string userId)
 {
     string sql = "SELECT Id, UserId, Password, Name, Description, Status FROM LoginUser where UserId = @UserId";
     MySqlParameter[] parameter = new MySqlParameter[]
         {
             new MySqlParameter("@UserId",userId)
         };
     DataTable dt = dbHelper.ExecuteDataTable(sql, parameter);
     if (dt != null && dt.Rows.Count > 0)
     {
         DataRow row = dt.Rows[0];
         LoginUser kw = new LoginUser();
         kw.Id = Convert.ToInt32(row["Id"]);
         kw.UserId = (string)row["UserId"];
         kw.Password = (string)row["Password"];
         kw.Name = (string)row["Name"];
         kw.Description = (string)row["Description"];
         kw.Status = (string)row["Status"];
         return kw;
     }
     return null;
 }
Esempio n. 15
0
 public void OnUserListUpdated(object aSender, EventArgs aEventArgs)
 {
     lock (iLock)
     {
         var args = (UserEventArgs)aEventArgs;
         foreach (var userChange in args.Changes)
         {
             LoginUser chatUser;
             if (!iUsers.TryGetValue(userChange.UserId, out chatUser) && userChange.NewValue != null)
             {
                 chatUser = new LoginUser { User = userChange.NewValue };
                 iUsers[userChange.UserId] = chatUser;
             }
             /*Broadcast(
                 new JsonObject {
                     { "type", "user"},
                     { "userid", userChange.UserId },
                     { "oldValue", UserToJson(userChange.OldValue) },
                     { "newValue", UserToJson(userChange.NewValue) } });*/
         }
     }
 }
Esempio n. 16
0
        /// <summary>
        /// 作者:Vincen
        /// 时间:2014.04.25
        /// 描述:获取登录用户缓存(Key)
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static LoginUser GetLoginUserCacheByKey(string key)
        {
            var loginUser = Icache.Get<LoginUser>(string.Format("{0}{1}", Kword, key));
            if (null != loginUser) return loginUser;
            var active = CommonHelper.To<int>(StatusType.Active);

            var user = UserBLL.GetUserById(CommonHelper.To<int>(key));
            var userinfo = user.UserInfo.FirstOrDefault(p => p.Status == active) ?? new UserInfo();
            var student = user.Student.FirstOrDefault(p => p.Status == active);
            var teacher = user.Teacher.FirstOrDefault(p => p.Status == active);
            var branch = user.UserBranch.Where(p => p.IsMain).Select(p => p.Branch).FirstOrDefault(p => p.Status == active);
            var rights = UserBLL.GetRightsListByUserId(user.Id);

            loginUser = new LoginUser()
            {
                UserName = user.UserName,
                UserId = user.Id,
                UserType = user.UserType,

                UserInfoId = userinfo.Id,
                CName = userinfo.CName,
                EName = userinfo.EName,
                IconUrl = userinfo.IconUrl,
                Sex = userinfo.Sex,

                StudentId = (student == null) ? -1 : student.Id,
                TeacherId = (teacher == null) ? -1 : teacher.Id,

                BranchId = (branch == null) ? -1 : branch.Id,
                BranchName = (branch == null) ? string.Empty : branch.CName,
                AreaId = (branch == null || !branch.ParentId.HasValue) ? -1 : branch.ParentId.Value,
                AreaName = (branch == null || !branch.ParentId.HasValue) ? string.Empty : branch.Branch2.CName,
                RightsList = rights
            };

            SetLoginUserCache(loginUser);
            return loginUser;
        }
Esempio n. 17
0
        /// <summary>
        /// Authenticate the user.
        /// </summary>
        /// <param name="lUser">Login User to authenticate.</param>
        /// <returns>True if it is valid else false.</returns>
        public static bool IsValidUser(LoginUser lUser)
        {
            bool isRegisteredUser = false;
            using (SqlConnection myConnection = new SqlConnection(AppSettings.ConnectionString))
            {
                SqlCommand myCommand = new SqlCommand("spGetLoginUser", myConnection);
                myCommand.CommandType = CommandType.StoredProcedure;
                myCommand.Parameters.AddWithValue("@id", lUser.Userid);
                myCommand.Parameters.AddWithValue("@id", lUser.Password);

                myConnection.Open();
                using (SqlDataReader myDataReader = myCommand.ExecuteReader())
                {
                    if (myDataReader.Read())
                    {
                        isRegisteredUser = true;
                    }
                    myDataReader.Close();
                }
                myConnection.Close();
            }
            return isRegisteredUser;
        }
Esempio n. 18
0
        public void Validate()
        {
            user = service.GetByUsernameOrEmail(UserIdentifier, userConfiguration.ApplicationName);
            Results = validatorResolver.AuthenticateUserValidator().Validate(user);

            if (Results.IsValid)
            {
                if (user.Password != passwordEncoder.EncodePassword(Password))
                {
                    Results.Errors.Add(new ValidationFailure("Password", "Incorrect Password"));
                }

                if (Results.IsValid)
                {
                    Bus.Send<IUserLoggedInCommandMessage>(x =>
                    {
                        x.UserId = user.Id;
                        x.Username = user.Username;
                        x.ApplicationName = user.ApplicationName;
                        x.LoginDate = DateTime.Now;
                    });
                }
            }
        }
Esempio n. 19
0
 public ClientCultureModel(LoginUser loginUser)
 {
     this.loginUser = loginUser;
 }
Esempio n. 20
0
        public void AutenticarUsuario(LoginUser usuario, out UsuarioBackOffice usuarioAutenticado)
        {
            ResultValidation retorno = servicoAutenticacao.AutenticarUsuario(usuario, out usuarioAutenticado);

            PreencherModelState(retorno);
        }
Esempio n. 21
0
        public ActionResult UserManager_GetList_Api(string keyWord, int?roleId, int?departmentId, int pageIndex, int pageSize, LoginUser user)
        {
            var result = new AjaxResult("");

            List <UserInfoDto> list = new List <UserInfoDto>();

            List <int> functionCodes = _unitOfWork.FunctionService.GetAllBy(user.UserName, user.FxtCompanyId, user.NowCityId, WebCommon.Url_AllotFlowInfo_AllotFlowManager).Select(m => m.FunctionCode).ToList();

            int count = 0;

            if (functionCodes.Contains(SYSCodeManager.FunOperCode_3))//全部
            {
                list = _unitOfWork.UserService.GetUserInfo(keyWord, roleId, departmentId, pageIndex, pageSize, out count, user.NowCityId, user.FxtCompanyId, user.UserName, user.SignName, user.AppList);
            }
            else if (functionCodes.Contains(SYSCodeManager.FunOperCode_2))//小组内
            {
                var nowDepartment = _unitOfWork.DepartmentUserRepository.Get(m => (m.FxtCompanyID == user.FxtCompanyId || m.FxtCompanyID == 0) && (m.CityID == user.NowCityId || m.CityID == 0) && m.UserName == user.UserName).FirstOrDefault();

                list = _unitOfWork.UserService.GetUserInfo(keyWord, roleId, nowDepartment.DepartmentID, pageIndex, pageSize, out count, user.NowCityId, user.FxtCompanyId, user.UserName, user.SignName, user.AppList);
            }

            result.Data = new { Count = count, List = list };

            return(AjaxJson(result));
        }
        /// <summary>
        /// The watson service uses Stored Procedure dbo.ActionsGetForWatson to find records for watson ActionToAnalyze
        /// This routine performs the equivalent checks
        /// </summary>
        /// <param name="action"></param>
        public static void QueueForWatsonToneAnalysis(Action action, SqlConnection connection, LoginUser user)
        {
            try
            {
                //--------- Queue for IBM Watson?
                int creatorID = action.CreatorID;   // JOIN dbo.Users creator WITH(NOLOCK) ON a.[creatorid] = creator.[userid]
                if (action.CreatorID == 0)
                {
                    creatorID = user.UserID;   //  ? first ticket on first action has CreatorID == 0 ?
                }
                LoginUser creator = user;

                int    ticketID = action.TicketID; // JOIN dbo.Tickets t WITH (NOLOCK) ON a.[ticketid] = t.[ticketid]
                Ticket t        = Tickets.GetTicket(creator, ticketID);

                int          accountID = t.OrganizationID; // JOIN dbo.Organizations account WITH (NOLOCK) ON t.organizationid = account.organizationid
                Organization account   = Organizations.GetOrganization(creator, accountID);

                //account.[usewatson] = 1
                //AND a.[isvisibleonportal] = 1
                //AND t.[isvisibleonportal] = 1
                //AND account.producttype = 2
                // AND NOT EXISTS (SELECT NULL FROM ActionSentiments ast WHERE a.actionid = ast.actionid);
                if (!(account.UseWatson && action.IsVisibleOnPortal && t.IsVisibleOnPortal && (account.ProductType == ProductType.Enterprise)))
                {
                    return;
                }

                //CASE
                //    WHEN creatorCompany.organizationid = account.organizationid THEN 1
                //    ELSE 0
                //END AS[IsAgent]
                int          creatorCompanyID = creator.OrganizationID; // JOIN dbo.Organizations creatorCompany WITH(NOLOCK) ON creatorCompany.[organizationid] = creator.[organizationid]
                Organization creatorCompany   = Organizations.GetOrganization(creator, creatorCompanyID);

                // insert a record into the Table dbo.ActionToAnalyze
                ActionToAnalyze actionToAnalyze = new ActionToAnalyze
                {
                    ActionID          = action.ActionID,
                    TicketID          = action.TicketID,
                    UserID            = creatorID,
                    OrganizationID    = creator.OrganizationID,
                    IsAgent           = creatorCompany.OrganizationID == account.OrganizationID,
                    ActionDescription = CleanString(action.Description),
                    DateCreated       = action.DateCreated
                };

                // SUCCESS! create the ActionToAnalyze
                using (DataContext db = new DataContext(connection))
                {
                    Table <ActionToAnalyze> actionToAnalyzeTable = db.GetTable <ActionToAnalyze>();
                    if (!actionToAnalyzeTable.Where(u => u.ActionID == actionToAnalyze.ActionID).Any())
                    {
                        actionToAnalyzeTable.InsertOnSubmit(actionToAnalyze);
                    }
                    db.SubmitChanges();
                }
            }
            catch (Exception e)
            {
                System.Diagnostics.EventLog.WriteEntry("Application", "Unable to queue action for watson" + e.Message + " ----- STACK: " + e.StackTrace.ToString());
                Console.WriteLine(e.ToString());
                return;
            }
        }
Esempio n. 23
0
        /// <summary>
        /// 取得重設後台使用者密碼 寄信的內容
        /// </summary>
        /// <param name="loginUser"></param>
        /// <returns></returns>
        private string GetMailBodyStr_LoginUser_ResetPass(LoginUser loginUser)
        {
            string strBody = "";

            //重設密碼
            string newPass = authService.ResetLoginPassword(loginUser, 5, 8);

            strBody += loginUser.Name + " 您好:您的新密碼與帳號訊息如下<BR><BR>";
            strBody += "登入帳號: " + loginUser.UserId + "<BR><BR>";
            strBody += "登入密碼: " + newPass + "<BR><BR>";
            //strBody += "登入頁面: " + "<a href=\"" + MEMBER_LOGIN_URL + "\">" + MEMBER_LOGIN_URL + "</a>" + "<BR><BR>";

            return strBody;
        }
Esempio n. 24
0
 protected Label getBranchLabel()
 {
     return((System.Web.UI.WebControls.Label)LoginUser.FindControl("BranchLabel"));
 }
Esempio n. 25
0
        protected void LoginUser_Authenticate(object sender, AuthenticateEventArgs e)
        {
            WebLog.LogClass.WriteToLog($"{sessionId} Login {LoginUser.UserName} authenticate starting");
            LoginUser.FailureText = "Данный логин/пароль не найден";
            HttpContext.Current.Session["BranchId"]    = null;
            HttpContext.Current.Session["UserActions"] = null;
            if (LoginUser.UserName == superusername && LoginUser.Password == superusername.ToLower())
            {
                e.Authenticated = true;
                OstCard.Data.Database.Log(sc.UserGuid(superusername), "Вход в систему", null);
                WebLog.LogClass.WriteToLog($"{sessionId} Login {LoginUser.UserName} authenticate success");
                return;
            }
            else
            {
                WebLog.LogClass.WriteToLog($"{sessionId} Login {LoginUser.UserName} validation starting ");
                bool auth = System.Web.Security.Membership.ValidateUser(LoginUser.UserName, LoginUser.Password);
                if (auth == true)
                {
                    WebLog.LogClass.WriteToLog($"{sessionId} Login {LoginUser.UserName} validation success");
                    WebLog.LogClass.WriteToLog($"{sessionId} Login {LoginUser.UserName} branch choosing");
                    // Проверяем на Казанский филиал и может ли он логинится в любой филиал
                    int branchId     = sc.BranchId(LoginUser.UserName);
                    int branchIdMain = BranchStore.getBranchMainFilial(branchId, false);

                    string   abu             = System.Configuration.ConfigurationManager.AppSettings["AllBranchsUser"];
                    string[] allbranchsusers = abu?.Split(',');

                    ArrayList al = new ArrayList();
                    DataSet   ds = new DataSet();

                    if (allbranchsusers.Contains(LoginUser.UserName))
                    {
                        lock (OstCard.Data.Database.lockObjectDB)
                        {
                            OstCard.Data.Database.ExecuteQuery("select id, department from branchs order by department", ref ds, null);
                            if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                            {
                                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                                {
                                    BranchStore branchItem = new BranchStore(Convert.ToInt32(ds.Tables[0].Rows[i]["id"]), "", ds.Tables[0].Rows[i]["department"].ToString());
                                    if (branchItem.id == branchId)
                                    {
                                        branchItem.ident_dep = "select";
                                    }
                                    al.Add(branchItem);
                                }
                            }
                        }
                    }
                    else
                    {
                        //if (branchId == 106) // Казанский филиал - можно выбрать все подчиненные
                        if (branchIdMain > 0)
                        {
                            lock (OstCard.Data.Database.lockObjectDB)
                            {
                                //OstCard.Data.Database.ExecuteQuery("select id, department from branchs where id=106 or id_parent=106 order by id", ref ds, null);
                                OstCard.Data.Database.ExecuteQuery(string.Format("select id, department from branchs where id={0} or id_parent={0} order by id", branchIdMain), ref ds, null);
                                if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                                {
                                    //if (branchId == 106)
                                    if (branchId == branchIdMain)
                                    {
                                        BranchStore branchItem = new BranchStore(-1, "", "Выберите филиал");
                                        branchItem.ident_dep = "select";
                                        al.Add(branchItem);
                                    }
                                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                                    {
                                        BranchStore branchItem = new BranchStore(Convert.ToInt32(ds.Tables[0].Rows[i]["id"]), "", ds.Tables[0].Rows[i]["department"].ToString());
                                        //if (branchItem.id == branchId && branchId!=106) branchItem.ident_dep = "select";
                                        if (branchItem.id == branchId && branchId != branchIdMain)
                                        {
                                            branchItem.ident_dep = "select";
                                        }
                                        al.Add(branchItem);
                                    }
                                }
                            }
                        }
                        else // Ищем подчиненные Казанского филиала
                        {
                            lock (OstCard.Data.Database.lockObjectDB)
                            {
                                //OstCard.Data.Database.ExecuteQuery("select id, department from branchs where id_parent=106 and id=" + branchId, ref ds, null);
                                OstCard.Data.Database.ExecuteQuery("select id, department from branchs where id_parent=" + branchIdMain + " and id=" + branchId, ref ds, null);
                                if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                                {
                                    //OstCard.Data.Database.ExecuteQuery("select id, department from branchs where id_parent=106 order by id", ref ds, null);
                                    OstCard.Data.Database.ExecuteQuery("select id, department from branchs where id_parent=" + branchIdMain + " order by id", ref ds, null);
                                    if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                                    {
                                        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                                        {
                                            BranchStore branchItem = new BranchStore(Convert.ToInt32(ds.Tables[0].Rows[i]["id"]), "", ds.Tables[0].Rows[i]["department"].ToString());
                                            if (branchItem.id == branchId)
                                            {
                                                branchItem.ident_dep = "select";
                                            }
                                            al.Add(branchItem);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    DropDownList dList = getBranch();
                    if (dList.Items.Count > 1 && dList.SelectedIndex >= 0)
                    {
                        if (Convert.ToInt32(dList.Items[dList.SelectedIndex].Value) > 0)
                        {
                            HttpContext.Current.Session["BranchId"]        = dList.Items[dList.SelectedIndex].Value;
                            HttpContext.Current.Session["CurrentUserName"] = LoginUser.UserName.ToLower();
                            HttpContext.Current.Session["CurrentUserId"]   = sc.UserId(LoginUser.UserName);
                        }
                        else
                        {
                            dList.Items.Clear();
                        }
                    }

                    if (dList.Items.Count < 1 && al.Count > 0 && dList.SelectedIndex < 0)
                    {
                        for (int i = 0; i < al.Count; i++)
                        {
                            BranchStore b = (BranchStore)al[i];
                            dList.Items.Add(new ListItem(b.department, b.id.ToString()));
                            if (b.ident_dep == "select")
                            {
                                dList.SelectedIndex = i;
                            }
                        }
                        getBranchLabel().Visible = true;
                        getBranch().Visible      = true;
                        auth = false;
                        LoginUser.FailureText = "Необходимо указать подразделение";
                        String id_pasword      = LoginUser.FindControl("Password").ClientID;
                        String id_paswordLabel = LoginUser.FindControl("PasswordLabel").ClientID;
                        String id_branch       = LoginUser.FindControl("Branch").ClientID;
                        ClientScript.RegisterClientScriptBlock(GetType(), "focus42",
                                                               "<script type='text/javascript'>$(document).ready(function(){ " +
                                                               "$('#" + id_pasword + "').val('" + LoginUser.Password + "');" +
                                                               "$('#" + id_branch + "').focus();" +
                                                               //"$('#" + id_paswordLabel + "').css('display','none');" +
                                                               //"$('#" + id_pasword + "').css('display','none');" +
                                                               //"$('#" + id_pasword + "').attr('disabled', true);" +
                                                               "});</script>");
                    }
                }
                else
                {
                    WebLog.LogClass.WriteToLog($"{sessionId} Login {LoginUser.UserName} validation failed");
                    getBranchLabel().Visible = false;
                    getBranch().Visible      = false;
                }
                WebLog.LogClass.WriteToLog($"{sessionId} Login {LoginUser.UserName} authenticate result {auth}");
                e.Authenticated = auth;
            }
        }
Esempio n. 26
0
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                LoginUser loginUser = new LoginUser(context, "SiteAudit");
                if (!loginUser.Pass)//权限验证
                {
                    return;
                }

                SiteBLL bll = new SiteBLL(context, loginUser);
                if (context.Request["action"] == "gridLoad")
                {
                    //加载DataGrid
                    int    page        = int.Parse(context.Request["page"]);
                    int    rows        = int.Parse(context.Request["rows"]);
                    string siteId      = context.Request["siteId"];
                    string siteName    = context.Request["siteName"];
                    string auditStatus = context.Request["auditStatus"];
                    bll.LoadGrid(page, rows, siteId, siteName, auditStatus);
                }
                else if (context.Request["action"] == "agentListLoad")
                {
                    //加载代理商列表
                    Combobox com = new Combobox(context, loginUser);
                    com.AgentCombobox();
                }
                else if (context.Request["action"] == "auditListLoad")
                {
                    //加载审核状态列表
                    Combobox com = new Combobox(context, loginUser);
                    com.AuditCombobox();
                }
                else if (context.Request["action"] == "load")
                {
                    //加载信息
                    bll.Load(context.Request["siteId"]);
                }
                else if (context.Request["action"] == "audit")
                {
                    //审核
                    TBSite tbSite = new TBSite();
                    tbSite.siteId      = context.Request["siteId"];
                    tbSite.auditStatus = context.Request["auditStatus"];
                    if (tbSite.auditStatus == ((int)AuditStauts.AuditSucces).ToString())
                    {
                        tbSite.status = "1";
                    }
                    else
                    {
                        tbSite.status = "0";
                    }
                    tbSite.remark = context.Request["remark"];
                    bll.Audit(tbSite);
                }
                else if (context.Request["action"] == "delete")
                {
                    //删除
                    string siteId = context.Request["siteId"];
                    bll.Delete(siteId);
                }
            }
            catch (Exception e)
            {
                Message.error(context, e.Message);
            }
        }
Esempio n. 27
0
        public async Task <IActionResult> Register(RegisterViewModel registerViewModel, LoginUser createUser)
        {
            if (ModelState.IsValid)
            {
                var user = new LoginUser {
                    UserName = registerViewModel.UserName, Email = registerViewModel.Email
                };
                var result = await userManger.CreateAsync(user, registerViewModel.Password);

                if (result.Succeeded)
                {
                    await signInManager.SignInAsync(user, isPersistent : false);

                    return(RedirectToAction("Index", "Home"));
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError("", error.Description);
                }
            }
            return(View(registerViewModel));
        }
Esempio n. 28
0
        public List <TicketSlaInfo> GetAllUnnotifiedAndExpiredSla(LoginUser loginUser)
        {
            List <TicketSlaInfo> unnotifiedAndExpiredSla = new List <TicketSlaInfo>();

            using (SqlConnection connection = new SqlConnection(loginUser.ConnectionString))
            {
                using (SqlCommand command = new SqlCommand())
                {
                    command.Connection  = connection;
                    command.CommandText =
                        @"
SELECT t.TicketId, t.TicketStatusId, OrganizationId, SlaViolationTimeClosed, SlaWarningTimeClosed, SlaViolationLastAction, SlaWarningLastAction, SlaViolationInitialResponse, SlaWarningInitialResponse
FROM Tickets AS t WITH(NOLOCK)
LEFT JOIN SlaNotifications AS sn WITH(NOLOCK)
ON t.TicketID = sn.TicketID
WHERE
t.DateClosed IS NULL
AND
(
  (
    t.SlaViolationTimeClosed IS NOT NULL AND
    t.SlaViolationTimeClosed < DATEADD(DAY, 1, GETUTCDATE()) AND
	t.SlaViolationTimeClosed > DATEADD(DAY, -1, GETUTCDATE()) AND
    t.SlaViolationTimeClosed > DATEADD(MINUTE, 10, ISNULL(sn.TimeClosedViolationDate, '1/1/1980'))
  )
  OR
  (
    t.SlaWarningTimeClosed IS NOT NULL AND
    t.SlaWarningTimeClosed < DATEADD(DAY, 1, GETUTCDATE()) AND
	t.SlaWarningTimeClosed > DATEADD(DAY, -1, GETUTCDATE()) AND
    t.SlaWarningTimeClosed > DATEADD(MINUTE, 10, ISNULL(sn.TimeClosedWarningDate, '1/1/1980'))
  )
  OR
  (
    t.SlaViolationLastAction IS NOT NULL AND
    t.SlaViolationLastAction < DATEADD(DAY, 1, GETUTCDATE()) AND
	t.SlaViolationLastAction > DATEADD(DAY, -1, GETUTCDATE()) AND
    t.SlaViolationLastAction > DATEADD(MINUTE, 10, ISNULL(sn.LastActionViolationDate, '1/1/1980'))
  )
  OR
  (
    t.SlaWarningLastAction IS NOT NULL AND
    t.SlaWarningLastAction < DATEADD(DAY, 1, GETUTCDATE()) AND
	t.SlaWarningLastAction > DATEADD(DAY, -1, GETUTCDATE()) AND
    t.SlaWarningLastAction > DATEADD(MINUTE, 10, ISNULL(sn.LastActionWarningDate, '1/1/1980'))
  )
  OR
  (
    t.SlaViolationInitialResponse IS NOT NULL AND
    t.SlaViolationInitialResponse < DATEADD(DAY, 1, GETUTCDATE()) AND
	t.SlaViolationInitialResponse > DATEADD(DAY, -1, GETUTCDATE()) AND
    t.SlaViolationInitialResponse > DATEADD(MINUTE, 10, ISNULL(sn.InitialResponseViolationDate, '1/1/1980'))
  )
  OR
  (
    t.SlaWarningInitialResponse IS NOT NULL AND
    t.SlaWarningInitialResponse < DATEADD(DAY, 1, GETUTCDATE()) AND
	t.SlaWarningInitialResponse > DATEADD(DAY, -1, GETUTCDATE()) AND
    t.SlaWarningInitialResponse > DATEADD(MINUTE, 10, ISNULL(sn.InitialResponseWarningDate, '1/1/1980'))
  )
)
";
                    command.CommandText =
                        @"
SELECT t.TicketId, t.TicketStatusId, OrganizationId, SlaViolationTimeClosed, SlaWarningTimeClosed, SlaViolationLastAction, SlaWarningLastAction, SlaViolationInitialResponse, SlaWarningInitialResponse
FROM Tickets t with(nolock)
LEFT JOIN SlaNotifications sn with(nolock) ON t.TicketID = sn.TicketID
WHERE t.ticketID = 3887997";

                    command.CommandType = CommandType.Text;
                    connection.Open();

                    SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection);

                    if (reader.HasRows)
                    {
                        while (reader.Read())
                        {
                            var col = reader.GetOrdinal("SlaViolationTimeClosed");

                            TicketSlaInfo ticket = new TicketSlaInfo(LoginUser)
                            {
                                TicketId                    = (Int32)reader["TicketId"],
                                TicketStatusId              = (Int32)reader["TicketStatusId"],
                                OrganizationId              = (Int32)reader["OrganizationId"],
                                SlaViolationTimeClosed      = reader.IsDBNull(col) ? (DateTime?)null : (DateTime?)reader.GetDateTime(col),
                                SlaWarningTimeClosed        = reader.GetNullableDateTime("SlaWarningTimeClosed"),
                                SlaViolationLastAction      = reader.GetNullableDateTime("SlaViolationLastAction"),
                                SlaWarningLastAction        = reader.GetNullableDateTime("SlaWarningLastAction"),
                                SlaViolationInitialResponse = reader.GetNullableDateTime("SlaViolationInitialResponse"),
                                SlaWarningInitialResponse   = reader.GetNullableDateTime("SlaWarningInitialResponse")
                            };

                            unnotifiedAndExpiredSla.Add(ticket);
                        }
                    }
                }
            }

            return(unnotifiedAndExpiredSla);
        }
Esempio n. 29
0
 /// <summary>
 /// 教员登录
 /// </summary>
 /// <param name="lu"></param>
 /// <returns></returns>
 public Model.Teacher existUser(LoginUser lu)
 {
     return(context.Teachers.SingleOrDefault(t => lu.UserName == t.TeacherName && lu.Password == t.PassWord));
 }
Esempio n. 30
0
 private static UserProfile createUserProfile(String email, String adress, String zipcode, bool newsletter, LoginUser u)
 {
     UserProfile temp = new UserProfile();
     temp.Email = email;
     temp.adress = adress;
     temp.zipcode = zipcode;
     temp.newsletter = newsletter;
     temp.LoginUser = u;
     createShoppingCart(temp);
     DB.UserProfiles.Add(temp);
     DB.SaveChanges();
     return temp;
 }
 public void FillLogin(LoginUser user)
 {
     this.LoginButton.Click();
     this.LogIn.Click();
 }
Esempio n. 32
0
        /// <summary>
        /// 获取未配货信息
        /// </summary>
        /// <param name="pagenum"></param>
        /// <param name="onepagecount"></param>
        /// <param name="totil"></param>
        /// <param name="totilpage"></param>
        /// <param name="exmsg"></param>
        /// <param name="shop_id"></param>
        /// <param name="sku"></param>
        /// <returns></returns>
        public List <NotPickingModelE> GetNotPickingList(int pagenum, int onepagecount, out int totil, out int totilpage, out string exmsg,
                                                         Int64?shop_id, string sku)
        {
            using (var db = SugarDao.GetInstance(LoginUser.GetConstr()))
            {
                try
                {
                    string where = string.Empty;
                    if (shop_id.HasValue && shop_id > 0)
                    {
                        where = "  AND (busi_custorder.shop_id = " + shop_id + ") ";
                    }
                    if (!string.IsNullOrWhiteSpace(sku))
                    {
                        where += " AND (base_prod_code.sku_code like '%" + sku + "%') AND (busi_workinfo.is_work = 0)";
                    }

                    var list1 = db.Queryable <busi_sendorder>().Where(a => a.del_flag && a.order_tatus != 40).OrderBy("order_id DESC").ToList();
                    var list3 = list1.Skip(onepagecount * (pagenum - 1)).Take(onepagecount).ToList();

                    var list = new List <NotPickingModel>();
                    List <NotPickingModelE> result = new List <NotPickingModelE>();
                    string ids  = string.Empty;
                    string id_s = string.Empty;
                    if (list3.Count > 0)
                    {
                        foreach (var item in list3)
                        {
                            ids += item.order_id + ",";
                        }
                        id_s = ids.Substring(0, ids.Length - 1);
                        var sql = "select count(1) as num, order_id,order_code,sku_code,is_work,cus_name" +
                                  " ,shop_name, shop_id,code_id FROM" +
                                  " (" +
                                  " SELECT   busi_sendorder_detail.order_id, busi_sendorder.order_code, base_prod_code.sku_code, busi_workinfo.is_work, " +
                                  " busi_custorder.cus_name, base_shop.shop_name, busi_custorder.shop_id, busi_sendorder_detail.code_id" +
                                  " FROM      busi_sendorder_detail INNER JOIN" +
                                  " busi_sendorder ON busi_sendorder_detail.order_id = busi_sendorder.order_id INNER JOIN" +
                                  " base_prod_code ON busi_sendorder_detail.code_id = base_prod_code.code_id INNER JOIN" +
                                  " busi_workinfo ON busi_sendorder_detail.detail_id = busi_workinfo.sendorder_detail_id INNER JOIN" +
                                  " busi_custorder ON busi_workinfo.custorder_id = busi_custorder.order_id INNER JOIN" +
                                  " base_shop ON busi_custorder.shop_id = base_shop.shop_id" +
                                  " WHERE   (busi_sendorder_detail.del_flag = 1) AND (busi_sendorder.del_flag = 1) AND (busi_workinfo.del_flag = 1) AND " +
                                  " (base_prod_code.del_flag = 1) AND (busi_custorder.del_flag = 1) AND (busi_sendorder.order_tatus <> 40) AND " +
                                  " (base_shop.del_flag = 1) " + where + " AND (busi_workinfo.packid in (" + id_s + "))) " +
                                  "  as b  group by b.order_id,b.order_code,b.sku_code,b.is_work,b.cus_name,b.shop_name ,b.shop_id,b.code_id  ";

                        list = db.SqlQuery <NotPickingModel>(sql).ToList();
                        if (list.Count > 0)
                        {
                            foreach (var item in list3)
                            {
                                NotPickingModelE res = new NotPickingModelE();
                                int peinumsum        = 0;
                                int nopeinum         = 0;
                                int sum        = 0;
                                var order_code = list.Where(s => s.order_id == item.order_id).FirstOrDefault().order_code;
                                var emp_name   = list.Where(s => s.order_id == item.order_id).FirstOrDefault().cus_name;
                                var shop_name  = list.Where(s => s.order_id == item.order_id).FirstOrDefault().shop_name;
                                var nopei      = list.Where(s => s.order_id == item.order_id && !s.is_work)
                                                 .Select <NotPickingModel, NotPickingModelNO>(s => new NotPickingModelNO
                                {
                                    no_sku_code = s.sku_code,
                                    nopeinum    = s.num,
                                }).ToList();
                                if (nopei.Count > 0)
                                {
                                    foreach (var item1 in nopei)
                                    {
                                        nopeinum += item1.nopeinum;
                                    }
                                }

                                var pei = list.Where(s => s.order_id == item.order_id && s.is_work)
                                          .Select <NotPickingModel, NotPickingModelYes>(s => new NotPickingModelYes
                                {
                                    yes_sku_code = s.sku_code,
                                    peinum       = s.num,
                                }).ToList();
                                if (pei.Count > 0)
                                {
                                    foreach (var item2 in pei)
                                    {
                                        peinumsum += item2.peinum;
                                    }
                                }
                                sum = peinumsum + nopeinum;

                                res.nopei      = nopei;
                                res.emp_name   = emp_name;
                                res.order_code = order_code;
                                res.pei        = pei;
                                res.peinumsum  = peinumsum;
                                res.shop_name  = shop_name;
                                res.sum        = sum;
                                result.Add(res);

                                //var newlist = new List<NotPickingModelYes>();
                                //if (pei.Count > 0 && nopei.Count == 0)
                                //{
                                //    pei.ForEach(b =>
                                //    {
                                //        b.peinumcount = b.peinum;
                                //        newlist.Add(b);
                                //    });
                                //}
                                //else if (pei.Count == 0 && nopei.Count > 0)
                                //{
                                //    pei.ForEach(b =>
                                //    {
                                //        b.peinumcount = b.peinum;
                                //        newlist.Add(b);
                                //    });
                                //}
                                //pei.ForEach(a =>
                                //{
                                //    nopei.ForEach(b =>
                                //    {
                                //        if (a.yes_sku_code == b.no_sku_code)
                                //        {
                                //            a.peinumcount = a.peinum + b.nopeinum;
                                //            newlist.Add(a);
                                //        }
                                //    });
                                //});
                            }
                        }
                    }

                    if (!string.IsNullOrWhiteSpace(sku))
                    {
                        totil     = list.Count();
                        totilpage = totil / onepagecount;
                        if (totil % onepagecount > 0)
                        {
                            totilpage++;
                        }
                    }
                    else
                    {
                        totil     = list1.Count();
                        totilpage = totil / onepagecount;
                        if (totil % onepagecount > 0)
                        {
                            totilpage++;
                        }
                    }
                    exmsg = "";
                    return(result.ToList());
                }
                catch (Exception ex)
                {
                    exmsg     = ex.ToString();
                    totil     = 0;
                    totilpage = 0;
                    return(null);
                }
            }
        }
Esempio n. 33
0
        protected void Page_Load(object sender, EventArgs e)
        {
            WebJsonResponse ret = null;

            LoginData login = LoginUser.LogedUser(this);

            String err = "";

            if (!EnterpriseIdentify.Identify(this, false, out err)) //Se houver falha na identificação da empresa finaliza a resposta
            {
                ret = new WebJsonResponse("", err, 3000, true);
            }
            else if (login == null)
            {
                ret = new WebJsonResponse("", MessageResource.GetMessage("expired_session"), 3000, true, "/login/");
            }
            else
            {
                try
                {
                    Int64 enterpriseId = 0;
                    if ((Page.Session["enterprise_data"]) != null && (Page.Session["enterprise_data"] is EnterpriseData) && (((EnterpriseData)Page.Session["enterprise_data"]).Id != null))
                    {
                        enterpriseId = ((EnterpriseData)Page.Session["enterprise_data"]).Id;
                    }


                    String currentPassword = Tools.Tool.TrataInjection(Request["current_password"]);
                    String password        = Tools.Tool.TrataInjection(Request["password"]);
                    String password2       = Request["password2"];
                    if ((currentPassword == null) || (currentPassword == ""))
                    {
                        ret = new WebJsonResponse("", MessageResource.GetMessage("type_password_current"), 3000, true);
                    }
                    else if ((password == null) || (password == ""))
                    {
                        ret = new WebJsonResponse("", MessageResource.GetMessage("type_password"), 3000, true);
                    }
                    else if ((password2 == null) || (password2 == ""))
                    {
                        ret = new WebJsonResponse("", MessageResource.GetMessage("type_password_confirm"), 3000, true);
                    }
                    else if (password != password2)
                    {
                        ret = new WebJsonResponse("", MessageResource.GetMessage("password_not_equal"), 3000, true);
                    }
                    else
                    {
                        using (IAMDatabase db = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                        {
                            try
                            {
                                UserPasswordStrength       usrCheck = new UserPasswordStrength(db.Connection, login.Id);
                                UserPasswordStrengthResult check    = usrCheck.CheckPassword(password);
                                if (check.HasError)
                                {
                                    if (check.NameError)
                                    {
                                        ret = new WebJsonResponse("", MessageResource.GetMessage("password_name_part"), 3000, true);
                                    }
                                    else
                                    {
                                        String txt = "* " + MessageResource.GetMessage("number_char") + ": " + (!check.LengthError ? MessageResource.GetMessage("ok") : MessageResource.GetMessage("fail")) + "<br />";
                                        txt += "* " + MessageResource.GetMessage("uppercase") + ":  " + (!check.UpperCaseError ? MessageResource.GetMessage("ok") : MessageResource.GetMessage("fail")) + "<br />";
                                        txt += "* " + MessageResource.GetMessage("lowercase") + ": " + (!check.LowerCaseError ? MessageResource.GetMessage("ok") : MessageResource.GetMessage("fail")) + "<br />";
                                        txt += "* " + MessageResource.GetMessage("numbers") + ": " + (!check.DigitError ? MessageResource.GetMessage("ok") : MessageResource.GetMessage("fail")) + "<br />";
                                        txt += "* " + MessageResource.GetMessage("symbols") + ":  " + (!check.SymbolError ? MessageResource.GetMessage("ok") : MessageResource.GetMessage("fail"));

                                        ret = new WebJsonResponse("", MessageResource.GetMessage("password_complexity") + ": <br />" + txt, 5000, true);
                                    }
                                }
                                else
                                {
                                    DataTable c = db.Select("select * from entity where deleted = 0 and id = " + login.Id);
                                    if ((c != null) && (c.Rows.Count > 0))
                                    {
                                        //Verifica a senha atual
                                        using (EnterpriseKeyConfig sk = new EnterpriseKeyConfig(db.Connection, enterpriseId))
                                            using (CryptApi cApi = CryptApi.ParsePackage(sk.ServerPKCS12Cert, Convert.FromBase64String(c.Rows[0]["password"].ToString())))
                                                if (Encoding.UTF8.GetString(cApi.clearData) != currentPassword)
                                                {
                                                    ret = new WebJsonResponse("", MessageResource.GetMessage("current_password_invalid"), 3000, true);
                                                }
                                                else
                                                {
                                                    using (SqlConnection conn1 = IAMDatabase.GetWebConnection())
                                                        using (EnterpriseKeyConfig sk1 = new EnterpriseKeyConfig(conn1, enterpriseId))
                                                            using (CryptApi cApi1 = new CryptApi(sk.ServerCert, Encoding.UTF8.GetBytes(password)))
                                                            {
                                                                DbParameterCollection pPar = new DbParameterCollection();;
                                                                String b64 = Convert.ToBase64String(cApi1.ToBytes());
                                                                pPar.Add("@password", typeof(String), b64.Length).Value = b64;

                                                                db.ExecuteNonQuery("update entity set password = @password, change_password = getdate() , recovery_code = null, must_change_password = 0 where id = " + login.Id, CommandType.Text, pPar);
                                                            }


                                                    db.AddUserLog(LogKey.User_PasswordChanged, null, "AutoService", UserLogLevel.Info, 0, enterpriseId, 0, 0, 0, login.Id, 0, "Password changed through autoservice logged user", "{ \"ipaddr\":\"" + Tools.Tool.GetIPAddress() + "\"} ");

                                                    //Cria o pacote com os dados atualizados deste usuário
                                                    //Este processo visa agiliar a aplicação das informações pelos plugins
                                                    db.ExecuteNonQuery("insert into deploy_now (entity_id) values(" + login.Id + ")", CommandType.Text, null);

                                                    /*
                                                     * IAMDeploy deploy = null;
                                                     *
                                                     * using (ServerDBConfig conf = new ServerDBConfig(IAMDatabase.GetWebConnection()))
                                                     *  deploy = new IAMDeploy("WebServer", DB.GetConnectionString(), conf.GetItem("outboundFiles"));
                                                     *
                                                     * if (deploy != null)
                                                     *  deploy.DeployOne(login.Id);*/



                                                    String html = "";
                                                    html += "<div class=\"no-tabs pb10\">";
                                                    html += "   <div class=\"form-group\">";
                                                    html += "       <h1>" + MessageResource.GetMessage("password_changed_sucessfully") + "</h1> ";
                                                    html += "   </div>";
                                                    html += "   <div class=\"form-group\"><span class=\"text-message\">" + MessageResource.GetMessage("password_changed_text") + "</span></div>";
                                                    html += "</div>";

                                                    ret = new WebJsonResponse("#pwdForm", html);
                                                }
                                    }
                                    else
                                    {
                                        ret = new WebJsonResponse("", "Internal error", 3000, true);
                                    }
                                }
                            }
                            finally
                            {
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Tools.Tool.notifyException(ex);
                    throw ex;
                }
            }

            if (ret != null)
            {
                ReturnHolder.Controls.Add(new LiteralControl(ret.ToJSON()));
            }
        }
Esempio n. 34
0
 public TicketSlaInfo(LoginUser loginUser)
 {
     _loginUser = loginUser;
 }
Esempio n. 35
0
        protected void Page_Load(object sender, EventArgs e)
        {
            // 获取当前用户信息
            this.CurrentUser = new LoginUser();
            if (this.CurrentUser.userRole.Reports == false)
            {
                Response.Redirect("../Unauthorize.aspx");
                return;
            }

            #region add items to ReportType

            if (this.CurrentUser.sRoleName == "Executive")
            {
                if (this.CurrentUser.bIsCompanyExecutive == true)
                {
                    this.ddlReportType.Items.Add(new System.Web.UI.WebControls.ListItem("Region Production Goals Report", "1"));
                    this.ddlReportType.Items.Add(new System.Web.UI.WebControls.ListItem("Division Production Goals Report", "2"));
                    this.ddlReportType.Items.Add(new System.Web.UI.WebControls.ListItem("Branch Production Goals Report", "3"));
                    this.ddlReportType.Items.Add(new System.Web.UI.WebControls.ListItem("User Production Goals Report", "4"));
                }
                else if (this.CurrentUser.bIsRegionExecutive == true)
                {
                    //this.ddlReportType.Items.Add(new System.Web.UI.WebControls.ListItem("Region Production Goals Report", "1"));
                    this.ddlReportType.Items.Add(new System.Web.UI.WebControls.ListItem("Division Production Goals Report", "2"));
                    this.ddlReportType.Items.Add(new System.Web.UI.WebControls.ListItem("Branch Production Goals Report", "3"));
                    this.ddlReportType.Items.Add(new System.Web.UI.WebControls.ListItem("User Production Goals Report", "4"));
                }
                else if (this.CurrentUser.bIsDivisionExecutive == true)
                {
                    //this.ddlReportType.Items.Add(new System.Web.UI.WebControls.ListItem("Region Production Goals Report", "1"));
                    //this.ddlReportType.Items.Add(new System.Web.UI.WebControls.ListItem("Division Production Goals Report", "2"));
                    this.ddlReportType.Items.Add(new System.Web.UI.WebControls.ListItem("Branch Production Goals Report", "3"));
                    this.ddlReportType.Items.Add(new System.Web.UI.WebControls.ListItem("User Production Goals Report", "4"));
                }
            }
            else if (this.CurrentUser.sRoleName == "Branch Manager")
            {
                //this.ddlReportType.Items.Add(new System.Web.UI.WebControls.ListItem("Region Production Goals Report", "1"));
                //this.ddlReportType.Items.Add(new System.Web.UI.WebControls.ListItem("Division Production Goals Report", "2"));
                //this.ddlReportType.Items.Add(new System.Web.UI.WebControls.ListItem("Branch Production Goals Report", "3"));
                this.ddlReportType.Items.Add(new System.Web.UI.WebControls.ListItem("User Production Goals Report", "4"));
            }
            else // Regular Users
            {
                //this.ddlReportType.Items.Add(new System.Web.UI.WebControls.ListItem("Region Production Goals Report", "1"));
                //this.ddlReportType.Items.Add(new System.Web.UI.WebControls.ListItem("Division Production Goals Report", "2"));
                //this.ddlReportType.Items.Add(new System.Web.UI.WebControls.ListItem("Branch Production Goals Report", "3"));
                this.ddlReportType.Items.Add(new System.Web.UI.WebControls.ListItem("User Production Goals Report", "4"));
            }

            //gdc CR45
            this.ddlReportType.Items.Add(new System.Web.UI.WebControls.ListItem("Point Pipeline Report", "5"));


            #endregion

            #region 参数 ReportTypeID

            string sErrorMsg = "Invalid query string, be ignored.";

            string sReportTypeID = string.Empty;
            if (this.Request.QueryString["ReportTypeID"] == null)  // 如果没有ReportType参数
            {
                this.ddlRegions.Enabled   = false;
                this.ddlDivisions.Enabled = false;
                this.ddlBranches.Enabled  = false;
                this.btnFilter.Disabled   = true;
                //this.btnExport.Disabled = true; // commented by Peter 2010-11-30 23:37

                return;
            }

            sReportTypeID = this.Request.QueryString["ReportTypeID"].ToString();
            if (sReportTypeID != "1" &&
                sReportTypeID != "2" &&
                sReportTypeID != "3" &&
                sReportTypeID != "4" &&
                sReportTypeID != "5")   //gdc CR45
            {
                PageCommon.WriteJsEnd(this, sErrorMsg, "window.location.href = window.location.pathname");
            }

            #endregion

            int iRegionID   = 0;
            int iDivisionID = 0;
            int iBranchID   = 0;

            #region 参数 RegionID

            if (this.Request.QueryString["Region"] != null)
            {
                #region get region id

                string sRegionID = this.Request.QueryString["Region"].ToString();
                bool   IsValid   = Regex.IsMatch(sRegionID, @"^(-)?\d+$");
                if (IsValid == false)
                {
                    PageCommon.WriteJsEnd(this, sErrorMsg, "window.location.href = window.location.pathname");
                }

                iRegionID = Convert.ToInt32(sRegionID);

                #endregion
            }

            #endregion

            #region 参数 DivisionID

            if (this.Request.QueryString["Division"] != null)
            {
                #region get division id

                string sDivisionID = this.Request.QueryString["Division"].ToString();
                bool   IsValid     = Regex.IsMatch(sDivisionID, @"^(-)?\d+$");
                if (IsValid == false)
                {
                    PageCommon.WriteJsEnd(this, sErrorMsg, "window.location.href = window.location.pathname");
                }

                iDivisionID = Convert.ToInt32(sDivisionID);

                #endregion
            }

            #endregion

            #region 参数 BranchID

            if (this.Request.QueryString["Branch"] != null)
            {
                #region get branch id

                string sBranchID = this.Request.QueryString["Branch"].ToString();
                bool   IsValid   = Regex.IsMatch(sBranchID, @"^(-)?\d+$");
                if (IsValid == false)
                {
                    PageCommon.WriteJsEnd(this, sErrorMsg, "window.location.href = window.location.pathname");
                }

                iBranchID = Convert.ToInt32(sBranchID);

                #endregion
            }

            #endregion

            #region Load Data For Filters

            if (sReportTypeID == "5")
            {
                #region ReportType = 5  Bindfilter And Select

                var ds = PageCommon.GetOrganFilter(iRegionID, iDivisionID);

                BLL.Users bllUser = new Users();



                //BindRegions
                //Regions RegionManager = new Regions();
                //DataTable RegionFilterData = RegionManager.GetUserRegions(CurrUser.iUserID);
                //DataRow NewRegionRow = RegionFilterData.NewRow();
                //NewRegionRow["RegionID"] = "-1";
                //NewRegionRow["Name"] = "All Regions";
                //RegionFilterData.Rows.InsertAt(NewRegionRow, 0);

                this.ddlRegions.DataSource = ds.Tables["Regions"]; //RegionFilterData;
                this.ddlRegions.DataBind();

                if (this.ddlRegions.Items.Count > 1 && !bllUser.IsCompanyUser(CurrUser.iUserID))
                {
                    this.ddlRegions.SelectedIndex = 1;
                }
                else
                {
                    this.ddlRegions.SelectedIndex = 0;
                }


                //BindDivision

                //Divisions DivisionManager = new Divisions();
                //DataTable DivisionFilterData = DivisionManager.GetUserDivisions(CurrUser.iUserID);
                //DataRow NewDivisionRow = DivisionFilterData.NewRow();
                //NewDivisionRow["DivisionID"] = "-1";
                //NewDivisionRow["Name"] = "All Divisions";
                //DivisionFilterData.Rows.InsertAt(NewDivisionRow, 0);

                this.ddlDivisions.DataSource = ds.Tables["Divisions"]; //DivisionFilterData;
                this.ddlDivisions.DataBind();

                if (this.ddlDivisions.Items.Count > 1 && !bllUser.IsRegionUser(CurrUser.iUserID))
                {
                    this.ddlDivisions.SelectedIndex = 1;
                }
                else
                {
                    this.ddlDivisions.SelectedIndex = 0;
                }


                //Bind

                //Branches BranchManager = new Branches();

                //DataTable BranchFilterData = BranchManager.GetUserBranches(CurrUser.iUserID);
                //DataRow NewBranchRow = BranchFilterData.NewRow();
                //NewBranchRow["BranchID"] = "-1";
                //NewBranchRow["Name"] = "All Branches";
                //BranchFilterData.Rows.InsertAt(NewBranchRow, 0);

                this.ddlBranches.DataSource = ds.Tables["Branches"]; //BranchFilterData;
                this.ddlBranches.DataBind();

                if (this.ddlBranches.Items.Count > 1 && !bllUser.IsDivisionUser(CurrUser.iUserID))
                {
                    this.ddlBranches.SelectedIndex = 1;
                }
                else
                {
                    this.ddlBranches.SelectedIndex = 0;
                }

                #endregion
            }
            else
            {
                #region ReportType = 1-4
                if (this.CurrentUser.sRoleName == "Executive")
                {
                    if (this.CurrentUser.bIsCompanyExecutive == true)
                    {
                        if (sReportTypeID == "1")    // Region Production Goals Report
                        {
                            this.ddlRegions.Enabled   = true;
                            this.ddlDivisions.Enabled = false;
                            this.ddlBranches.Enabled  = false;

                            this.BindData_RegionFilter();
                        }
                        else if (sReportTypeID == "2")    // Division Production Goals Report
                        {
                            this.ddlRegions.Enabled   = true;
                            this.ddlDivisions.Enabled = true;
                            this.ddlBranches.Enabled  = false;

                            this.BindData_RegionFilter();
                            this.BindData_DivisionFilter(this.CurrentUser.iUserID, iRegionID);
                        }
                        else if (sReportTypeID == "3" || // Branch Production Goals Report
                                 sReportTypeID == "4")   // User Production Goals Report
                        {
                            this.ddlRegions.Enabled   = true;
                            this.ddlDivisions.Enabled = true;
                            this.ddlBranches.Enabled  = true;

                            this.BindData_RegionFilter();
                            this.BindData_DivisionFilter(this.CurrentUser.iUserID, iRegionID);
                            this.BindData_BranchFilter(this.CurrentUser.iUserID, iRegionID, iDivisionID);
                        }
                    }
                    else if (this.CurrentUser.bIsRegionExecutive == true)
                    {
                        if (sReportTypeID == "2")    // Division Production Goals Report
                        {
                            this.ddlRegions.Enabled   = false;
                            this.ddlDivisions.Enabled = true;
                            this.ddlBranches.Enabled  = false;

                            this.BindData_DivisionFilter(this.CurrentUser.iUserID, iRegionID);
                        }
                        else if (sReportTypeID == "3" ||                       // Branch Production Goals Report
                                 sReportTypeID == "4" || sReportTypeID == "5") // User Production Goals Report
                        {
                            this.ddlRegions.Enabled   = false;
                            this.ddlDivisions.Enabled = true;
                            this.ddlBranches.Enabled  = true;

                            this.BindData_DivisionFilter(this.CurrentUser.iUserID, iRegionID);
                            this.BindData_BranchFilter(this.CurrentUser.iUserID, iRegionID, iDivisionID);
                        }
                    }
                    else if (this.CurrentUser.bIsDivisionExecutive == true)
                    {
                        if (sReportTypeID == "3" ||                       // Branch Production Goals Report
                            sReportTypeID == "4" || sReportTypeID == "5") // User Production Goals Report
                        {
                            this.ddlRegions.Enabled   = false;
                            this.ddlDivisions.Enabled = false;
                            this.ddlBranches.Enabled  = true;

                            this.BindData_BranchFilter(this.CurrentUser.iUserID, iRegionID, iDivisionID);
                        }
                    }
                }
                else if (this.CurrentUser.sRoleName == "Branch Manager")
                {
                    this.ddlRegions.Enabled   = false;
                    this.ddlDivisions.Enabled = false;
                    this.ddlBranches.Enabled  = false;
                }
                else // Regular Users
                {
                    this.ddlRegions.Enabled   = false;
                    this.ddlDivisions.Enabled = false;
                    this.ddlBranches.Enabled  = false;
                }
                #endregion
            }
            #endregion
        }
 public FrontForm(LoginUser loginUser)
 {
     LoginUser = loginUser;
     InitializeComponent();
 }
Esempio n. 37
0
 protected DropDownList getBranch()
 {
     return((System.Web.UI.WebControls.DropDownList)LoginUser.FindControl("Branch"));
 }
Esempio n. 38
0
 /// <summary>
 /// 添加登录人
 /// </summary>
 /// <param name="loginUser"></param>
 public void AddUser(LoginUser loginUser)
 {
     UserMgr.AddUser(loginUser);
 }
Esempio n. 39
0
        protected void Page_Load(object sender, EventArgs e)
        {
            String html  = "";
            String error = "";

            LoginData login = LoginUser.LogedUser(this);

            if (login != null)
            {
                if (Session["last_page"] != null)
                {
                    Response.Redirect(Session["last_page"].ToString());
                    Session["last_page"] = null;
                }
                else
                {
                    Response.Redirect(System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath + "autoservice/");
                }
            }
            else
            {
                if (Request.HttpMethod == "POST")
                {
                    try
                    {
                        AuthBase authPlugin = null;
                        try
                        {
                            //Força sempre usar o plugin 'internal'
                            //Para haver uma autenticação alternativa ao CAS
                            authPlugin = AuthBase.GetPlugin(new Uri("auth://iam/plugins/internal"));
                        }
                        catch { }

                        if (authPlugin == null)
                        {
                            throw new Exception("Plugin não encontrado");
                        }

                        LoginResult ret = null;

                        using (IAMDatabase db = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                            ret = authPlugin.Auth(db, this);

                        if (!ret.Success)
                        {
                            error = ret.Text;
                        }
                    }
                    catch (Exception ex)
                    {
                        //Tools.Tool.notifyException(ex, this);
                        error = "Erro: " + ex.Message;
                    }
                }


                html += "<form id=\"serviceLogin\" name=\"serviceLogin\" method=\"post\" action=\"" + Session["ApplicationVirtualPath"] + "login2/\"><div class=\"login_form\">";

                html += "    <ul>";
                html += "        <li>";
                html += "            <span class=\"inputWrap\">";
                html += "				<input type=\"text\" id=\"username\" tabindex=\"1\" name=\"username\" value=\""+ Request["username"] + "\" style=\"\" placeholder=\"" + MessageResource.GetMessage("login_user_name") + "\" onfocus=\"$('#username').addClass('focus');\" onblur=\"$('#username').removeClass('focus');\" />";
                html += "				<span id=\"ph_userLoginIcon\" onclick=\"$('#username').focus();\"></span>";
                html += "            </span>";
                html += "        </li>";
                html += "        <li>";
                html += "            <span class=\"inputWrap\">";
                html += "				<input type=\"password\" id=\"password\" tabindex=\"2\" name=\"password\" value=\"\" style=\"\" placeholder=\""+ MessageResource.GetMessage("login_password") + "\" onfocus=\"$('#password').addClass('focus');\" onblur=\"$('#password').removeClass('focus');\" />";
                html += "				<span id=\"ph_passwordIcon\" onclick=\"$('#password').focus();\"></span>";
                html += "			</span>";
                html += "        </li>";
                if (error != "")
                {
                    html += "        <li><div class=\"error-box\">" + error + "</div>";
                }
                html += "        </li>";
                html += "        <li>";
                html += "            <span class=\"forgot\"> <a href=\"" + Session["ApplicationVirtualPath"] + "login2/recover/\">" + MessageResource.GetMessage("login_forgot") + "</a> </span>";
                html += "            <button tabindex=\"4\" id=\"submitBtn\" class=\"action button floatright\">" + MessageResource.GetMessage("login_log") + "</button>";
                html += "        </li>";
                html += "    </ul>     ";

                html += "</div></form>";
                holderContent.Controls.Add(new LiteralControl(html));
            }
        }
Esempio n. 40
0
 public ReturnValue AddUser(LoginUser model)
 {
     BLL_LoginUser bll = new BLL_LoginUser();
     return bll.AddUpdate(model);
 }
Esempio n. 41
0
        private bool PerformLogin(LoginEventArgs args)
        {
            using (var jsonClient = new JsonServiceClient(BaseUrl))
            {
                //jsonClient.SetCredentials("morten", "pass");
                jsonClient.HttpMethod = "POST";

                var login = new LoginUser
                                {
                                    Username = args.Username,
                                    Password = args.Password,
                                };
                var loginResponse = jsonClient.Send<LoginUserResponse>(login);
                if (loginResponse.Successful)
                {
                    _loginScreen.Enabled = false;
                    _loginScreen.Visible = false;
                }
                //jsonClient.AlwaysSendBasicAuthHeader = true;
                //jsonClient.SendOneWay(move);
            }
            return true;
        }
Esempio n. 42
0
 /// <summary>
 /// 游客登录游戏
 /// </summary>
 /// <returns></returns>
 public abstract LoginResult Guest(LoginUser guest);
Esempio n. 43
0
 public void Handle(LoginUser command, Action<User> callback)
 {
     Client.LoginCompleted += (sender, args) => callback(args.Result);
     Client.LoginAsync(command.Login, command.Password);
 }
 public void Sldier_Tick(object sender, EventArgs e)
 {
     if (count < (Slider.Items.Count - 1))
     {
         count++;
         Slider.SelectedIndex = count;
     }
     else
     {
         DatabaseAndQueries.SessionFactory.DatabaseType = DatabaseAndQueries.DBTYPE.SqlLite.ToString();
         DatabaseAndQueries.SessionFactory.FilePath     = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\InventoryDBA\CTE_Data.db";
         DatabaseAndQueries.SessionFactory.AssemblyName = System.Reflection.Assembly.GetExecutingAssembly().ToString();
         Log.Info("Before: call copy database in LodingWindow");
         CopyDataBase();
         Log.Info("After: call copy database,successfully in LodingWindow");
         Log.Info("Before: to get list of setting variable from DB in LoadingWindow");
         IList <Setting> _Sp = Queries.GetAllByCondition <Setting>(x => x.Id == 1);
         Log.Info("after: to get list of setting variable from DB in LoadingWindow");
         var rdiction  = new ResourceDictionary();
         var rdiction1 = new ResourceDictionary();
         if (_Sp == null)
         {
             Setting _setting = new Setting();
             _setting.Accent = "Blue";
             _setting.Theme  = "Basedark";
             Queries.Add <Setting>(_setting);
             rdiction.Source = new Uri(string.Format("pack://application:,,,/MahApps.Metro;component/Styles/Accents/{0}.xaml", _setting.Accent));
             Application.Current.Resources.MergedDictionaries.Add(rdiction);
             rdiction1.Source = new Uri(string.Format("pack://application:,,,/MahApps.Metro;component/Styles/Accents/{0}.xaml", _setting.Theme));
             Log.Info("After: to get list of setting variable from DB, Successfully in LoadingWindow");
         }
         else
         {
             Log.Info("Before: to get list of setting variable from DB in LoadingWindow");
             Inventory.Model.Setting _S = _Sp.First();//DatabaseAndQueries.Queries.GetDataByCondition<Inventory.Model.Setting>(x => x.Id == 1);
             Log.Info("After: to get list of setting variable from DB, Successfully in LoadingWindow");
             rdiction.Source = new Uri(string.Format("pack://application:,,,/MahApps.Metro;component/Styles/Accents/{0}.xaml", _S.Accent));
             Application.Current.Resources.MergedDictionaries.Add(rdiction);
             rdiction1.Source = new Uri(string.Format("pack://application:,,,/MahApps.Metro;component/Styles/Accents/{0}.xaml", _S.Theme));
             Log.Info("After: to get list of setting variable from DB, Successfully in LoadingWindow");
         }
         List <LoginUser> _lst = Queries.GetAllData <LoginUser>();
         if (_lst.Count == 0)
         {
             new MasterPassword().Show();
         }
         else
         {
             LoginUser _lu = _lst.First <LoginUser>();
             if (_lu.Trial.Date <= DateTime.Now.Date)
             {
                 new TrialExpireWindow().Show();           // send to expire window.
                 Log.Info("After: To show trail Expire window, in LoadingWindow");
             }
             else
             {
                 Application.Current.Resources.MergedDictionaries.Add(rdiction);
                 Application.Current.Resources.MergedDictionaries.Add(rdiction1);
                 new Login().Show();
             }
         }
         newslider.Stop();
         count = 0;
         this.Close();
     }
 }
Esempio n. 45
0
 public static Model.Student existUser(LoginUser lu)
 {
     return(student.existUser(lu));
 }
Esempio n. 46
0
        public ActionResult EditUser_SubmitData_Api(string userName, string truename, int departmentId, List <int> roleIds, LoginUser userInfo)
        {
            var result = new AjaxResult("提交成功!");

            if (userName.IsNullOrEmpty())
            {
                result.Result = false;

                result.Message = "请填写用户名";

                return(AjaxJson(result));
            }

            #region 小组
            var departmentUser = _unitOfWork.DepartmentUserRepository.GetBy(m => m.UserName == userName && (m.CityID == userInfo.NowCityId || m.CityID == 0) && (m.FxtCompanyID == userInfo.FxtCompanyId || m.FxtCompanyID == 0));

            if (departmentUser == null)
            {
                var department = _unitOfWork.DepartmentRepository.GetById(departmentId);//必须找到小组

                departmentUser = _unitOfWork.DepartmentUserRepository.Insert(new DepartmentUser()
                {
                    CityID       = department.FK_CityId,
                    CreateDate   = DateTime.Now,
                    DepartmentID = departmentId,
                    FxtCompanyID = department.Fk_CompanyId,
                    UserName     = userName
                });
            }
            else
            {
                departmentUser.DepartmentID = departmentId;
            }
            #endregion

            #region 角色
            List <string> roleNames = new List <string>();

            _unitOfWork.SysRoleUserRepository.Delete(m => m.UserName == userName && (m.CityID == userInfo.NowCityId || m.CityID == 0) && (m.FxtCompanyID == userInfo.FxtCompanyId || m.FxtCompanyID == 0));

            if (roleIds != null && roleIds.Count > 0)
            {
                roleIds.ForEach((o) =>
                {
                    var role = _unitOfWork.SysRoleRepository.GetById(o);//必须找到角色

                    _unitOfWork.SysRoleUserRepository.Insert(new SYS_Role_User()
                    {
                        CityID       = role.CityID,
                        FxtCompanyID = role.FxtCompanyID,
                        RoleID       = o,
                        TrueName     = truename,
                        UserName     = userName
                    });

                    roleNames.Add(role.RoleName);
                });
            }
            #endregion

            _unitOfWork.Commit();

            result.Data = new { username = userName, truename = truename, departmentname = departmentUser.Department.DepartmentName, rolename = string.Join(",", roleNames) };

            return(AjaxJson(result));
        }
Esempio n. 47
0
        public IEnumerable<IResult> DoLogin()
        {
            ShowScreens = false;
            Error = null;

            if (Login == null) yield break;

            var loginUser = new LoginUser() { Login = Login.Name, Password = Password }.AsResult();
            yield return loginUser;
            if (loginUser.Response == null)
            {
                Error = "Invalid password";
            }
            else
            {
                var getScreens = new GetScreensForUser() { Permissions = loginUser.Response.Type }.AsResult();
                yield return getScreens;

                Screens.Clear();
                foreach (var screen in getScreens.Response)
                {
                    Screens.Add(screen);
                }
                ShowScreens = true;
            }
        }
Esempio n. 48
0
        public ActionResult GetBuildingList_Api(string buildingName, int projectId, string functionCodes, int pageIndex, int pageSize, int isGetCount, LoginUser loginUserInfo)
        {
            IList <CAS.Entity.DBEntity.DATBuilding> list = DataCenterBuildingApi.GetBuilding(buildingName, loginUserInfo.NowCityId, projectId, pageIndex, pageSize, loginUserInfo.UserName, loginUserInfo.SignName, loginUserInfo.AppList);
            string json  = "{{\"Count\":{0},\"List\":{1}}}";
            int    count = list.Count;

            json = string.Format(json, count, (list as List <CAS.Entity.DBEntity.DATBuilding>).ToJSONjss());
            return(Content(""));
        }
Esempio n. 49
0
    // 100. login
    public LoginUser Login(string loginid, string password)
    {
        LoginUser loginUser = new LoginUser();
            DataTable dt = new DataTable();

            using (SqlConnection conn = new SqlConnection(connStr))
            {
                string sql = "SELECT login_user_pk, account_fk, loginid, first_name, last_name, email, phone, is_sys_admin, a.is_client FROM LOGIN_USER";
                sql += " INNER JOIN Account a";
                sql += " ON LOGIN_USER.account_fk = a.account_pk";
                sql += " WHERE loginid = @loginid AND password = @password";
                SqlCommand cmd = new SqlCommand(sql, conn);
                cmd.CommandType = CommandType.Text;
                cmd.Parameters.Add(new SqlParameter("@loginid", loginid));
                cmd.Parameters.Add(new SqlParameter("@password", password));
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                try
                {
                    da.Fill(dt);
                    if ((dt != null) && (dt.Rows.Count > 0))
                    {
                        loginUser = new LoginUser();
                        loginUser.pk = (int)dt.Rows[0][0];
                        loginUser.account = (int)dt.Rows[0][1];
                        loginUser.loginid = (string)dt.Rows[0][2];
                        loginUser.firstName = (string)dt.Rows[0][3];
                        loginUser.lastName = (string)dt.Rows[0][4];
                        loginUser.email = (string)dt.Rows[0][5];
                        loginUser.phone = (string)dt.Rows[0][6];
                        loginUser.is_sys_admin = (string)dt.Rows[0][7].ToString().Trim().ToLower() == "y" ? true : false;
                        loginUser.is_client = (string)dt.Rows[0][8].ToString().Trim().ToLower() == "y" ? true : false;
                        loginUser.is_accountant = loginUser.is_client ? false : true;
                        HttpContext.Current.Session["LoginUser"] = loginUser;
                    }
                    else
                    {
                        loginUser.pk = 0;
                        loginUser.firstName = "Could not authenticate user";
                    }
                }
                catch (Exception ex)
                {
                    loginUser.pk = 0;
                    loginUser.firstName = ex.ToString();
                }
                finally
                {
                    conn.Close();
                }
            }
            return loginUser;
    }
Esempio n. 50
0
        public ActionResult Add(Project project, string developersCompany, string managerCompany, LoginUser loginUserInfo)
        {
            AjaxResult result = new AjaxResult("新增任务成功!!!");

            //检查是否已存在任务
            Project exists = _unitOfWork.AllotFlowService.ExistsAllot(project);

            if (exists == null)
            {
                var ret = _unitOfWork.AllotFlowService.AddAllot(project, developersCompany, managerCompany, " 从调度中心 <span class=\"red\">创建任务</span>",

                                                                loginUserInfo.NowCityId, loginUserInfo.FxtCompanyId, loginUserInfo.UserName, loginUserInfo.TrueName, SYSCodeManager.STATECODE_1);

                if (ret.AllotState == 0)
                {
                    result.Result = false;

                    result.Message = "新增任务失败。";
                }
                else if (ret.AllotState == -1)
                {
                    result.Result = false;

                    result.Message = "失败,未设置模板。";
                }
            }
            else
            {
                result.Result = false;

                result.Message = "任务重复";
            }

            return(AjaxJson(result));
        }
Esempio n. 51
0
    private void initAuthData()
    {
        LoginUser user = new LoginUser();
        LoginRole role = new LoginRole();
        user.UserId = "admin";
        user.Password = EncryptUtil.GetMD5(PASS_WORD);
        user.Name = "系統管理者";
        user.IsEnable = true;
        user.Email = "*****@*****.**";
        myService.DaoInsert(user);

        role.RoleName = "系統管理者";
        myService.DaoInsert(role);

        List<LoginUser> userList = new List<LoginUser>();
        List<LoginRole> roleList = new List<LoginRole>();
        roleList.Add(role);
        user.BelongRoles = new List<LoginRole>();

        role.BelongUsers = userList;
        user.BelongRoles = roleList;
        myService.DaoUpdate(role);
        myService.DaoUpdate(user);

        lblStatus.Text = "初始化資料成功!!";
    }
Esempio n. 52
0
        public ActionResult GetList_Api(string projectName, int areaId, int subAreaId, string functionCodes, int pageIndex, int pageSize, int isGetCount, LoginUser loginUserInfo)
        {
            var result = new AjaxResult("");

            var list = DataCenterProjectApi.GetProject(projectName, loginUserInfo.NowCityId, areaId, subAreaId, pageIndex, pageSize, loginUserInfo.UserName, loginUserInfo.SignName, loginUserInfo.AppList).ToList();

            list.ForEach((o) =>
            {
                var project = _unitOfWork.ProjectRepository.GetBy(m => m.FxtCompanyId == o.fxtcompanyid && m.CityID == o.cityid && m.FxtProjectId == o.projectid && m.Status != SYSCodeManager.STATECODE_10 && m.Valid == 1);

                if (project != null)
                {
                    o.valid = 0;
                }
            });

            result.Data = list;

            return(Json(result));
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            string    loginIdentifer = Request["loginIdentifer"] ?? "";
            LoginUser loginUser      = GlobalAppModule.GetLoginUser(loginIdentifer);

            if (loginUser == null)
            {
                this.Response.Write("<script>alert('未登录')</script>");
                this.Response.End();
            }
            if (loginUser.LoginTimeout)
            {
                this.Response.Write("<script>alert('登录超时')</script>");
                this.Response.End();
            }
            loginUser.LastOperateTime = DateTime.Now;
            CommonUtil.WaitMainLibInit();

            string t = Request["t"] ?? "";

            if (t != "1" && t != "2")
            {
                this.Response.Write("<script>alert('参数非法')</script>");
                this.Response.End();
            }

            string str = "";

            try
            {
                DateTime UploadTime   = DateTime.Parse(Request["UploadTime"].ToString());
                string   UserName     = Request["UserName"] ?? "";
                string   deviceFullNo = Request["deviceFullNo"] ?? "";
                string   FileName     = Request["FileName"] ?? "";

                string rootpath = "";
                string filename = "";
                string path     = "";
                if (t == "1")
                {
                    rootpath = "UploadFiles/Device/";
                    path     = Server.MapPath("~/" + rootpath + deviceFullNo + "/");
                    filename = FileName;
                }
                else if (t == "2")
                {
                    rootpath = "UploadFiles/User/";
                    path     = Server.MapPath("~/" + rootpath + UserName + "/" + UploadTime.ToString("yyyyMMddHHmmss") + "_" + deviceFullNo + "_");
                    filename = FileName;
                }

                string fullfilename = path + filename;
                string method       = Request["Method"] ?? "";
                switch (method)
                {
                case "DownloadFile":
                    if (filename != "")
                    {
                        System.IO.FileInfo file = new System.IO.FileInfo(fullfilename);
                        if (file.Exists)
                        {
                            this.Response.ContentType = "application/ms-download";
                            this.Response.Clear();
                            this.Response.AddHeader("Content-Type", "application/octet-stream");
                            this.Response.Charset = "utf-8";
                            this.Response.AddHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(filename));
                            this.Response.AddHeader("Content-Length", file.Length.ToString());
                            this.Response.WriteFile(file.FullName);
                            this.Response.Flush();
                            this.Response.Clear();
                            this.Response.End();
                        }
                        else
                        {
                            str = "文件不存在,无法下载!";
                        }
                    }
                    else
                    {
                        str = "非法请求,无法下载!";
                    }
                    break;

                case "DeleteFile":
                    if (filename != "")
                    {
                        System.IO.FileInfo file = new System.IO.FileInfo(fullfilename);
                        if (file.Exists)
                        {
                            file.Delete();
                            str = "删除成功!";
                        }
                        else
                        {
                            str = "文件不存在,无法删除!";
                        }
                    }
                    else
                    {
                        str = "非法请求,无法删除!";
                    }
                    break;

                default:
                    str = "缺少参数!";
                    break;
                }
            }
            catch (Exception ex)
            {
                str = "错误!" + ex.Message;
            }

            this.Response.Write("<script>alert('" + str + "');</script>");
            this.Response.End();
        }
Esempio n. 54
0
 public Result <LoginUser> Login(LoginUser loginUser)
 {
     userDataAccess.Login();
     return(new Result <LoginUser>());
 }
Esempio n. 55
0
 public void Update(LoginUser item)
 {
     string UpdSql = @"Update LoginUser SET UserId = @UserId, Password = @Password, Name = @Name, "
            + "Description = @Description, Status = @Status WHERE Id = @Id";
     MySqlParameter[] parameter = new MySqlParameter[]
     {
         new MySqlParameter("@UserId",item.UserId),
         new MySqlParameter("@Password",item.Password),
         new MySqlParameter("@Name",item.Name),
         new MySqlParameter("@Description",item.Description),
         new MySqlParameter("@Status",item.Status),
         new MySqlParameter("@Id",item.Id)
     };
     dbHelper.ExecuteNonQuery(UpdSql, parameter);
 }
Esempio n. 56
0
        /// <summary>
        /// 将当前登录用户信息和Cookie信息进行同步
        /// </summary>
        protected void LoadCookiedUser()
        {
            // 无论何时,均先设置好本页面的Cookie结构
            InitCookieStructure();

            LogPart.ActiveViewIndex  = 0;
            FuncMenu.ActiveViewIndex = -1;

            // 存在已登录对象的情况,通过对象重设Cookies
            if (CurrentLoginUser != null)
            {
                LogPart.ActiveViewIndex         = 1;
                Request.Cookies["UserID"].Value = CurrentLoginUser.userId.ToString();
                if (CurrentLoginUser.type == 1)
                {
                    FuncMenu.ActiveViewIndex = 1;
                    Request.Cookies["LoginStudent"].Value = CurrentLoginUser.alias;
                }
                else
                {
                    FuncMenu.ActiveViewIndex = 0;
                    Request.Cookies["LoginManager"].Value = CurrentLoginUser.alias;
                }
                Request.Cookies["ExperimentID"].Value = CurrentLoginUser.currentExperimentId;
                Request.Cookies["TaskID"].Value       = CurrentLoginUser.currentTaskId;
                Request.Cookies["SessionID"].Value    = CurrentLoginUser.currentSessionId;
                Request.Cookies["CompileID"].Value    = CurrentLoginUser.currentCompileId;
                Request.Cookies["UploadID"].Value     = CurrentLoginUser.currentUploadId;
                Request.Cookies["RunID"].Value        = CurrentLoginUser.currentRunId;
                Request.Cookies["CodeURI"].Value      = CurrentLoginUser.currentCodeUri;
                return;
            }

            // 已登录对象已经不存在,但反过来若Cookie还在,就尝试自动登录重建登录对象,除非Cookie也没有
            string currentUserID = Request.Cookies["UserID"].Value;

            if (currentUserID == null || currentUserID.Equals(String.Empty))
            {
                return;
            }

            int    userType = 0;
            string cmdString;
            string currentAlias = Request.Cookies["LoginStudent"].Value;

            if (currentAlias != null && !currentAlias.Equals(string.Empty))
            {
                cmdString = "SELECT DISTINCT [alias], [password], [id_student], [name], [gender], [grade], [belong], [phone], [email], [record_status] FROM[bhStudent] WHERE([alias] = @alias)";
                userType  = 1;
            }
            else
            {
                currentAlias = Request.Cookies["LoginManager"].Value;
                if (currentAlias != null && !currentAlias.Equals(string.Empty))
                {
                    cmdString = "SELECT DISTINCT [id_manager], [alias], [password], [name], [type], [phone], [email] FROM [bhManager] WHERE ([alias] = @alias)";
                }
                else
                {
                    return;
                }
            }

            // 获取数据库读取连接字符串并建立连接
            string  sConnString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            DataSet outDS       = new DataSet();

            // 准备查询命令和接受查询结果的数据工具集,进行查询,结果通过da格式化填充到ds中
            using (SqlConnection sSqlConn = new SqlConnection(sConnString))
            {
                SqlCommand     cmd = sSqlConn.CreateCommand();
                SqlDataAdapter da  = new SqlDataAdapter(cmd);
                try
                {
                    sSqlConn.Open();
                    cmd.CommandText = cmdString;
                    cmd.Parameters.Clear();
                    cmd.Parameters.Add("@alias", SqlDbType.VarChar, 50).Value = currentAlias;
                    da.FillSchema(outDS, SchemaType.Source, "BHUSER");
                    da.Fill(outDS, "BHUSER");
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    sSqlConn.Close();
                }
            }

            // 没有查到匹配Cookie的用户也不能自动登录
            if (outDS.Tables["BHUSER"].Rows.Count <= 0)
            {
                return;
            }

            // 创建登录用户对象,并使用ds来初始化所有数据
            LoginUser loginUser = new LoginUser();

            loginUser.type = userType;
            // loginUser.alias = outDS.Tables["BHUSER"].Rows[0]["alias"].ToString(); 可以不必反写一次
            loginUser.name = outDS.Tables["BHUSER"].Rows[0]["name"].ToString();

            if (outDS.Tables["BHUSER"].Columns.Contains("gender"))
            {
                loginUser.gender = (short)outDS.Tables["BHUSER"].Rows[0]["gender"];
            }
            if (outDS.Tables["BHUSER"].Columns.Contains("grade"))
            {
                loginUser.grade = outDS.Tables["BHUSER"].Rows[0]["grade"].ToString();
            }
            if (outDS.Tables["BHUSER"].Columns.Contains("belong"))
            {
                loginUser.belong = outDS.Tables["BHUSER"].Rows[0]["belong"].ToString();
            }

            loginUser.phone    = outDS.Tables["BHUSER"].Rows[0]["phone"].ToString();
            loginUser.email    = outDS.Tables["BHUSER"].Rows[0]["email"].ToString();
            loginUser.password = outDS.Tables["BHUSER"].Rows[0]["password"].ToString();

            // 尝试从Cookie中恢复当前登录对象的实验信息
            //loginUser.currentExperimentId = Request.Cookies["ExperimentID"].Value;
            //loginUser.currentTaskId = Request.Cookies["TaskID"].Value;
            //loginUser.currentSessionId = Request.Cookies["SessionID"].Value;
            //loginUser.currentCompileId = Request.Cookies["CompileID"].Value;
            //loginUser.currentUploadId = Request.Cookies["UploadID"].Value;
            //loginUser.currentCodeUri = Request.Cookies["CodeURI"].Value;
            loginUser.currentExperimentId = "";
            loginUser.currentTaskId       = "";
            loginUser.currentSessionId    = "";
            loginUser.currentCompileId    = "";
            loginUser.currentUploadId     = "";
            loginUser.currentRunId        = "";
            loginUser.currentCodeUri      = "";

            loginUser.currentState   = EnvironmentState.NotReady;
            loginUser.compileSuccess = false;
            loginUser.uploadSuccess  = false;
            loginUser.playSuccess    = false;

            LogPart.ActiveViewIndex  = 1;
            FuncMenu.ActiveViewIndex = userType;

            // 将创建好的User对象交付Master框架完成最后创建。该过程将会把此用户对象写入Session
            ((SiteMaster)Master).CreateCurrentLoginUser(loginUser);
        }
Esempio n. 57
0
 /// <summary>
 /// 作者:Vincen
 /// 时间:2014.04.25
 /// 描述:更新登录用户缓存
 /// </summary>
 /// <param name="loginUser"></param>
 public static void UpdateLoginUserCache(LoginUser loginUser)
 {
     if (loginUser != null)
     {
         Icache.Set(string.Format("{0}{1}", Kword, loginUser.UserId), loginUser, 180 * 24 * 60);
     }
 }
Esempio n. 58
0
 public void ResetLoginUser()
 {
     currentLoginUser = null;
     Session.Remove("user");
 }
Esempio n. 59
0
 /// <summary>
 /// 作者:Vincen
 /// 时间:2014.04.25
 /// 描述:设置登录用户缓存
 /// </summary>
 /// <param name="loginUser"></param>
 public static void SetLoginUserCache(LoginUser loginUser)
 {
     if (null == loginUser) return;
     if (!Icache.IsSet(string.Format("{0}{1}", Kword, loginUser.UserId)))
     {
         Icache.Set(string.Format("{0}{1}", Kword, loginUser.UserId), loginUser, 180 * 24 * 60);
     }
 }
Esempio n. 60
0
        public LongFileReceiveProcess(AsynchSocketServiceBaseFrame InAsynchSocketServiceBaseFrame, SocketServiceReadWriteChannel InputSocketServiceReadWriteChannel, byte[] RecieveFileByteUnit, uint MyRecieveCount)
        {
            if (LoopReadCount == 0)
            {
                string RecieveMessageLenghtStr = string.Format("{0:X2}", RecieveFileByteUnit[21]);
                RecieveMessageLenghtStr = RecieveMessageLenghtStr + string.Format("{0:X2}", RecieveFileByteUnit[20]);
                RecieveMessageLenghtStr = RecieveMessageLenghtStr + string.Format("{0:X2}", RecieveFileByteUnit[19]);
                RecieveMessageLenghtStr = RecieveMessageLenghtStr + string.Format("{0:X2}", RecieveFileByteUnit[18]);

                UInt32 RecieveMessageLenght = Convert.ToUInt32(RecieveMessageLenghtStr, 16);
                UInt32 RecieveFileLenght    = RecieveMessageLenght - 22;

                LoopReadCount++;

                StaticRecieveFileBytes = new byte[RecieveFileLenght];
                //byte[] RecieveFileFirstByteBuffer = new byte[MyRecieveCount-22];

                LoopReadFlag  = (uint)(RecieveMessageLenght - MyRecieveCount);
                NextSaveIndex = MyRecieveCount - 22;

                //--填充所接收的文件字节----
                for (int i = 0; i < NextSaveIndex; i++)
                {
                    StaticRecieveFileBytes[0] = RecieveFileByteUnit[22 + i];
                }

                //AddLongFilePackage(RecieveFileByteUnit, MyRecieveCount);

                //---1.找智能锁本身通道的路由表记录-------------------------------------
                LockServerLib.FindLockChannel MyBindedLockChannel = new LockServerLib.FindLockChannel(InputSocketServiceReadWriteChannel);
                LoginUser MyLoginUser = InAsynchSocketServiceBaseFrame.MyManagerSocketLoginUser.MyLoginUserList.Find(new Predicate <LoginUser>(MyBindedLockChannel.BindedLockChannelForSocket));
                MyLockIDStr = MyLoginUser.LockID;
            }
            else
            {
                this.AddLongFilePackage(RecieveFileByteUnit, MyRecieveCount);
            }
            //MyMobileIDStr = MyLoginUser.MobileID;

            //AddLongFilePackage(RecieveFileByteUnit, (int)RecieveFileLenght)

            /*
             * LoopReadFlag = RecieveMessageLenght;
             *
             * if (RecieveMessageLenght <= MyRecieveCount)
             * {
             *
             * StaticRecieveFileBytes = new byte[RecieveFileLenght];
             * AddLongFilePackage(RecieveFileByteUnit, MyRecieveCount);
             * StartUpLoadFileSave();
             *
             * }
             * else
             * {
             * LoopReadCount++;
             * StaticRecieveFileBytes = new byte[RecieveFileLenght];
             * AddLongFilePackage(RecieveFileByteUnit, MyRecieveCount);
             *
             * }
             */
        }