Example #1
0
 public void Setup()
 {
     if (rsaServer == null)
     {
         rsaServer = new RSACryptoService(java_privatekey, java_publickey);
     }
     session_state = Session.SESSION_SIGN;
 }
Example #2
0
        public ActionResult SaveUser(RUser user)
        {
            ReturnObject ro    = null;
            var          admin = UserUtils.GetUser();

            if (!UserUtils.GetUser().IsAdmin)
            {
                ro = new ReturnObject("该用户无权限!");
            }
            else
            {
                try
                {
                    using (TransactionScope trans = new TransactionScope())
                    {
                        var    u        = this.dbContext.User.Where(p => p.ID == user.ID).FirstOrDefault();
                        string password = new RSACryptoService(SystemUtility.Config.RSA.PrivateKey.ToString()).Decrypt(user.Password);

                        if (u == null)
                        {
                            u = new User()
                            {
                                ID             = Guid.NewGuid().ToString(),
                                UserName       = user.UserName,
                                Password       = password,
                                LastModifyUser = admin.ID,
                                LastModifyTime = DateTime.Now,
                                CreateUser     = admin.ID,
                                CreateTime     = DateTime.Now
                            };
                            this.dbContext.User.Add(u);
                        }
                        else
                        {
                            if (this.dbContext.User.Where(p => p.ID != user.ID && p.UserName == user.UserName).FirstOrDefault() != null)
                            {
                                throw new Exception("用户重名,请修改用户名!");
                            }
                            else
                            {
                                u.UserName       = user.UserName;
                                u.Password       = password;
                                u.LastModifyTime = DateTime.Now;
                                u.LastModifyUser = admin.ID;
                            }
                        }
                        this.dbContext.SaveChanges();
                        trans.Complete();
                    }
                    ro = new ReturnObject();
                }
                catch (Exception ex)
                {
                    ro = new ReturnObject(ex.Message);
                }
            }
            return(Json(ro));
        }
Example #3
0
        public static User ValidateUser(string UserName, string Password)
        {
            string admUserName = SystemUtility.Config.User.UserName.ToString();
            string admPassword = SystemUtility.Config.User.Password;

            //RSA解密
            Password = new RSACryptoService(SystemUtility.Config.RSA.PrivateKey.ToString()).Decrypt(Password);
            if (admUserName == UserName && admPassword == Password)
            {
                return(UserUtils.GetAdmin());
            }
            return(SystemUtility.EFDbContext.User.Where(p => p.UserName == UserName && p.Password == Password).FirstOrDefault());
        }
        private async void loading()
        {
            try
            {
                await Task.Delay(500);

                if (!CommonHelper.CheckNetworkAvailable(this))
                {
                    throw new Exception("请打开网络连接");
                }
                //1.检查是否已有缓存登录令牌
                CommonHelper.token = CommonHelper.ReadTextFile <AccessToken>("token.txt", this);
                //2.检查是否已有缓存用户信息
                CommonHelper.userInfo = CommonHelper.ReadTextFile <UserInfo>("userInfo.txt", this);
                if (CommonHelper.token == null || CommonHelper.token.CheckTokenIsOverdue())
                {
                    OAuthClient client = new OAuthClient();
                    if (CommonHelper.token != null && CommonHelper.userInfo != null)
                    {
                        RSACryptoService rsaService = new RSACryptoService(CNBlogAPI.Service.UserService.publicKey);
                        CommonHelper.token = await CNBlogAPI.Service
                                             .UserService
                                             .Login(rsaService.Encrypt(CommonHelper.userInfo.UName), (rsaService.Encrypt(CommonHelper.userInfo.Pwd)));
                    }
                    else
                    {
                        CommonHelper.token = await client.GetAccessToken();
                    }
                    //保存令牌供下次使用
                    CommonHelper.SaveTextFile("token.txt", this, JsonConvert.SerializeObject(CommonHelper.token));
                }
                StartActivity(new Intent(this, typeof(MainActivity)));
            }
            catch (Exception ex)
            {
                string path     = Android.OS.Environment.ExternalStorageDirectory.Path;
                string fileName = "/error.txt";
                using (var streamWriter = new StreamWriter(path + fileName, false))
                {
                    streamWriter.WriteLine(ex.InnerException + "," + ex.Message + "," + ex.StackTrace + "," + ex.Source + "," + ex.Data);
                }
                Msg.AppMsg.MakeText(this, ex.Message, Msg.AppMsg.STYLE_ALERT).Show();
                await Task.Delay(1000);

                Android.Util.Log.Debug("error:", ex.Message);
                Finish();
            }
        }
        public void TestMethod1()
        {
            var publicKey = @"
                            MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC7PyjMEuniN6BPn8oqzIZ6AO1N
                            jSTO9R3adCCIwKfKIEoWXXM+tHDpktdPKSaAsWJPTNAGvEvtxOfzXib/EMXKqD0e
                            Uy5MatfpRjRdf1hJVimmfrb09Qx2j7CsKLy7nD23m4xubdYBwvkjMwt/L3JxB5D6
                            qryW1wei/j1c+/OCxQIDAQAB
                            ";


            var privateKey = @"MIICXQIBAAKBgQC7PyjMEuniN6BPn8oqzIZ6AO1NjSTO9R3adCCIwKfKIEoWXXM+
tHDpktdPKSaAsWJPTNAGvEvtxOfzXib/EMXKqD0eUy5MatfpRjRdf1hJVimmfrb0
9Qx2j7CsKLy7nD23m4xubdYBwvkjMwt/L3JxB5D6qryW1wei/j1c+/OCxQIDAQAB
AoGAT7vGYJgRNf4f6qgNS4pKHTu10RcwPFyOOM7IZ9M5380+HyXuBB6MEjowKwpH
1fcy+LepwaR+5KG7b5uBGY4H2ticMtdysBd9gLwnY4Eh4j7LCWE54HvELpeWXkWp
FQdb/NQhcqMAGwYsTnRPdBqkrUmJBTYqEGkIlqCQ5vUJOCECQQDhe0KGmbq1RWp6
TDvgpA2dUmlt2fdP8oNW8O7MvbDaQRduoZnVRTPYCDKfzFqpNXL1hAYgth1N0vzD
nv3VoLcpAkEA1JcY+rLv5js1g5Luv8LaI5/3uOg0CW7fmh/LfGuz8k/OxASN+cAO
UjPHrxtc5xn1zat4/bnV5GEdlOp/DhquPQJBAIV2Fsdi4M+AueiPjPWHRQO0jvDV
jfwFOFZSn5YSRUa6NmtmPY6tumUJXSWWqKb1GwlVTuc3xBqXYsNLLUWwLhkCQQDJ
UJCiD0LohhdGEqUuSKnj5H9kxddJO4pZXFSI7UEJbJQDwcBkyn+FTm2BH+tZGZdQ
fVnlA89OJr0poOpSg+eNAkAKY85SR9KASaTiDBoPpJ8N805XEhd0Kq+ghzSThxL3
fVtKUQLiCh7Yd8oMd/G5S3xWJHUXSioATT8uPRH2bOb/";


            var launchInfo = new LaunchInfo
            {
                ComputerName    = MachineInfo.Instance.GetComputerName(),
                CPUSerialNumber = MachineInfo.Instance.GetCPUSerialNumber(),
                MACAddress      = MachineInfo.Instance.GetMacAddress(),
                Name            = "测试",
                ProductKey      = "G5S3xWJHUXSioATT8uPRH2bOb",
                SystemType      = MachineInfo.Instance.GetSystemType(),
                ExpirationDate  = DateTime.Now.AddDays(30)
            };

            var serializedText = JsonConvert.SerializeObject(launchInfo);


            var privateCryto = new RSACryptoService(privateKey);
            var publickCryto = new RSACryptoService(null, publicKey);

            var encryptedText = publickCryto.Encrypt(serializedText);

            var decryptedText = privateCryto.Decrypt(encryptedText);

            Assert.IsTrue(serializedText == decryptedText);
        }
Example #6
0
        private void userlogin(HttpContext context)
        {
            loginmsg logs    = new loginmsg();
            string   account = context.Request["userName"];
            string   rePwd   = context.Request["pwd"];
            string   pwd     = RSACryptoService.DecryptByAES(rePwd);
            User     user    = loginBll.getPwdByUserId(account);
            string   userPwd = rsa.Decrypt(user.Pwd);
            Result   row     = userBll.isUser(account);

            if (row == Result.记录不存在)
            {
                logs.msg = "该账号不存在";
                string json = JsonHelper.JsonSerializerBySingleData(logs);
                context.Response.Write(json);
                context.Response.End();
            }
            else
            {
                if (user.UserId.ToString() == account && userPwd == pwd)
                {
                    context.Response.Cookies[FormsAuthentication.FormsCookieName].Value = null;
                    FormsAuthenticationTicket Ticket = new FormsAuthenticationTicket(1, account, DateTime.Now, DateTime.Now.AddDays(1), true, "staff"); //建立身份验证票对象
                    string     HashTicket            = FormsAuthentication.Encrypt(Ticket);                                                             //加密序列化验证票为字符串
                    HttpCookie UserCookie            = new HttpCookie(FormsAuthentication.FormsCookieName, HashTicket);                                 //生成Cookie
                    context.Response.Cookies.Add(UserCookie);                                                                                           //票据写入Cookie
                    isLogined(account, context);

                    logs.sid      = RSACryptoService.EncryptByAES(context.Session.SessionID);
                    logs.msg      = "登录成功";
                    logs.customID = user.UserId.ToString();
                    string json = JsonHelper.JsonSerializerBySingleData(logs);
                    context.Response.Write(json);
                    context.Response.End();
                }
                else
                {
                    logs.msg = "密码错误";
                    string json = JsonHelper.JsonSerializerBySingleData(logs);
                    context.Response.Write(json);
                    context.Response.End();
                }
            }
        }
Example #7
0
        private void _DgvContextMenu_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            this.dgvContextMenu.Hide();
            if (this.dgvLicenseView.SelectedRows.Count < 1)
            {
                return;
            }

            var    row         = this.dgvLicenseView.SelectedRows[0];
            var    commandText = e.ClickedItem.Text;
            string dataPropertyName;
            string expressData;

            if (this._commandDictionary.TryGetValue(commandText, out dataPropertyName))
            {
                expressData = row.Cells[dataPropertyName].Value.ToString();
            }
            else
            {
                if (this._delegateDictionary.ContainsKey(e.ClickedItem.Text))
                {
                    this._delegateDictionary[e.ClickedItem.Text](row.Cells["Id"].Value.ToString());
                    MessageBox.Show(@"删除成功", @"提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    ManagerFormService.BindDataGridView(this.dgvLicenseView);
                    return;
                }

                var publicKey   = row.Cells["PublicKey"].Value.ToString();
                var licenseCode = row.Cells["LicenseCode"].Value.ToString();
                expressData = RSACryptoService.DecryptString(licenseCode, publicKey);
            }

            try
            {
                Clipboard.SetText(expressData);
                MessageBox.Show(LicenseManagerResource.ManagerFormdgvContextMenuPaste);
            }
            catch (ExternalException)
            {
                MessageBox.Show(@"复制到剪贴版失败,请重试。", LicenseManagerResource.ManagerFormGetLicenseEntityAuthenticationTargetWarning, MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
Example #8
0
        /// <summary>
        /// 添加学院管理员
        /// </summary>
        public void insertAdmin()
        {
            string account = Context.Request["account"].ToString();
            string name    = Context.Request["name"].ToString();
            string sex     = Context.Request["sex"].ToString();
            string college = Context.Request["college"].ToString();
            string email   = Context.Request["email"].ToString();
            string phone   = Context.Request["phone"].ToString();

            try
            {
                if (teaBll.selectByColl(Convert.ToInt32(college)))
                {
                    Response.Write("该学院已设置过分院管理员");
                    Response.End();
                }
                else if (teaBll.selectByteaId(account))
                {
                    if (teaBll.GetModel(account).TeaType == 2)
                    {
                        Response.Write("该教师已为分院管理员");
                        Response.End();
                    }
                }
                else if (teaBll.selectByEmail(email))
                {//根据输入的邮箱查找是否已存在
                    Response.Write("此邮箱已存在");
                    Response.End();
                }
                else if (teaBll.selectByPhone(phone))
                {//根据输入的联系电话查找是否已存在
                    Response.Write("此联系电话已存在");
                    Response.End();
                }
                else
                {
                    tea.TeaAccount = account;
                    tea.TeaName    = name;
                    tea.Sex        = sex;
                    coll.ColID     = int.Parse(college);
                    tea.college    = coll;
                    tea.Email      = email;
                    tea.Phone      = phone;
                    RSACryptoService rsa = new RSACryptoService();
                    tea.TeaPwd  = rsa.Encrypt("000000");
                    tea.TeaType = 2;
                    result      = teaBll.Insert(tea);
                    if (result == Result.添加成功)
                    {
                        LogHelper.Info(this.GetType(), admin.TeaAccount + " - " + admin.TeaName + " - 添加分院管理员");
                        Response.Write("添加成功");
                        Response.End();
                    }
                    else
                    {
                        Response.Write("添加失败");
                        Response.End();
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(this.GetType(), ex);
            }
        }
Example #9
0
        protected void Button1_Click(object sender, EventArgs e)
        {
            RegionBll        regionBll = new RegionBll();
            UserBll          userBll   = new UserBll();
            RoleBll          roleBll   = new RoleBll();
            RSACryptoService rsa       = new RSACryptoService();

            string roleName = "微信零售";
            int    row      = roleBll.selectByroleName(roleName);
            int    roleId   = 0;

            if (row <= 0)
            {
                Role role = new Role();
                role.RoleName = roleName;
                Result insert = roleBll.Insert(role);
                if (insert == Result.添加成功)
                {
                    roleId = roleBll.selectByroleName(roleName);
                    string sqlText = "(" + roleId + "," + 14 + ")";
                    Result inserts = roleBll.InsertPer(sqlText, roleId, "添加");
                    if (inserts == Result.添加失败)
                    {
                        Response.Write("添加失败");
                        Response.End();
                    }
                }
            }
            else
            {
                roleId = row;
            }
            DataSet ds    = regionBll.select();
            int     count = ds.Tables[0].Rows.Count;

            if (count > 0 && ds != null)
            {
                for (int i = 0; i < count; i++)
                {
                    string regionId   = ds.Tables[0].Rows[i]["regionId"].ToString();
                    string regionName = ds.Tables[0].Rows[i]["regionName"].ToString();
                    Region region     = new Region();
                    region.RegionId = Convert.ToInt32(regionId);
                    Role role = new Role();
                    role.RoleId = roleId;
                    User user = new User();
                    user.UserId   = regionId + "01";
                    user.UserName = regionName + "微信零售";
                    user.ReginId  = region;
                    user.Pwd      = rsa.Encrypt("000000");
                    user.RoleId   = role;
                    Result rows = userBll.Insert(user);
                    if (rows == Result.添加失败)
                    {
                        Response.Write("添加失败:" + regionId);
                    }
                }
                Response.Write("添加成功");
            }
            else
            {
                Response.Write("未查到任何组织信息");
            }
        }
Example #10
0
        /// <summary>
        /// 获取一对 RAS 公钥与私钥。
        /// </summary>
        /// <returns></returns>
        internal static string[] GeneratorKeys()
        {
            var keys = RSACryptoService.GenerateKeys();

            return(keys);
        }
Example #11
0
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            DataRsp rsp    = new DataRsp();
            string  Action = context.Request.Form["Action"];

            if (Action == "null")
            {
                context.Response.Write(PublicProperty.PublicKey);
            }
            else if (Action == "Login")//登录
            {
                string str = "";
                //解密 RSA
                RSACryptoService rsa = new RSACryptoService(PublicProperty.PrivateKey, PublicProperty.PublicKey);
                try
                {
                    string usernameEncode = context.Request.Form["UserName"];
                    string uname          = Com.Public.SqlEncStr(rsa.Decrypt(usernameEncode));
                    //获取到学校ID,判断该学校是否正常
                    //bool isschcor = false;
                    SchSystem.BLL.SchUserInfo userbll = new SchSystem.BLL.SchUserInfo();
                    SchSystem.BLL.SchInfo     schbll  = new SchSystem.BLL.SchInfo();
                    //if (Com.Public.getKey("issch") == "1")//单学校登录
                    //{
                    //    string appschid = Com.Public.getKey("appschid");
                    //    //判断该学校是否正常
                    //    isschcor = schbll.Exists(int.Parse(appschid), 1);
                    //}
                    //else//统一登录
                    //{
                    //    SchSystem.Model.SchUserInfo usermodel = userbll.GetModelByUname(uname);
                    //    if (usermodel != null && usermodel.UserId > 0)
                    //    {
                    //        isschcor = schbll.Exists(usermodel.SchId, 1);
                    //    }
                    //}
                    //if (!isschcor)
                    //{
                    //    rsp.RspCode = "6";
                    //    rsp.RspTxt = "该学校已经被关闭或者账号不存在,请联系系统管理人员!";
                    //}
                    //else
                    //{
                    string pwdEncode = context.Request.Form["PassWord"];
                    string txtCode   = context.Request.Form["TxtCode"];  //IsCookies
                    //string IsCookies = context.Request.Form["IsCookies"];
                    string txtcode = rsa.Decrypt(txtCode);
                    //string iscookies = rsa.Decrypt(IsCookies);
                    //bool iscook =false;
                    //if (iscookies == "1") iscook = true;
                    if (recode(txtcode, context))
                    {
                        if (!string.IsNullOrEmpty(uname))
                        {
                            string pwd = Com.Public.SqlEncStr(rsa.Decrypt(pwdEncode));
                            Com.Session.userpw = pwd;
                            Com.Session.usertp = "0";
                            string pwdmd5 = Com.Public.StrToMD5(pwd);
                            //查询所登录的用户名和密码是否一致。如果一致,则返回true;否则,返回false。
                            bool result = false;
                            if (Com.Public.getKey("issch") == "1")    //分学校部署,需要在本学校中
                            {
                                result = userbll.Exists("UserName='******' and PassWord='******' and Stat=1 and AccStat=1 and SysType=0 and schid=" + Com.Public.getKey("appschid"));
                            }
                            else    //总平台不允许分学校部署的用户登录,则加上schid所在学校限制
                            {
                                result = userbll.Exists("UserName='******' and PassWord='******' and Stat=1 and AccStat=1 and SysType=0 and schid not in (select schid from SchInfo where IsAlone=1)");
                            }
                            if (result == true)
                            {
                                //用户登录处理函数
                                str = Com.Public.UserLoginDo(uname, false, Com.Public.getKey("appschid"));

                                if (str == "1" && pwd == "123456")
                                {
                                    rsp.RspCode = "2";
                                    rsp.RspTxt  = context.Request.Url.Authority + context.Request.ApplicationPath + "/userpwdedit.aspx";
                                    //str = "2";//默认初始化密码,需要先修改密码
                                }
                                else
                                {
                                    rsp.RspCode = "1";
                                    rsp.RspTxt  = context.Request.Url.Authority + context.Request.ApplicationPath + "/index.aspx";
                                }
                            }
                            else
                            {
                                rsp.RspCode = "3";
                                rsp.RspTxt  = "账号或密码错误,请联系系统管理员!";
                                //str = "3";//账号或密码错误,或者被停用,请联系管理员
                            }
                        }
                        else
                        {
                            rsp.RspCode = "4";
                            rsp.RspTxt  = "用户名不能为空";
                            //str = "4";//用户名不能为空
                        }
                    }
                    else
                    {
                        rsp.RspCode = "5";
                        rsp.RspTxt  = "验证码错误";
                        //str = "5";//验证码错误
                    }
                    //}
                }
                catch (Exception ex)
                {
                    rsp.RspCode = "9";
                    rsp.RspTxt  = ex.Message;
                }
                context.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(rsp));
            }
            else if (Action == "out")//退出
            {
                /*PublicMethod.Clear();*/

                context.Session.Clear();
                context.Session.Abandon();
                context.Response.Clear();
                //清除cookies
                Com.CookieHelper.ClearCookie("uname");
                rsp.RspCode = "success";
                rsp.RspTxt  = "Login.aspx";
                if (Com.Public.getKey("isyssch") == "1")
                {
                    rsp.RspTxt = "LoginYs.aspx";
                }
                context.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(rsp));
            }
        }
Example #12
0
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            string Action = context.Request.Form["Action"];

            if (Action == "null")
            {
                context.Response.Write(PublicProperty.PublicKey);
            }
            else if (Action == "Login")//登录
            {
                string str = "";
                //解密 RSA
                RSACryptoService rsa = new RSACryptoService(PublicProperty.PrivateKey, PublicProperty.PublicKey);
                try
                {
                    string usernameEncode = context.Request.Form["UserName"];
                    string pwdEncode      = context.Request.Form["PassWord"];
                    string txtCode        = context.Request.Form["TxtCode"];//IsCookies
                    //string IsCookies = context.Request.Form["IsCookies"];
                    string txtcode = rsa.Decrypt(txtCode);
                    //string iscookies = rsa.Decrypt(IsCookies);
                    //bool iscook =false;
                    //if (iscookies == "1") iscook = true;
                    if (recode(txtcode, context))
                    {
                        string uname = Com.Public.SqlEncStr(rsa.Decrypt(usernameEncode));
                        if (!string.IsNullOrEmpty(uname))
                        {
                            string pwd = Com.Public.SqlEncStr(rsa.Decrypt(pwdEncode));
                            Com.Session.userpw = pwd;
                            Com.Session.usertp = "0";
                            string pwdmd5 = Com.Public.StrToMD5(pwd);
                            //查询所登录的用户名和密码是否一致。如果一致,则返回true;否则,返回false。
                            SchSystem.BLL.SchUserInfo userbll = new SchSystem.BLL.SchUserInfo();
                            bool result = userbll.Exists("UserName='******' and PassWord='******' and Stat=1 and AccStat=1 and SysType=2 and schid=" + Com.Public.getKey("adminschid"));
                            if (result == true)
                            {
                                //用户登录处理函数
                                str = Com.Public.UserLoginDo(uname, false, Com.Public.getKey("appschid"));
                                if (str == "1" && pwd == "123456")
                                {
                                    str = "2";
                                }
                            }
                            else
                            {
                                str = "3";//账号或密码错误,或者被停用,请联系管理员
                            }
                        }
                        else
                        {
                            str = "4";//用户名不能为空
                        }
                    }
                    else
                    {
                        str = "5";//验证码错误
                    }
                }
                catch (Exception ex)
                {
                    str = ex.Message;
                }
                context.Response.Write(str);
            }
            else if (Action == "out")//退出
            {
                /*PublicMethod.Clear();*/

                context.Session.Clear();
                context.Session.Abandon();
                context.Response.Clear();
                //清除cookies
                Com.CookieHelper.ClearCookie("uname");
                context.Response.Write("out");
            }
        }
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.login);
            FindViewById <TextView>(Resource.Id.head_title).Text = "博客园登录";
            Button btnBack = FindViewById <Button>(Resource.Id.title_bar_back);

            btnBack.Click += delegate { Finish(); };
            textUserName   = FindViewById <EditText>(Resource.Id.text_username);
            textPwd        = FindViewById <EditText>(Resource.Id.text_pwd);
            Button btnLogin = FindViewById <Button>(Resource.Id.btn_login);

            btnLogin.Click += async delegate
            {
                string uName = textUserName.Text;
                if (string.IsNullOrWhiteSpace(uName))
                {
                    Msg.AppMsg.MakeText(this, "请输入用户名", Msg.AppMsg.STYLE_ALERT).Show();
                    return;
                }
                string pwd = textPwd.Text;
                if (string.IsNullOrWhiteSpace(pwd))
                {
                    Msg.AppMsg.MakeText(this, "请输入密码", Msg.AppMsg.STYLE_ALERT).Show();
                    return;
                }
                waitDialog = CommonHelper.CreateLoadingDialog(this, GetString(Resource.String.login_msg));
                try
                {
                    waitDialog.Show();
                    RSACryptoService rsaService = new RSACryptoService(CNBlogAPI.Service.UserService.publicKey);
                    AccessToken      token      = await CNBlogAPI.Service.UserService.Login(rsaService.Encrypt(uName), rsaService.Encrypt(pwd));

                    if (token == null)
                    {
                        Msg.AppMsg.MakeText(this, "登录失败", Msg.AppMsg.STYLE_ALERT);
                    }
                    else
                    {
                        CommonHelper.token = token;
                        CommonHelper.SaveTextFile(CommonHelper.TokenFileName, this, JsonConvert.SerializeObject(token));
                        CommonHelper.userInfo = await CNBlogAPI.Service.UserService.GetCurrentLoginUserInfo(CommonHelper.token);

                        CommonHelper.userInfo.UName = textUserName.Text;
                        CommonHelper.userInfo.Pwd   = textPwd.Text;
                        CommonHelper.SaveTextFile(CommonHelper.UserInfoFileName, this, JsonConvert.SerializeObject(CommonHelper.userInfo));
                        Msg.AppMsg.MakeText(this, "登录成功", Msg.AppMsg.STYLE_INFO).Show();
                        Intent intent = new Intent(this, typeof(PersonalCenterActivity));
                        intent.PutExtra("loginSuccessfulFlag", true);
                        SetResult(Result.Ok, intent);
                        Finish();
                    }
                }
                catch (Exception ex)
                {
                    Msg.AppMsg.MakeText(this, "登录错误,请稍候再试", Msg.AppMsg.STYLE_ALERT).Show();
                    Android.Util.Log.Debug("error:", ex.Message);
                }
                finally
                {
                    waitDialog.Cancel();
                }
            };
        }
Example #14
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string op  = Request["op"];
            string pwd = "";

            if (op == "login")
            {
                try
                {
                    teaAccount = Request["userName"].Trim();
                    pwd        = Request["pwd"].Trim();
                    TeacherBll       bll     = new TeacherBll();
                    string           roles   = "administrator";
                    RSACryptoService rsa     = new RSACryptoService();
                    Teacher          teacher = bll.Login(teaAccount, rsa.Decrypt(pwd));
                    if (teacher != null)
                    {
                        if (teacher.TeaType == 0)
                        {
                            Session["user"]  = teacher;
                            Session["state"] = 0;
                            Response.Cookies[FormsAuthentication.FormsCookieName].Value = null;
                            FormsAuthenticationTicket Ticket = new FormsAuthenticationTicket(1, teaAccount, DateTime.Now, DateTime.Now.AddMinutes(30), true, roles); //建立身份验证票对象
                            string HashTicket = FormsAuthentication.Encrypt(Ticket);                                                                                 //加密序列化验证票为字符串
                            //Session["HashTicket"] = HashTicket;
                            HttpCookie UserCookie = new HttpCookie(FormsAuthentication.FormsCookieName, HashTicket);                                                 //生成Cookie
                            Context.Response.Cookies.Add(UserCookie);                                                                                                //票据写入Cookie
                            isLogined(teaAccount);
                            LogHelper.Info(this.GetType(), teacher.TeaAccount + " - " + teacher.TeaName + " - 登录");
                            Response.Write("登录成功");
                            Response.End();
                        }
                        else if (teacher.TeaType == 2)
                        {
                            Session["user"]  = teacher;
                            Session["state"] = 2;
                            Response.Cookies[FormsAuthentication.FormsCookieName].Value = null;
                            FormsAuthenticationTicket Ticket = new FormsAuthenticationTicket(1, teaAccount, DateTime.Now, DateTime.Now.AddMinutes(30), true, roles); //建立身份验证票对象
                            string HashTicket = FormsAuthentication.Encrypt(Ticket);                                                                                 //加密序列化验证票为字符串
                            //Session["HashTicket"] = HashTicket;
                            HttpCookie UserCookie = new HttpCookie(FormsAuthentication.FormsCookieName, HashTicket);                                                 //生成Cookie
                            Context.Response.Cookies.Add(UserCookie);                                                                                                //票据写入Cookie
                            isLogined(teaAccount);
                            LogHelper.Info(this.GetType(), teacher.TeaAccount + " - " + teacher.TeaName + " - 登录");
                            Response.Write("登录成功");
                            Response.End();
                        }
                        else
                        {
                            LogHelper.Error(this.GetType(), "用户名或密码错误");
                            Response.Write("用户名或密码错误");
                            Response.End();
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.Error(this.GetType(), ex);
                }
            }
        }
Example #15
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string s         = "";
            string sessionId = Request["sid"];

            if (sessionId == null || sessionId == "")
            {
                Hashtable hOnline = (Hashtable)Application["Online"];
                if (hOnline != null)
                {
                    IDictionaryEnumerator idE = hOnline.GetEnumerator();
                    while (idE.MoveNext())
                    {
                        if (idE.Key != null && idE.Key.ToString().Equals(Session.SessionID))
                        {
                            if (idE.Value != null && "Offline".Equals(idE.Value.ToString()))
                            {
                                hOnline.Remove(Session.SessionID);
                                Application.Lock();
                                Application["Online"] = hOnline;
                                Application.UnLock();

                                Session.Abandon();
                                s = "已登录";
                                Response.Write(s);
                                Response.End();
                                return;
                            }
                            break;
                        }
                    }
                    Response.Write(s);
                    Response.End();
                }
            }
            else
            {
                string cry = RSACryptoService.DecryptByAES(sessionId);
                if (cry != "cancel")
                {
                    Hashtable hOnline = (Hashtable)Application["Online"];
                    if (hOnline != null)
                    {
                        IDictionaryEnumerator idE = hOnline.GetEnumerator();
                        while (idE.MoveNext())
                        {
                            if (idE.Key != null && idE.Key.ToString().Equals(cry))
                            {
                                if (idE.Value != null && "Offline".Equals(idE.Value.ToString()))
                                {
                                    hOnline.Remove(cry);
                                    Application.Lock();
                                    Application["Online"] = hOnline;
                                    Application.UnLock();

                                    Session.Abandon();
                                    s = "已登录";
                                    Response.Write(s);
                                    Response.End();
                                    return;
                                }
                                break;
                            }
                        }
                    }
                }
                else
                {
                    s = "已失效";
                }
                Response.Write(s);
                Response.End();
            }
        }
Example #16
0
        public JsonResult LoginValidate()
        {
            string sourceUrl = CommonHelper.GetPostValue("url");

            if (!string.IsNullOrEmpty(sourceUrl))
            {
                ViewBag.SourceUrl = sourceUrl;
            }
            sourceUrl = Server.UrlDecode(sourceUrl);
            string username = CommonHelper.GetPostValue("username");
            string password = CommonHelper.GetPostValue("password");
            //string mRemember = CommonHelper.GetPostValue("remember");

            LoginValidateEntity entity = new LoginValidateEntity();

            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                entity.ErrorCode    = "E0011";
                entity.ErrorMessage = ErrorInfoHelper.GetErrorValue(entity.ErrorCode);
                return(Json(entity, JsonRequestBehavior.AllowGet));
            }

            string ip = IPHelper.GetLoginIp(System.Web.HttpContext.Current.Request);
            var    rSaCryptoService   = new RSACryptoService(ProductConfigHelper.ThinkTankJsEncryptPrivateKeyForCSharp, ProductConfigHelper.ThinkTankJsEncryptPublickKeyForCSharp);
            string strDecryptUsername = rSaCryptoService.Decrypt(username);
            string strDecryptPassword = rSaCryptoService.Decrypt(password);

            try
            {
                T_BG_User user = _bgUserService.GetUser(strDecryptUsername, strDecryptPassword);
                if (user != null)
                {
                    if (user.Status == 0)
                    {
                        entity.ErrorCode = "E0003";
                    }
                    else if (user.Status == 1)
                    {
                        string        address  = LoginHelper.GetMaxMindOmniData(ip);
                        T_BG_LoginLog loginLog = new T_BG_LoginLog {
                            LogUserID = user.ID, IP = ip, Address = address, LogTime = DateTime.Now, IsLogIn = true
                        };
                        long result = _bgLoginLogService.Add(loginLog);
                        entity.ErrorCode = result > 0 ? "E0001" : "E0007";
                        LoginHelper.SetBgUserCookie(user);

                        entity.ToUrl = string.IsNullOrEmpty(sourceUrl) ? DomainUrlHelper.PublicMessagePath + "/Login/Index" : sourceUrl;
                    }
                    else if (user.Status == 2)
                    {
                        entity.ErrorCode = "E0004";
                    }
                    else if (user.Status == 3)
                    {
                        entity.ErrorCode = "E0005";
                    }
                    else
                    {
                        entity.ErrorCode = "E0006";
                    }
                    entity.ErrorMessage = ErrorInfoHelper.GetErrorValue(entity.ErrorCode);
                }
            }
            catch (Exception)
            {
                entity.ErrorCode    = "E0008";
                entity.ErrorMessage = ErrorInfoHelper.GetErrorValue(entity.ErrorCode);
            }
            return(Json(entity, JsonRequestBehavior.AllowGet));
        }
Example #17
0
        private async void BtnConfigure_Click(object sender, EventArgs e)
        {
            try
            {
                btnConfigure.Enabled = false;
                txtPassword.Enabled  = false;
                Properties.Settings.Default.NotProcessing = false;
                toolStripServiceStatus.Text = "Initializing...";

                var cert = new RSACryptoService(pfxFile: txtFile.Text, password: txtPassword.Text.Trim());

                if (cert.HasPrivateKey == false)
                {
                    toolStripServiceStatus.Text = "Failed to configure NPrinting. No private key present.";

                    MessageBox.Show("Error: The provided certificate does not have a private key.",
                                    Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);

                    txtFile.Text         = "";
                    txtPassword.Text     = "";
                    btnConfigure.Enabled = true;
                    txtPassword.Enabled  = chkPassword.Checked;
                    Properties.Settings.Default.NotProcessing = true;
                    return;
                }

                if (chkBackup.Checked)
                {
                    toolStripServiceStatus.Text = "Creating configuration backups...";

                    File.Copy(_np.NewsStand.ConfigFile,
                              $"{_np.NewsStand.ConfigFile}.bak", overwrite: true);
                    File.Copy(_np.WebConsole.ConfigFile,
                              $"{_np.WebConsole.ConfigFile}.bak", overwrite: true);
                }

                toolStripServiceStatus.Text = "Converting and installing certificate...";

                cert.SavePublicKeyPem(_np.NewsStand.SSLCertFile);
                cert.SavePrivateKeyPem(_np.NewsStand.SSLKeyFile);
                cert.SavePublicKeyPem(_np.WebConsole.SSLCertFile);
                cert.SavePrivateKeyPem(_np.WebConsole.SSLKeyFile);

                toolStripServiceStatus.Text = "Updating NPrinting configuration files...";

                _np.UpdateConfig(_np.NewsStand.ConfigFile, _np.NewsStand.SSLCertConfEntry,
                                 _np.NewsStand.SSLKeyConfEntry);
                _np.UpdateConfig(_np.WebConsole.ConfigFile, _np.WebConsole.SSLCertConfEntry,
                                 _np.WebConsole.SSLKeyConfEntry);

                toolStripServiceStatus.Text = "NPrinting was successfully configured.";

                if (MessageBox.Show("Configuration of NPrinting was completed successfully. " +
                                    "Do you want to restart the Qlik NPrinting Web Engine service?",
                                    Application.ProductName, MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                {
                    await RestartServiceAsync();
                }
            }
            catch (CryptographicException)
            {
                toolStripServiceStatus.Text = "Failed to configure NPrinting. Invalid certificate password.";

                MessageBox.Show("Error: The password provided for the certificate is incorrect, or one is not required.",
                                Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception ex) when(ex is IOException || ex is UnauthorizedAccessException)
            {
                toolStripServiceStatus.Text = "Failed to configure NPrinting.";

                MessageBox.Show($"Error: {ex.Message}",
                                Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            Properties.Settings.Default.NotProcessing = true;
            txtPassword.Enabled  = chkPassword.Checked;
            btnConfigure.Enabled = true;
            txtPassword.Text     = "";
            txtPassword.Focus();
        }
Example #18
0
        /// <summary>
        /// 添加教师
        /// </summary>
        public void saveTeacher()
        {
            string teaAccount = Context.Request["TeaAccount"].ToString();

            if (!teabll.selectByteaId(teaAccount))
            {
                try
                {
                    int collegeId = Convert.ToInt32(Context.Request["CollegeId"]);
                    //int teaType = Convert.ToInt32(Context.Request["TeaType"]);
                    //string pwd = Context.Request["Pwd"].ToString();
                    string teaName = Context.Request["TeaName"].ToString();
                    string sex     = Context.Request["Sex"].ToString();
                    string email   = Context.Request["Email"].ToString();
                    string tel     = Context.Request["Tel"].ToString();
                    if (teabll.selectByEmail(email))
                    {//根据输入的邮箱查找是否已存在
                        Response.Write("此邮箱已存在");
                        Response.End();
                    }
                    else if (teabll.selectByPhone(tel))
                    {//根据输入的联系电话查找是否已存在
                        Response.Write("此联系电话已存在");
                        Response.End();
                    }
                    else
                    {
                        Teacher tea     = new Teacher();
                        College college = new College();
                        Teacher teacher = teabll.GetModel(tealogin.TeaAccount);
                        if (state == 0)
                        {
                            college.ColID = collegeId;
                        }
                        else
                        {
                            college.ColID = tealogin.college.ColID;
                        }
                        tea.college    = college;
                        tea.TeaType    = 1;
                        tea.TeaAccount = teaAccount;
                        RSACryptoService rsa = new RSACryptoService();
                        tea.TeaPwd  = rsa.Encrypt("000000");
                        tea.TeaName = teaName;
                        tea.Sex     = sex;
                        tea.Email   = email;
                        tea.Phone   = tel;
                        OpResult result = teabll.Insert(tea);
                        if (result == OpResult.添加成功)
                        {
                            LogHelper.Info(this.GetType(), tealogin.TeaAccount + " - " + tealogin.TeaName + " - 添加教师账号");
                            Response.Write("添加成功");
                            Response.End();
                        }
                        else
                        {
                            Response.Write("添加失败");
                            Response.End();
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.Error(this.GetType(), ex);
                }
            }
            else
            {
                Response.Write("此账号已存在");
                Response.End();
            }
        }
Example #19
0
        /// <summary>
        /// 编辑教师信息
        /// </summary>
        public void saveChange()
        {
            string teaName    = Context.Request["TeaName"].ToString();
            string teaAccount = Context.Request["TeaAccount"].ToString();
            string teaEmal    = Context.Request["TeaEmail"].ToString();
            string teaPhone   = Context.Request["TeaPhone"].ToString();
            //string pwd = Context.Request["Pwd"].ToString();
            string sex       = Context.Request["Sex"].ToString();
            int    collegeId = Convert.ToInt32(Context.Request["CollegeId"]);
            string oldPhone  = Context.Request["oldPhone"].ToString();
            string oldEmail  = Context.Request["oldEmail"].ToString();
            int    teaType;

            if (state == 0)
            {
                teaType = Convert.ToInt32(Context.Request["TeaType"]);
            }
            else
            {
                teaType = 1;
            }
            if (teaEmal != oldEmail)
            {
                if (teabll.selectByEmail(teaEmal))
                {//根据输入的邮箱查找是否已存在
                    Response.Write("此邮箱已存在");
                    Response.End();
                }
            }
            else if (teaPhone != oldPhone)
            {
                if (teabll.selectByPhone(teaPhone))
                {//根据输入的联系电话查找是否已存在
                    Response.Write("此联系电话已存在");
                    Response.End();
                }
            }
            else
            {
                Teacher tea     = new Teacher();
                College college = new College();
                try
                {
                    tealogin = (Teacher)Session["user"];
                    Teacher teacher = teabll.GetModel(tealogin.TeaAccount);
                    if (state == 0)
                    {
                        college.ColID = collegeId;
                    }
                    else
                    {
                        college.ColID = tealogin.college.ColID;
                    }
                    tea.college    = college;
                    tea.TeaAccount = teaAccount;
                    RSACryptoService rsa = new RSACryptoService();
                    tea.TeaPwd  = rsa.Encrypt(teabll.GetModel(teaAccount).TeaPwd);
                    tea.TeaName = teaName;
                    tea.Phone   = teaPhone;
                    tea.Email   = teaEmal;
                    tea.Sex     = sex;
                    tea.TeaType = teaType;
                    OpResult result = teabll.Updata(tea);
                    if (result == OpResult.更新成功)
                    {
                        LogHelper.Info(this.GetType(), tealogin.TeaAccount + " - " + tealogin.TeaName + " - 编辑" + teaAccount + "教师账号");
                        Response.Write("修改成功");
                        Response.End();
                    }
                    else
                    {
                        Response.Write("修改失败");
                        Response.End();
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.Error(this.GetType(), ex);
                }
            }
        }
Example #20
0
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                string op = Request["op"];
                if (op == "login")
                {
                    account  = Request["userName"].Trim();
                    pwd      = Request["pwd"].Trim();
                    captcha  = Request["captcha"].ToLower();
                    usertype = Request["type"].Trim();
                    string Verification = vildata();
                    string roles        = "";
                    if (Verification.Length == 0)
                    {
                        int loginstate       = 0;
                        RSACryptoService rsa = new RSACryptoService();
                        switch (usertype)
                        {
                        case "teacher":
                            TeacherBll teaBll = new TeacherBll();
                            if (teaBll.GetModel(account).TeaType == 1)
                            {
                                Teacher tea = teaBll.Login(account, rsa.Decrypt(pwd));
                                if (tea == null)
                                {
                                    loginstate = 0;
                                }
                                else
                                {
                                    loginstate           = 1;
                                    Session["loginuser"] = tea;
                                    Session["state"]     = 1;
                                    Response.Cookies[FormsAuthentication.FormsCookieName].Value = null;
                                    roles = "teacher";
                                    FormsAuthenticationTicket Ticket = new FormsAuthenticationTicket(1, account, DateTime.Now, DateTime.Now.AddMinutes(30), true, roles); //建立身份验证票对象
                                    string HashTicket = FormsAuthentication.Encrypt(Ticket);                                                                              //加密序列化验证票为字符串
                                    //Session["HashTicket"] = HashTicket;
                                    HttpCookie UserCookie = new HttpCookie(FormsAuthentication.FormsCookieName, HashTicket);                                              //生成Cookie
                                    Context.Response.Cookies.Add(UserCookie);                                                                                             //票据写入Cookie
                                    isLogined(account);
                                }
                            }
                            else
                            {
                                Response.Write("管理员");
                                Response.End();
                            }
                            break;

                        case "student":
                            StudentBll sdao = new BLL.StudentBll();
                            Student    stu  = sdao.Login(account, rsa.Decrypt(pwd));

                            if (stu == null)
                            {
                                loginstate = 0;
                            }
                            else
                            {
                                loginstate           = 1;
                                Session["loginuser"] = stu;
                                Session["state"]     = 3;
                                Response.Cookies[FormsAuthentication.FormsCookieName].Value = null;
                                roles = "student";
                                FormsAuthenticationTicket Ticket = new FormsAuthenticationTicket(1, account, DateTime.Now, DateTime.Now.AddMinutes(30), true, roles); //建立身份验证票对象
                                string HashTicket = FormsAuthentication.Encrypt(Ticket);                                                                              //加密序列化验证票为字符串
                                //Session["HashTicket"] = HashTicket;
                                HttpCookie UserCookie = new HttpCookie(FormsAuthentication.FormsCookieName, HashTicket);                                              //生成Cookie
                                Context.Response.Cookies.Add(UserCookie);                                                                                             //票据写入Cookie
                                isLogined(account);
                            }
                            break;
                        }
                        if (loginstate == 0)
                        {
                            Response.Write("用户名或密码错误");
                            Response.End();
                        }
                        else if (loginstate == 1)
                        {
                            if (Convert.ToInt32(Session["state"]) == 1)
                            {
                                Teacher tea = (Teacher)Session["loginuser"];
                                LogHelper.Info(this.GetType(), tea.TeaAccount + " - " + tea.TeaName + " - 登录");
                            }
                            else if (Convert.ToInt32(Session["state"]) == 3)
                            {
                                Student stu = (Student)Session["loginuser"];
                                LogHelper.Info(this.GetType(), stu.StuAccount + " - " + stu.RealName + " - 登录");
                            }
                            Response.Write("登录成功");
                            Response.End();
                        }
                        else
                        {
                            Response.Write("登录失败");
                            Response.End();
                        }
                    }
                    else
                    {
                        LogHelper.Error(this.GetType(), account + " - " + Verification);
                        Response.Write(Verification);
                        Response.End();
                    }
                }
            }
            catch
            {
            }
        }
Example #21
0
        /// <summary>
        /// 修改密码
        /// </summary>
        public void Change()
        {
            RSACryptoService rsa    = new RSACryptoService();
            string           oldpwd = rsa.Decrypt(Request["old"]);
            string           newpwd = Request["newP"];
            int    state            = Convert.ToInt32(Session["state"].ToString());
            string Old    = oldpwd;
            string NewPwd = newpwd;

            try
            {
                if (state == 0 || state == 2)
                {
                    admin      = (Teacher)Session["user"];
                    teacherPwd = admin.TeaPwd;
                    teacherID  = admin.TeaAccount;
                    if (Old == teacherPwd)
                    {
                        Result result = teaBll.UpdataPwd(teacherID, NewPwd);
                        if (result == Result.更新成功)
                        {
                            LogHelper.Info(this.GetType(), admin.TeaAccount + " - " + admin.TeaName + " - 修改密码");
                            Response.Write("更新成功");
                            Response.End();
                        }
                    }
                    else
                    {
                        Response.Write("更新失败");
                        Response.End();
                    }
                }
                else if (state == 1)
                {
                    teacher    = (Teacher)Session["loginuser"];
                    teacherPwd = teacher.TeaPwd;
                    teacherID  = teacher.TeaAccount;
                    if (Old == teacherPwd)
                    {
                        Result result = teaBll.UpdataPwd(teacherID, NewPwd);
                        if (result == Result.更新成功)
                        {
                            LogHelper.Info(this.GetType(), teacher.TeaAccount + " - " + teacher.TeaName + " - 修改密码");
                            Response.Write("更新成功");
                            Response.End();
                        }
                    }
                    else
                    {
                        Response.Write("更新失败");
                        Response.End();
                    }
                }
                else
                {
                    stu    = (Student)Session["loginuser"];
                    stuPwd = stu.StuPwd;
                    stuID  = stu.StuAccount;
                    if (Old == stuPwd)
                    {
                        Result result = stuBll.UpdataPwd(stuID, NewPwd);
                        if (result == Result.更新成功)
                        {
                            LogHelper.Info(this.GetType(), stu.StuAccount + " - " + stu.RealName + " - 修改密码");
                            Response.Write("更新成功");
                            Response.End();
                        }
                    }
                    else
                    {
                        Response.Write("更新失败");
                        Response.End();
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(this.GetType(), ex);
            }
        }
Example #22
0
        public static string usersave(string dotype, string schid, string systype, string userid, string usercode, string usertname, string usertel, string userpst, string usertitle, string usermobile, string username, string userpw, string usersex, string userstat, string usersub, string userdpts, string userroles)
        {
            //解密 RSA
            RSACryptoService rsa = new RSACryptoService(PublicProperty.PrivateKey, PublicProperty.PublicKey);

            if (userpw != "")
            {
                userpw = Com.Public.SqlEncStr(rsa.Decrypt(userpw));
            }
            string ret = "";

            if (Com.Session.userid == null)
            {
                ret = "expire";
            }
            else
            {
                try
                {
                    if (string.IsNullOrEmpty(schid) || schid == "0")
                    {
                        ret += "非法的学校!";
                    }
                    SchSystem.BLL.SchUserInfo   userbll   = new SchSystem.BLL.SchUserInfo();
                    SchSystem.Model.SchUserInfo usermodel = new SchSystem.Model.SchUserInfo();
                    if (!Com.Public.isVa(schid, ""))
                    {
                        ret += "无跨界权限;";
                    }
                    //判断编号及账号是否有重复,生成密码加密
                    if (dotype == "e")
                    {
                        //if (userbll.ExistsUserCode(int.Parse(userid), usercode, int.Parse(schid)))
                        //{
                        //    ret += "用户编号重复!";
                        //}
                        if (username != "")
                        {
                            if (userbll.ExistsUserName(int.Parse(userid), username))
                            {
                                ret += "账号重复!";
                            }
                            else if (!userbll.ExistsUserName(0, username))
                            {
                                userbll.UpdateUserName(username, int.Parse(userid));
                            }
                        }
                    }
                    if (dotype == "a")
                    {
                        //if (userbll.ExistsUserCode(0, usercode, int.Parse(schid)))
                        //{
                        //    ret += "用户编号重复!";
                        //}
                        if (username != "")
                        {
                            /*if (userbll.ExistsUserName(0, username, int.Parse(schid)))
                             * {
                             *  ret += "账号重复!";
                             * }*/
                            StringBuilder sbExists = new StringBuilder();
                            string        utname   = "";
                            if (userbll.ExistsUserName(0, username))
                            {
                                SchSystem.BLL.SchUserDeptV bllusdpt = new SchSystem.BLL.SchUserDeptV();
                                DataTable dt = bllusdpt.GetList("DepartName,UserTname", "UserName='******'").Tables[0];
                                DataRow[] dr = dt.Select();
                                foreach (DataRow item in dr)
                                {
                                    sbExists.Append(item["DepartName"].ToString() + "、");
                                    utname = item["UserTname"].ToString();
                                }
                                //ret += "账号重复!";
                                ret += sbExists.ToString().Substring(0, sbExists.ToString().Length - 1);
                                ret += "," + utname;
                            }
                        }
                    }
                    if (ret == "")
                    {
                        usermodel.LastRecTime = DateTime.Now;
                        usermodel.LastRecUser = Com.Session.userid;
                        usermodel.Mobile      = usermobile;
                        usermodel.Postion     = userpst;
                        usermodel.Sex         = int.Parse(usersex);
                        if (!string.IsNullOrEmpty(userstat))
                        {
                            usermodel.AccStat = int.Parse(userstat);
                        }
                        else
                        {
                            usermodel.AccStat = 2;
                        }
                        usermodel.SubCode   = usersub;
                        usermodel.SysType   = int.Parse(systype);
                        usermodel.Telno     = usertel;
                        usermodel.Title     = usertitle;
                        usermodel.UserNo    = usercode;
                        usermodel.UserTname = usertname;
                        if (dotype == "e")
                        {
                            if (!string.IsNullOrEmpty(userpw) && !string.IsNullOrEmpty(username))
                            {
                                userpw = Com.Public.StrToMD5(userpw);
                                if (userpw == Com.Public.StrToMD5("123456"))//如果重置密码时保存
                                {
                                    userbll.UpdatePw(int.Parse(userid), userpw);
                                }
                            }
                            usermodel.UserId = int.Parse(userid);
                            userbll.UpdateUser(usermodel);
                        }
                        if (dotype == "a")
                        {
                            //必须有账号和密码
                            if (!string.IsNullOrEmpty(userpw) && !string.IsNullOrEmpty(username))
                            {
                                usermodel.PassWord = Com.Public.StrToMD5("123456"); //SchManagerInfoSystem.Common.DESEncrypt.Encrypt(userpw) ;添加时均为123456密码
                            }
                            usermodel.RecTime  = DateTime.Now;
                            usermodel.RecUser  = Com.Session.userid;
                            usermodel.SchId    = int.Parse(schid);
                            usermodel.UserName = username;
                            userid             = userbll.Add(usermodel).ToString();
                        }
                        //添加或更新关联部门
                        SchSystem.BLL.SchUserDept userdeptbll = new SchSystem.BLL.SchUserDept();
                        if (userdpts == null)
                        {
                            userdpts = "0";
                        }
                        userdeptbll.DoUserDept(userid, Com.Session.userid, schid, userdpts);
                        //添加或更新关联角色
                        SchSystem.BLL.SchUserRole userrolebll = new SchSystem.BLL.SchUserRole();
                        if (userroles == null)
                        {
                            userroles = "0";
                        }
                        userrolebll.DoUserRole(userid, Com.Session.userid, schid, userroles);
                        ret = "success";
                    }
                }
                catch (Exception ex)
                {
                    ret = ex.Message;
                }
            }
            return(ret);
        }
Example #23
0
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string action = context.Request["Action"];

            if (action == "null")
            {
                context.Response.Write(PublicProperty.PublicKey);
            }
            else if (action == "Login")//登录
            {
                string str = "";
                //解密 RSA
                RSACryptoService rsa = new RSACryptoService(PublicProperty.PrivateKey, PublicProperty.PublicKey);
                try
                {
                    string LgName  = context.Request["UserName"];
                    string Pwd     = context.Request["PassWord"];
                    string Code    = context.Request["TxtCode"];
                    string txtcode = rsa.Decrypt(Code);
                    if (recode(txtcode, context))
                    {
                        string uname = Com.Public.SqlEncStr(rsa.Decrypt(LgName));
                        if (!string.IsNullOrEmpty(uname))
                        {
                            string pwd = Com.Public.SqlEncStr(rsa.Decrypt(Pwd));
                            Com.Session.Pwd = pwd;
                            string pwdmd5 = Com.Public.StrToMD5(pwd);
                            //查询所登录的用户名和密码是否一致。如果一致,则返回true;否则,返回false。
                            Learning.BLL.UserInfo userbll = new BLL.UserInfo();
                            bool result = userbll.strExists("UserName='******' and Pwd='" + pwdmd5 + "' and Status=1 and WorkerID='" + Com.Public.getKey("WorkerID") + "'");
                            if (result == true)
                            {
                                //用户登录处理
                                DataTable dt = userbll.GetList("UserName='******' and Status=1 and WorkerID='" + Com.Public.getKey("WorkerID") + "' ").Tables[0];
                                Com.Session.UserId   = dt.Rows[0]["UserId"].ToString();
                                Com.Session.UserName = dt.Rows[0]["UserName"].ToString();
                                Com.Session.WorkerId = dt.Rows[0]["WorkerId"].ToString();
                                Com.Session.Name     = dt.Rows[0]["Name"].ToString();
                                Com.Session.DepartId = dt.Rows[0]["DepartId"].ToString();
                                str = "001";
                            }
                            else
                            {
                                str = "002";//账号或密码错误,或者被停用,请联系管理员
                            }
                        }
                        else
                        {
                            str = "003";//用户名不能为空
                        }
                    }
                    else
                    {
                        str = "004";//验证码错误
                    }
                }
                catch (Exception ex)
                {
                    str = ex.Message;
                }
                context.Response.Write(str);
            }
            else if (action == "out")//退出
            {
                /*PublicMethod.Clear();*/
                context.Session.Clear();
                context.Session.Abandon();
                context.Response.Clear();
                //清除cookies
                // Com.CookieHelper.ClearCookie("uname");
                context.Response.Write("out");
            }
        }