Ejemplo n.º 1
0
        public async Task SendDirectMessage(int userId, int chatId, string messageText, bool isInvite)
        {
            var sendToUser = messageText;
            await Clients.All.SendAsync("sendDirectMessage", userId, chatId, sendToUser);


            if (!isInvite)
            {
                messageText = DataEncryption.DecryptionFromString(messageText);
                var newMessage = new Message(userId, chatId, messageText);
                _context.Messages.Add(newMessage);
                await _context.SaveChangesAsync();
            }

            /* var chatUserToReceive = _context.ChatUsers.SingleOrDefault(ch => ch.ChatId == chatId && ch.UserId != userId);
             * if (chatUserToReceive != null)
             * {
             *   var userToReceive = _context.Users.Find(chatUserToReceive.UserId);
             *   Console.WriteLine(userToReceive.WebSocketId);
             *   if (userToReceive.WebSocketId != null)
             *   {
             *       await Clients.Client(userToReceive.WebSocketId).SendAsync("sendDirectMessage", userId, chatId, sendToUser);
             *   }
             * }
             */
        }
        private void SaveButtonClick(object sender, RoutedEventArgs e)
        {
            FileStream FileWriter = new FileStream(@"Passwords.bin", FileMode.Create);

            BinaryFormatter formatter = new BinaryFormatter();

            List <SerializableDirectoryTree> l = new List <SerializableDirectoryTree>();

            foreach (var child in DirectoryTree.Items)
            {
                if (child is AbstractDirectoryTreeItem)
                {
                    l.Add(new SerializableDirectoryTree(child as AbstractDirectoryTreeItem));
                }
            }

            using (var mem = new MemoryStream())
            {
                formatter.Serialize(mem, l);
                var encrypted = DataEncryption.Encrypt(MasterPassword, mem.ToArray());
                FileWriter.Write(encrypted, 0, encrypted.Length);
            }

            //formatter.Serialize(FileWriter, l);

            FileWriter.Close();
        }
Ejemplo n.º 3
0
        /// <summary>
        /// 获取token
        /// </summary>
        /// <returns></returns>

        public string GetToken()
        {
            try
            {
                string         userName = ConfigCom.W_UserName;
                string         userPass = ConfigCom.W_UserPass;
                string         uri      = ConfigCom.W_TokenUri;
                DataEncryption data     = new DataEncryption();
                //加密方法
                string     encryUserName = data.Encryption(userName);
                string     encryUserPass = data.Encryption(userPass);
                RestClient rc            = new RestClient(baseUri);
                string     res           = rc.Get(uri + "/" + encryUserName + "/" + encryUserPass);
                //验证res
                if (string.IsNullOrWhiteSpace(res))
                {
                    ConfigCom.SetValue("W_ID", res);
                    ConfigCom.SetValue("W_TokenExpire", DateTime.Now.AddMinutes(Convert.ToDouble(ConfigCom.W_TokenExpireInterval)).ToString("yyyy-MM-dd HH:mm:ss"));
                    return(res);
                }
                else
                {
                    log.Error("GetToken()返回值为空");
                    return("");
                }
            }
            catch (Exception ex)
            {
                log.Error("GetToken()出错:" + ex.Message.ToString());
                return("false");
            }
        }
        public static bool Deserialize(string password, out object obj)
        {
            obj = null;

            FileStream fs = new FileStream("Passwords.bin", FileMode.Open);

            byte[]          encryptedData;
            BinaryFormatter formatter = new BinaryFormatter();

            try
            {
                encryptedData = (byte[])formatter.Deserialize(fs);
            }
            catch (SerializationException e)
            {
                MessageBox.Show("Failed to deserialize. Reason: " + e.Message);
                return(false);
            }
            finally
            {
                fs.Close();
            }
            byte[] decryptedData = DataEncryption.Decrypt(password, encryptedData);
            if (decryptedData == null)
            {
                return(false);
            }
            obj = ByteArrayToObject(decryptedData);
            return(true);
        }
        public bool SendMail()
        {
            if (mailWindow.Subject.Length == 0)
            {
                mailWindow.Status = "Subject is empty";
                return(false);
            }
            if (mailWindow.MailContent.Length == 0)
            {
                mailWindow.Status = "Content is empty";
                return(false);
            }
            List <CheckInDto> checkInDtos = (List <CheckInDto>)mailWindow.EmailData;

            foreach (CheckInDto checkInDto in checkInDtos)
            {
                try
                {
                    DataEncryption dataEncryption = new DataEncryption(checkInDto.EventAttendeesID.ToString(), null);
                    QRModuleLib.QRModule.CreateQRCode(dataEncryption.OutputCode, checkInDto.EventAttendeesID + ".png", mailWindow.EventId);
                    EmailLibrary.Email.SendEMail(Properties.Resources.email, Properties.Resources.password, checkInDto.Email, mailWindow.Subject, mailWindow.MailContent, mailWindow.EventId + "/" + checkInDto.EventAttendeesID + ".png");
                }
                catch
                {
                    mailWindow.Status = "Something email address is not exits";
                    return(false);
                }
            }
            EventDao eventDao = new EventDao();

            eventDao.MakeConnection(Properties.Resources.strConnection);
            eventDao.UpdateStatus(int.Parse(mailWindow.EventId), "sended mail");
            return(true);
        }
 private void Button_Click(object sender, RoutedEventArgs e)
 {
     if (!File.Exists(@"Passwords.bin"))
     {
         Page1 p = new Page1();
         p.MasterPassword = MasterPasswordBox.Password;
         NavigationService.Navigate(p);
     }
     else
     {
         byte[] data      = File.ReadAllBytes(@"Passwords.bin");
         byte[] decrypted = DataEncryption.Decrypt(MasterPasswordBox.Password, data);
         if (decrypted == null)
         {
             MessageBox.Show("Invalid password");
         }
         else
         {
             BinaryFormatter d = new BinaryFormatter();
             List <SerializableDirectoryTree> l = d.Deserialize(new MemoryStream(decrypted)) as List <SerializableDirectoryTree>;
             Page1 p = new Page1();
             p.MasterPassword = MasterPasswordBox.Password;
             foreach (var item in l)
             {
                 p.DirectoryTree.Items.Add(item.TurnIntoTreeView(p));
             }
             NavigationService.Navigate(p);
         }
     }
 }
Ejemplo n.º 7
0
        private static X509Certificate2 Getx509Certificate()
        {
            X509Certificate2 cert = null;

            try
            {
                SecureString pwd = DataEncryption.GetSecuredPasswordFromEncryptedFile(ConfigurationManager.AppSettings["EncryptedPasswordFilePathandName"], Int32.Parse(ConfigurationManager.AppSettings["EncryptionByteLength"]), ConfigurationManager.AppSettings["EncryptionEntropy"]);

                cert = new X509Certificate2(ConfigurationManager.AppSettings["CertificateFilePath"], pwd, X509KeyStorageFlags.MachineKeySet |
                                            X509KeyStorageFlags.PersistKeySet |
                                            X509KeyStorageFlags.Exportable);
            }
            catch (Exception ex)
            {
                string message = ex.Message;
                if (ex.InnerException != null)
                {
                    message += "Inner Exception : " + ex.InnerException.Message;
                }

                throw new LoggerException("AcquireToken exception: " + message, ex);
            }

            return(cert);
        }
Ejemplo n.º 8
0
        private void DoneButton_Click(object sender, RoutedEventArgs e)
        {
            InitializeComponent();
            DataEncryption workingWithFile = new DataEncryption();

            workingWithFile.WriteToFileEnrypted(_data, DataEncryption.TaskType.Task);
            this.Close();
        }
Ejemplo n.º 9
0
        public ActionResult <bool> Logout()
        {
            var           cookies       = Request.Cookies;
            AuthTokenBlob authTokenBlob = DataEncryption.Decrypt <AuthTokenBlob>(cookies[CookieName.AuthToken]);

            BurnOldToken(authTokenBlob.Email);

            return(true);
        }
Ejemplo n.º 10
0
        public ActionResult ChariDraw()
        {
            ViewData[SessionKey.VwCurrentNav] = "game";
            Session.Remove(SessionKey.DonationId);
            Session.Remove(SessionKey.DonationAmt);
            Session.Remove("ChariGame");
            Session.Add("ChariGame", DataEncryption.HashString("chari.game"));
            ChariWinnerViewModel cwvm = new ChariWinnerViewModel();

            if (Request.Headers["Referer"] != null && Request.Headers["Referer"].Contains(ConfigurationManager.AppSettings["UPOPHost"]))
            {
                cwvm.IsFromChinaUnion = true;
                base.RenderTip("完成抽奖前,请先不要关闭本页面,或点击其他链接", 3);
                _log.Info("from china union");
                string oAmt   = Request.Form.Get("orderAmount");
                string oQid   = Request.Form.Get("qid");
                string svar   = "orderAmount=" + oAmt.ToString() + "&orderCurrency=" + Request.Form.Get("orderCurrency") + "&qid=" + oQid;
                string sig_in = Request.Form.Get("signature");
                string sig    = DataEncryption.HashUPOPChariOrder(svar).Replace("-", "").ToLower();
                if (sig_in.Equals(sig))
                {
                    _log.Info("china union sign ok");
                    //signatures equal, writes variables to session
                    Session[SessionKey.ID]          = oQid;
                    Session[SessionKey.DonationAmt] = decimal.Parse(oAmt) / 100;
                    Session[SessionKey.UPOPChari]   = "Verified";
                }
            }
            #region Winner List

            cwvm.WinList = _uow.GetWinnerPrizeList();

            // pad the winner list to at least 5 winners
            for (int i = cwvm.WinList.Count; i < 10; i++)
            {
                switch (i % 5)
                {
                case 0: ViewBag.WinList += "<ul><li>wahaha</il><li>4天前</li><li>HTC 手机</li></ul>";
                    break;

                case 1: ViewBag.WinList += "<ul><li>iamgod</il><li>5天前</li><li>Sony TV</li></ul>";
                    break;

                case 2: ViewBag.WinList += "<ul><li>willywanker</il><li>7天前</li><li>笔记本</li></ul>";
                    break;

                case 3: ViewBag.WinList += "<ul><li>seanc</il><li>10天前</li><li>自行车</li></ul>";
                    break;

                case 4: ViewBag.WinList += "<ul><li>jaschen</il><li>13天前</li><li>iPad</li></ul>";
                    break;
                }
            }
            #endregion

            return(View(cwvm));
        }
Ejemplo n.º 11
0
        public UserModel Login(string Username, string Password)
        {
            UserModel userInfo    = new UserModel();
            string    encUsername = new DataEncryption().Encrypt(Username.Trim());
            string    encPassword = new DataEncryption().Encrypt(Password.Trim());

            try
            {
                using (UserEntities users = new UserEntities())
                {
                    var user = (from u in users.Users
                                where u.Username == encUsername && u.Password == encPassword
                                select u).FirstOrDefault();

                    if (user != null)
                    {
                        var config = new MapperConfiguration(
                            cfg =>
                        {
                            cfg.CreateMap <User, UserModel>();
                        }
                            );

                        var mapper = config.CreateMapper();
                        userInfo            = mapper.Map <UserModel>(user);
                        userInfo.LoginCount = 0;
                        userInfo.LastLogin  = DateTime.Now;
                        UpdateUser(userInfo, true);
                    }
                    else
                    {
                        //Invalid password
                        var checkUser = SearchAllUsers(null, Username.Trim());
                        if (checkUser != null)
                        {
                            var usr = checkUser.FirstOrDefault();
                            if (usr.LoginCount < 3)
                            {
                                usr.LoginCount += 1;
                            }
                            else
                            {
                                usr.IsLocked = true;
                            }

                            UpdateUser(usr, true);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                log.LogError(Username, "DataSolutions.Data", "Login", ex.Message);
            }
            return(userInfo);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// 获取案件文件
        /// </summary>
        /// <returns></returns>
        private void GetFile()
        {
            string wjlj = HttpUtility.UrlDecode(HttpUtility.UrlDecode(Request["wjlj"].Trim()));
            string wjmc = HttpUtility.UrlDecode(HttpUtility.UrlDecode(Request["wjmc"].Trim()));

            if (string.IsNullOrEmpty(wjlj) || string.IsNullOrEmpty(wjmc))
            {
                Response.Write("访问参数错误");
            }
            else
            {
                EDRS.BLL.XY_DZJZ_XTPZ   bll   = new EDRS.BLL.XY_DZJZ_XTPZ(this.Request);
                EDRS.Model.XY_DZJZ_XTPZ model = bll.GetModel((int)EnumConfig.卷宗文件下载地址);
                if (model != null)
                {
                    IceServicePrx isp = new IceServicePrx();

                    string msg = "";

                    byte[] bytes = new byte[] { };

                    if (isp.DownFile(model.CONFIGVALUE, wjlj, wjmc, "", ref bytes, ref msg))
                    {
                        string showType = ConfigHelper.GetConfigString("FileShowType");
                        if (showType == "1")
                        {
                            Response.Write("<img style=\"max-width:100%;\" alt=\"\" src=\"data:image/jpeg;base64," + Convert.ToBase64String(bytes) + "\" />");
                        }
                        else
                        {
                            byte[] info = DataEncryption.Decryption(bytes);

                            //MemoryStream ms = new MemoryStream(bytes);  //把那个byte[]数组传进去,然后
                            //File.WriteAllBytes(Server.MapPath("/") + "ddd.pdf", bytes);
                            //FileStream fs = new FileStream(Server.MapPath("/")+"ccc.pdf",FileMode.Append, FileAccess.Write);
                            //ms.WriteTo(fs);
                            //ms.Close();
                            //fs.Close();

                            Response.ContentType = "application/pdf";
                            Response.AddHeader("content-disposition", "filename=pdf");
                            Response.AddHeader("content-length", info.Length.ToString());
                            Response.BinaryWrite(info);
                        }
                    }
                    else
                    {
                        Response.Write(msg);
                    }
                }
                else
                {
                    Response.Write("请先配置" + EnumConfig.卷宗文件下载地址);
                }
            }
        }
        public void CheckIn()
        {
            BitmapSource srs    = (BitmapSource)checkInWindow.ImageSource;
            Bitmap       bitmap = null;

            if (srs != null)
            {
                using (MemoryStream outStream = new MemoryStream())
                {
                    BitmapEncoder enc = new BmpBitmapEncoder();

                    enc.Frames.Add(BitmapFrame.Create(srs));
                    enc.Save(outStream);
                    bitmap = new Bitmap(outStream);
                }
            }
            try
            {
                String         content        = QRModuleLib.QRModule.DecodeFromQRCode(bitmap);
                DataEncryption dataEncryption = new DataEncryption(null, content);
                content = dataEncryption.InputCode;
                if (content == null)
                {
                    checkInWindow.Status = "Waiting....";
                }
                else
                {
                    CheckInDao checkInDao = new CheckInDao();
                    checkInDao.MakeConnection(Properties.Resources.strConnection);
                    try
                    {
                        int        id         = int.Parse(content);
                        CheckInDto checkInDto = checkInDao.CheckInByAttendeesID(id);
                        if (checkInDto.Check)
                        {
                            checkInWindow.Status = "QR code is checked!";
                        }
                        else
                        {
                            checkInDao.UpdateStatus(id, true);
                            LoadMemberEvent();
                            checkInWindow.Status = checkInDto.Name;
                        }
                    }
                    catch
                    {
                        checkInWindow.Status = "QR code is not existed!";
                    }
                }
            }
            catch (NullReferenceException ex)
            {
                checkInWindow.Status = "Waiting";
            }
        }
Ejemplo n.º 14
0
        public void TestEncryption_BadCert()
        {
            Mock <ILogger> mockLogger = new Mock <ILogger>();
            X509CertConfig certConfig = new X509CertConfig()
            {
                CertFile = "certnotfound.pfx"
            };

            Assert.Throws <Exception>(() => DataEncryption.EncryptData(mockLogger.Object, certConfig, "Encrypt Me"));
            Assert.Throws <Exception>(() => DataEncryption.EncryptData(mockLogger.Object, certConfig, "Decrypt Me"));
        }
Ejemplo n.º 15
0
        public void ChangePassword()
        {
            RequestContext.Current.Add <UserContext>("UserContext", new UserContext {
                UserId = 1, LanguageId = 1, UserName = "******", SiteId = 1
            });
            SecurityManager securityManager = new SecurityManager();
            string          password        = DataEncryption.Encrypt("Password1");

            // securityManager.CreateAccount(new UserMembership { UserName = "******", Password = password });
            securityManager.ChangePassword("admin", "oldPassword", password);
        }
        public void Password_Match()
        {
            var user = testCtx.UserAuthentications.First(f => f.Username != un);

            user.Password = DataEncryption.Encrypt(pwd);
            testCtx.SaveChanges();

            var result = uManager.CheckPasswordAsync(new NuApplicationUser(user.Username), pwd).Result;

            Assert.IsTrue(result);
        }
        public void DecryptTest()
        {
            DataEncryption dataEncrypt = new DataEncryption();

            dataEncrypt.secret_key = "(IV8FxF!cv~JT3)v+iVRb/Kr@{kipW";
            dataEncrypt.secret_iv  = "apasajakalauyangini";
            String result   = dataEncrypt.Decrypt("ZGIvVisvQmQzNU1xVkJMcmh1V0dzZz09");
            String expected = "suwandi";

            Assert.AreEqual(expected, result);
        }
Ejemplo n.º 18
0
        private void Authenticate(User user)
        {
            var cookies       = Response.Cookies;
            var authTokenBlob = new AuthTokenBlob(user.Email, TokenProvider.NewAuthToken);

            PutAuthUserToDb(authTokenBlob);
            string encryptedBlob = DataEncryption.Encrypt(authTokenBlob);

            cookies.Append(CookieName.AuthToken, encryptedBlob, new CookieOptions {
                HttpOnly = true, Path = "/"
            });
        }
Ejemplo n.º 19
0
    private IEnumerator StartTimer()
    {
        while (true)
        {
            if (isRunning)
            {
                if (temptime == null)
                {
                    break;
                }

                string  [] decodesTime = DataEncryption.Base64Decode(temptime).Split(':');
                if (decodesTime == null)
                {
                    continue;
                }
                int tempm = int.Parse(decodesTime [0]);                                                 //minutes
                int temps = int.Parse(decodesTime [1]);                                                 //seconds

                temps--;
                if (temps == -1)
                {
                    temps = 59;
                    tempm--;
                }

                if (tempm == 0 && temps == 0)
                {
                    isDone    = true;
                    isRunning = false;

                    if (!string.IsNullOrEmpty(doneEventName) && doneEventObject != null)                                                               //send message when done
                    {
                        doneEventObject.SendMessage(doneEventName);
                    }
                }

                string strSeconds = getStringTime(temps);
                string strMinutes = getStringTime(tempm);
                temptime = DataEncryption.Base64Encode(strMinutes + ":" + strSeconds);
                if (applyTimeToTextMeshes)
                {
                    ApplyToTextMeshes();
                }
                yield return(new WaitForSeconds(delayTime));
            }
            else
            {
                yield return(0);
            }
        }
    }
Ejemplo n.º 20
0
        public ActionResult Login(Model.UserInfo usr)
        {
            var    x    = _uow.UserInfoService.Get(m => m.UserName == usr.UserName);
            string hpwd = DataEncryption.HashString(usr.Password);

            if ((x != null) && (x.UserName == usr.UserName) && (x.Password == hpwd))
            {
                // user authenticated login and store in session
                Session[SessionKey.User] = x;
                string returnUrl = Request["returnUrl"];

                var str      = Ichari.Common.DataEncryption.HashString(string.Format("{0}{1}{2}", x.UserName, x.Password, Ichari.Common.WebUtils.GetAppSettingValue("UserSalt")));
                var ckDomain = string.Format(".{0}", WebUtils.GetAppSettingValue(StaticKey.AkSiteDomainName));
                if (Request.IsLocal)
                {
                    ckDomain = null;
                }
                DataEncryption.SaveToCookies(str, usr.UserName, x.LotteryUserId, ckDomain, usr.IsSaveCookie);

                if (Request.IsAjaxRequest())
                {
                    return(Json(new ReturnJsonResult()
                    {
                        IsSuccess = true
                    }));
                }


                if (!string.IsNullOrWhiteSpace(returnUrl))
                {
                    return(Redirect(returnUrl));
                }
                else if (string.IsNullOrWhiteSpace(x.TrueName) || string.IsNullOrWhiteSpace(x.IdentityCardNo) || string.IsNullOrWhiteSpace(x.Phone))
                {
                    return(RedirectToAction("UserInfo"));
                }
                return(RedirectToAction("Summary"));
            }
            else
            {
                ModelState.AddModelError("", "用户/密码错误");
            }

            if (Request.IsAjaxRequest())
            {
                return(Json(new ReturnJsonResult()
                {
                    IsSuccess = false
                }));
            }
            return(View(usr));
        }
Ejemplo n.º 21
0
        public ActionResult <string> GetSharedCategoryLink(GetSharedCategoryLinkModel model)
        {
            ShareBlob blob = new ShareBlob
            {
                ShareMode = ShareMode.Category,
                Email     = LoggedUser.Email,
                Category  = model.Category
            };

            string encryptedBlob = DataEncryption.Encrypt(blob);

            return(encryptedBlob.ToUrl());
        }
Ejemplo n.º 22
0
        public ActionResult <string> GetSharedImageLink(GetSharedImageLinkModel model)
        {
            ShareBlob blob = new ShareBlob
            {
                ShareMode = ShareMode.SingleImage,
                Email     = LoggedUser.Email,
                PhotoNum  = model.PhotoNum
            };

            string encryptedBlob = DataEncryption.Encrypt(blob);

            return(encryptedBlob.ToUrl());
        }
Ejemplo n.º 23
0
        public void ProtectUnprotect_WithTestCases_ProducesCorrectResults(string testcase)
        {
            const string password = "******";

            var protector = new DataEncryption(new DataEncoder());

            var input           = Encoding.UTF8.GetBytes(testcase);
            var protectedData   = protector.Protect(input, password);
            var unprotectedData = protector.Unprotect(protectedData, password);
            var output          = Encoding.UTF8.GetString(unprotectedData);

            Assert.That(output, Is.EqualTo(input));
        }
Ejemplo n.º 24
0
 public void Play()
 {
     if (!isRunning)
     {
         isRunning = true;
         if (!isStarted)
         {
             temptime = DataEncryption.Base64Encode(startTime);
             StartCoroutine("StartTimer");
             isStarted = true;
         }
     }
 }
Ejemplo n.º 25
0
        /// <summary>
        /// eCollabroSetup
        /// </summary>
        /// <param name="registerModel"></param>
        public void eCollabroSetup(RegisterModel registerModel)
        {
            RegisterDC registerDC = new RegisterDC();

            registerDC.UserName = registerModel.UserName;
            registerDC.Password = DataEncryption.Encrypt(registerModel.Password);
            registerDC.Email    = registerModel.Email;
            ServiceResponse eCollabroSetupResponse = _setupProxy.Execute(opt => opt.eCollabroSetup(registerDC));

            if (eCollabroSetupResponse.Status != ResponseStatus.Success)
            {
                HandleError(eCollabroSetupResponse.Status, eCollabroSetupResponse.ResponseMessage);
            }
        }
Ejemplo n.º 26
0
        /*ServiceContract.AddTask(name,dateTime);*/


        protected override void OnStart(string[] args)
        {
            //todo get current date and time from file
            DateTime date = DateTime.Now;

            var   timerCallback = new TimerCallback(ListExam);
            Timer timer         = new Timer(timerCallback, date, 0, 60000);

            InitializeServiceHost();

            DataEncryption workingWithFile = new DataEncryption();

            _data = workingWithFile.ReadFileEncrypted();
        }
Ejemplo n.º 27
0
        public ActionResult ForgotPassword(Model.UserNameEmail fpwd)
        {
            if (ModelState.IsValid)
            {
                Model.UserInfo usr = _uow.UserInfoService.Get(o => o.UserName == fpwd.UserName);
                if (usr != null && usr.UserName == fpwd.UserName && usr.Email == fpwd.Email)
                {
                    SmtpClient smtpm = new SmtpClient();
                    smtpm.Host           = "mail.charilot.cc";
                    smtpm.Port           = 1025;
                    smtpm.EnableSsl      = false;
                    smtpm.Credentials    = new NetworkCredential("*****@*****.**", "");
                    smtpm.DeliveryMethod = SmtpDeliveryMethod.Network;

                    MailAddress sender   = new MailAddress("*****@*****.**", "集善网系统", Encoding.UTF8);
                    MailAddress receiver = new MailAddress(fpwd.Email);
                    MailMessage eMailMsg = new MailMessage(sender, receiver);
                    eMailMsg.Subject = "集善网忘记密码,密码重置系统邮件";
                    eMailMsg.Bcc.Add("*****@*****.**");
                    //eMailMsg.Bcc.Add("*****@*****.**");
                    eMailMsg.IsBodyHtml = true;
                    Random   rnd       = new Random();
                    DateTime dt        = DateTime.Now;
                    string   resetLink = DataEncryption.EncryptAES(dt.ToBinary().ToString() + "?" + fpwd.Email + "?" + rnd.Next(100, 10000).ToString() + "?" + fpwd.UserName + "?" + dt.ToShortTimeString());
                    eMailMsg.Body = "尊敬的集善网客户: <br />您好! <br />系统已收到您的密码找回申请,请点击链接 <br /><p>" +
                                    "http://" + Request.Url.Host + "/Account/ResetPassword?en=" + resetLink +
                                    "</p>重设您的密码。<br /><br />为了您的安全,该邮件通知地址将在 48 小时后失效,谢谢合作。<br /><p>--------------------------------------------------<br />" +
                                    "此邮件由系统发出,请勿直接回复! <br />集善网 版权所有(C) 2008-2009</p>";
                    eMailMsg.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
                    try
                    {
                        smtpm.Send(eMailMsg);
                    }
                    catch (Exception fre)
                    {
                        ModelState.AddModelError("", fre.Message);
                    }
                }
                else
                {
                    ModelState.AddModelError("", "*UserName/Email not found");
                }
            }
            else
            {
                ModelState.AddModelError("", "Error 99");
            }

            return(View());
        }
Ejemplo n.º 28
0
        /// <summary>
        /// CreateAccount
        /// </summary>
        /// <param name="registerModel"></param>
        public void CreateAccount(RegisterModel registerModel)
        {
            RegisterDC registerDC = new RegisterDC();

            registerDC.UserName = registerModel.UserName;
            registerDC.Password = DataEncryption.Encrypt(registerModel.Password);
            registerDC.Email    = registerModel.Email;
            ServiceResponse createAccountResponse = _securityProxy.Execute(opt => opt.CreateAccount(registerDC));

            if (createAccountResponse.Status != ResponseStatus.Success)
            {
                HandleError(createAccountResponse.Status, createAccountResponse.ResponseMessage);
            }
        }
Ejemplo n.º 29
0
        /// <summary>
        /// ChangePassword
        /// </summary>
        /// <param name="ChangePasswordModel"></param>
        public void ChangePassword(ChangePasswordModel changePasswordModel)
        {
            ChangePasswordDC changePasswordRequest = new ChangePasswordDC();

            changePasswordRequest.OldPassword = DataEncryption.Encrypt(changePasswordModel.OldPassword);
            changePasswordRequest.NewPassword = DataEncryption.Encrypt(changePasswordModel.NewPassword);
            changePasswordRequest.UserName    = changePasswordModel.UserName;
            ServiceResponse changePasswordResponse = _securityProxy.Execute(opt => opt.ChangePassword(changePasswordRequest));

            if (changePasswordResponse.Status != ResponseStatus.Success)
            {
                HandleError(changePasswordResponse.Status, changePasswordResponse.ResponseMessage);
            }
        }
Ejemplo n.º 30
0
        /// <summary>
        /// AuthenticateUser
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        public void AuthenticateUser(string username, string password)
        {
            AuthenticateUserRequest verifyLoginRequest = new AuthenticateUserRequest();

            verifyLoginRequest.Username    = username;
            verifyLoginRequest.Password    = DataEncryption.Encrypt(password);
            verifyLoginRequest.UserContext = SecurityClientTranslate.Convert(UserContext);
            ServiceResponse verifyLoginResponse = _securityProxy.Execute(opt => opt.AuthenticateUser(verifyLoginRequest));

            if (verifyLoginResponse.Status != ResponseStatus.Success)
            {
                HandleError(verifyLoginResponse.Status, verifyLoginResponse.ResponseMessage);
            }
        }