Exemple #1
0
        public ActionResult resendCode(VerifyEmail model)
        {
            fillUserData();
            if (model.userId == null || model.email == null)
            {
                TempData["errMessage"] = "Email or user is null";
            }
            else
            {
                UserVerificationHelper.VerificationResult result = UserVerificationHelper.reSendVerificationLog(model.userId, model.email);
                if (result.status.Equals("500"))
                {
                    TempData["errMessage"] = result.message;
                }
                else
                {
                    TempData["errMessage"]     = "";
                    TempData["SuccessMessage"] = result.message;
                }
            }



            return(View("VerifyEmail"));
        }
Exemple #2
0
        public async Task SendVerifyEmailAsync(VerifyEmail verifyEmail)
        {
            string       FilePath = Directory.GetCurrentDirectory() + "/Smtp/Templates/VerifyTemplate.html";
            StreamReader str      = new StreamReader(FilePath);
            string       MailText = str.ReadToEnd();

            str.Close();
            MailText = MailText.Replace("[FirstName]", verifyEmail.FirstName + " " + verifyEmail.LastName).Replace("[UrlKey]", verifyEmail.UrlKey);
            var email = new MimeMessage();

            email.Sender = MailboxAddress.Parse(_mailSettings.Mail);
            email.To.Add(MailboxAddress.Parse(verifyEmail.ToEmail));
            email.Subject = $"Password Recovery for your Account";
            var builder = new BodyBuilder();

            builder.HtmlBody = MailText;
            email.Body       = builder.ToMessageBody();
            using var smtp   = new SmtpClient();
            smtp.CheckCertificateRevocation = false;

            smtp.Connect(_mailSettings.Host, _mailSettings.Port, SecureSocketOptions.Auto);
            smtp.Authenticate(_mailSettings.Mail, _mailSettings.Password);
            await smtp.SendAsync(email);

            smtp.Disconnect(true);
        }
        public App()
        {
            InitializeComponent();

            // determine page to navigate to
            var isLoggedIn = TokenService.IsLoggedIn().Result;

            ContentPage mainPage;

            if (isLoggedIn)
            {
                if (TokenService.GetIsEmailVerified())
                {
                    mainPage = new Root();
                }
                else
                {
                    mainPage = new VerifyEmail();
                }
            }
            else
            {
                mainPage = new Login();
            }

            MainPage = new NavigationPage(mainPage);
        }
Exemple #4
0
        public async Task <ServiceResult> VerifyEmailAsync(VerifyEmail model)
        {
            ServiceResult result = new ServiceResult();

            PassportUser user = await userManager.FindByIdAsync(model.UserId);

            if (user == null)
            {
                result.Errors.Add(new ServiceResult.Error
                {
                    Key     = nameof(Errors.InvalidSignin),
                    Message = Errors.InvalidSignin
                });
                result.Code = 401;

                return(result);
            }

            IdentityResult identityResult = await userManager.ConfirmEmailAsync(user, model.Token);

            if (!identityResult.Succeeded)
            {
                result.Errors.Add(new ServiceResult.Error
                {
                    Key     = nameof(Errors.InvalidSignin),
                    Message = Errors.InvalidSignin
                });
                result.Code = 401;
            }

            return(result);
        }
        public void BuildEmailTemplate(int regID)
        {
            string ActivationLink = "{0}##{1}";

            var regInfo = _Util.Facade.UserLoginFacade.GetAllUserName().Where(x => x.Id == regID).FirstOrDefault();

            EncryptionDeycryption salt = new EncryptionDeycryption();

            ActivationLink = string.Format("?regId={0}",
                                           HttpUtility.UrlEncode(
                                               DESEncryptionDecryption.EncryptPlainTextToCipherText(string.Format(ActivationLink, regID, regInfo.EmailAddress))));
            if (regID > 0)
            {
                VerifyEmail ver = new VerifyEmail();
                ver.Name    = regInfo.UserName;
                ver.ToEmail = regInfo.EmailAddress;
                ver.EmailVerificationLink = AppConfig.SiteDomain + "/Home/Confirm" + ActivationLink;
                TempData["Link"]          = ver.EmailVerificationLink;

                if (_Util.Facade.MailFacade.SendEmailVerify(ver) == true)
                {
                    _Util.Facade.MailFacade.SendSuccessEmail(ver);
                }
            }
        }
        public async Task <IActionResult> ConfirmMail(string username, string pw)
        {
            VerifyEmail verifyEmail = new VerifyEmail {
                Username = username,
                Pw       = pw,
            };

            return(await verifyEmail.Excute());
        }
        /// <summary>
        /// Note: this may be called multiple times as the customer loves to reclick the same link ovr and over
        /// Moreover, we are going to poll using this .. from the verify email page until we get a "done" message with a URL
        /// </summary>
        /// <param name="verifyEmail"></param>
        /// <returns></returns>
        public HttpResponseMessage VerifyEmail([FromBody] VerifyEmail verifyEmail)
        {
            if (verifyEmail == null)
            {
                throw new ArgumentNullException("verifyEmail");
            }


            throw new NotImplementedException();

            // Responses?
            // - "tokenerror" unknown/bad token
            // - other failure modes??
            // - "processing" received and processing
            // - "done" done, ready to log in ... here's the URL..
        }
Exemple #8
0
 public ActionResult VerifyEmail(VerifyEmail model)
 {
     fillUserData();
     UserVerificationHelper.VerificationResult result = UserVerificationHelper.verifyCode(model.userId, model.code);
     if (result.status.Equals("200"))
     {
         var user = UserManager.FindById(model.userId);
         SignInAsync(user, isPersistent: false);
         return(RedirectToAction("AdminPage", "Roles"));
     }
     else
     {
         TempData["errMessage"] = result.message;
     }
     return(View());
 }
Exemple #9
0
        public async Task <bool> VerifyEmail(VerifyEmail model)
        {
            var client = _httpClientFactory.CreateClient();

            client.BaseAddress = new Uri(_configuration["BaseAddress"]);

            var json = JsonConvert.SerializeObject(model); //convert json to string

            var response = await client.GetAsync($"/api/users/VerifyEmail?token={model.Token}");

            if (response.IsSuccessStatusCode)//kiểm tra status code
            {
                return(true);
            }
            return(false);
        }
Exemple #10
0
        public async Task <IActionResult> VerifyEmail([FromQuery] string Token)
        {
            if (!ModelState.IsValid)
            {
                return(View());
            }

            if (!string.IsNullOrEmpty(Token))
            {
                var tokenReset = new VerifyEmail()
                {
                    Token = Token
                };
                return(View(tokenReset));
            }
            return(View("Error"));
        }
Exemple #11
0
        private void Action_ResendEmail()
        {
            string ErrorMessage;
            Label  TempPrimaryEmail = (Label)formView.FindControl("TempPrimaryEmail");

            //When the Email verification for Change email is resent, need to reset EmailChangeRequestDate to getdate()
            if (UserBLL.ResetEmailChangeRequestDate(ViewData.UserId, TempPrimaryEmail.Text))
            {
                bool mailSent = VerifyEmail.SendEmailVerificationNotificationforEmailChange(false, ViewData.UserId, ViewData.CreatedBy, TempPrimaryEmail.Text, out ErrorMessage);
                if (mailSent)
                {
                    DisplayMessage("The email has been sent successfully. <br />", false);
                }
                else
                {
                    DisplayMessage("The email attempt failed with the following error message:" + "<br />" + ErrorMessage, true);
                }
            }
        }
Exemple #12
0
        public async Task <IHttpActionResult> VerifyEmail(VerifyEmail model)
        {
            var user = db.Users.Where(a => a.Email.Equals(model.email)).FirstOrDefault();

            if (user == null)
            {
                return(BadRequest("No matching user with this email!"));
            }
            UserVerificationHelper.VerificationResult result = UserVerificationHelper.verifyCode(model.userId == null ? user.Id : model.userId, model.code);

            if (result.status.Equals("500"))
            {
                return(BadRequest(result.message));
            }
            else
            {
                return(Ok(result));
            }
        }
Exemple #13
0
        public async Task <IActionResult> VerifyEmail(VerifyEmail model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var result = await _userApiClient.VerifyEmail(model);

            if (result)
            {
                _notyf.Success("Xác thực Email thành công");
                return(RedirectToAction("Index", "Login"));
            }

            ModelState.AddModelError("", "Reset mật khẩu thất bại");//key and message

            return(View(model));
        }
Exemple #14
0
        protected void ChangeEmailCommand(object sender, EventArgs e)
        {
            //TODO: Validation to be replaced with ProxyValidator
            Page.Validate("ChangeEmail");
            if (Page.IsValid)
            {
                //using (TransactionScope scope = new TransactionScope(TransactionScopeOption.RequiresNew))
                //{
                bool   DoCommit = false;
                string ErrorMessage;
                string NewEmail = Email.Text.Trim();

                //Check if the Username already exists
                if (RegisterUserBLL.DoesUserNameExist(NewEmail))
                {
                    DisplayMessage("The Primary Email address is already registered. Duplicates are not allowed.", true);
                    return;
                }
                else
                {
                    if (UserBLL.ChangeEmail(ShiptalkPrincipal.UserId, ShiptalkPrincipal.Username, NewEmail, ShiptalkPrincipal.UserId, out ErrorMessage))
                    {
                        if (VerifyEmail.SendEmailVerificationNotificationforEmailChange(false, ShiptalkPrincipal.UserId, ShiptalkPrincipal.UserId, NewEmail, out ErrorMessage))
                        {
                            DoCommit = true;
                        }
                    }

                    if (DoCommit)
                    {
                        //scope.Complete();
                        DisplayMessage("Your request has been submitted. You will receive this Change Email request information email at your old Email address and  'Email verification' email at your new Email address shortly. Please follow the instruction to complete the Email verification process . If you do not receive an email after a while, please contact the help desk.", false);
                    }
                    else
                    {
                        DisplayMessage("Sorry. Unable to change your email. Please contact support for assistance.", false);
                    }
                    //}
                }
            }
        }
Exemple #15
0
        public async Task <OperationResult> VerifyEmail([FromBody] VerifyEmail model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            var result = await passport.VerifyEmailAsync(model);

            if (result.Successful)
            {
                return(Ok());
            }

            foreach (var error in result.Errors)
            {
                ModelState.AddModelError(error.Key, error.Message);
            }

            return(BadRequest());
        }
Exemple #16
0
        public bool SendSuccessEmail(VerifyEmail email)
        {
            try
            {
                Hashtable templateVars = new Hashtable();
                templateVars.Add("DOMAINNAME", email.Name);


                templateVars.Add("ToEmail", email.ToEmail);
                if (SentEmail(templateVars, EmailTemplateKey.Registration.ThanksForJoining))
                {
                    return(true);
                }
            }
            catch (Exception ex)
            {
                //Logger.AddElmah(ex);
            }

            return(false);
        }
Exemple #17
0
        public bool SendEmailVerify(VerifyEmail email)
        {
            try
            {
                Hashtable templateVars = new Hashtable();
                templateVars.Add("NAME", email.Name);
                templateVars.Add("EMAILVERIFICATIONLINK", email.EmailVerificationLink);

                templateVars.Add("ToEmail", email.ToEmail);
                if (SentEmail(templateVars, EmailTemplateKey.Registration.VerifyEmailAddress))
                {
                    return(true);
                }
            }
            catch (Exception ex)
            {
                //Logger.AddElmah(ex);
            }

            return(false);
        }
        public async Task <IResponseContent> VerificationEmailAsync(string tenantUid, string origin, string verificationUrl, string email, string language, string authorization = "")
        {
            var verifyEmail = new VerifyEmail
            {
                //TenantPlatformMapGuid = tenantUid,
                Email           = email,
                VerificationUrl = verificationUrl
            };

            try
            {
                IRestResponse response = await SubmitPostAsync(URL_VERIFCATION_EMAIL_REQUEST, origin, verifyEmail, authorization, tenantUid);

                return(await AssertResponseContentAsync <VerifyEmailResponseContent>(response));
            }
            catch (Exception ex)
            {
                return(new VerifyEmailResponseContent
                {
                    Exception = ex
                });
            }
        }
Exemple #19
0
        public async Task <IActionResult> VerifyEmail(VerifyEmail model)
        {
            ViewBag.Title = "Verify Email";

            if (!ModelState.IsValid)
            {
                ViewBag.Error = "Email is required";
                return(View(model));
            }
            var result = await AuthRepo.GetUserbyEmailAsync(model.Email);

            if (!result.Item1)
            {
                ViewData["error"] = result.Item2;
                return(View(model));
            }
            var TempObject = JsonConvert.SerializeObject(new LoginGetViewModel {
                UserName = model.Email, ReturnUrl = model.ReturnUrl, Name = result.Item2
            });

            TempData["LoginModel"] = TempObject;
            return(RedirectToAction("Authenticate", new { ReturnUrl = model.ReturnUrl }));
        }
Exemple #20
0
        public ActionResult SignUp(User U, bool condition)
        {
            if (U.Fname == "" || U.lname == "" || U.Email == "" || U.password == "" || U.birthday == "10/24/1900" || U.gender == "" || condition == false)
            {
                return(Json(4, JsonRequestBehavior.DenyGet));
            }
            VerifyEmail v          = new VerifyEmail();
            int         validation = v.VEmail(U.Email);

            if (validation == 0)
            {
                //Email is valid
                Rep_user RU    = new Rep_user();
                SHA256   Crypt = new SHA256();
                U.password = Crypt.DataSHA256(U.password);
                var    signUp = RU.AddUser(U);
                var    User   = db.Users.Where(c => c.Email.Equals(U.Email) && c.password.Equals(U.password)).Single().id;
                string sp     = Server.MapPath("\\Content\\User\\");
                Directory.CreateDirectory(sp + "\\" + User);
                //User login

                HttpCookie idLoginCookie = new HttpCookie("idlogin", User.ToString());
                Response.Cookies["idlogin"].Secure = true;
                Response.Cookies.Add(idLoginCookie);
                return(Json(1, JsonRequestBehavior.DenyGet));
            }
            else if (validation == 1)
            {
                //email exist in Database
                return(Json(2, JsonRequestBehavior.DenyGet));
            }
            else
            {
                //email format is not valid
                return(Json(3, JsonRequestBehavior.DenyGet));
            }
        }
Exemple #21
0
        public async Task <IActionResult> PasswordReset(VerifyEmail model)
        {
            ViewBag.Title = "Password Reset";

            if (!ModelState.IsValid)
            {
                return(RedirectToAction("PasswordReset", new { ReturnUrl = "" }));
            }

            var isEmailInDb = await AuthRepo.GetUserbyEmailAsync(model.Email);

            if (!isEmailInDb.Item1)
            {
                ViewBag.Error = isEmailInDb.Item2;
                return(RedirectToAction("PassordReset", new { ReturnUrl = "" }));
            }

            var result = await AuthRepo.GetResetPasswordToken(model.Email);

            if (!result.Item1)
            {
                ViewBag.Error = "Email does not exist, Please Enter registered Email";
            }

            var callbackUrl = UrlHelperExtensions.ActionLink(this.Url, "ResetPassword", "Auth", new { Username = result.Item2.Email, Token = result.Item3, ReturnUrl = model.ReturnUrl });
            var res         = await AuthRepo.SendResetPasswordEmail(result.Item2, callbackUrl);

            if (!res.Item1)
            {
                ViewBag.Error = "Email Failed to send";
            }

            ViewBag.Success = "Email Sent Successfully";
            return(View(new VerifyEmail {
                ReturnUrl = model.ReturnUrl
            }));
        }
        public ActionResult CreateAccount(UserAddViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            string      body           = "";
            VerifyEmail objVerifyEmail = new VerifyEmail();

            try
            {
                using (var db = new cursomvcEntities())
                {
                    user oUser = new user();
                    oUser.IdState     = 2; //1-Activo 2-Activacion Pendiente 3-Eliminado
                    oUser.nombre      = model.Nombre;
                    oUser.email       = model.Email;
                    oUser.password    = Encrypt.GetSHA256(model.Password);
                    oUser.edad        = model.Edad;
                    oUser.tokenCuenta = Encrypt.genTok(model.Email);

                    db.user.Add(oUser);
                    db.SaveChanges();

                    string c = "\"";


                    body = @"
                <body>
	                <style>
                      h3{color:default;}
                      h4{color:lightgreen;}
                    </style>
 
                 <div>   
    
                 <h3>Hola " + oUser.nombre + @".</h3>
                   <p>Gracias por unirte a nuestro Blog. Para hacer uso de nuestra plataforma por favor da clic en el enlace para verificar tu cuenta.</p>
                      <div align=" + c + "center" + c + @">
                      <a href=" + c + "https://*****:*****@">Activar Cuenta</a>
                       
                        <br>
                        <br>
                        <div align=" + c + "left" + c + @">
                        Ricardo Alcántara Castro<br>
                        5561086391 <br>
                        Ingeniero en Computación
                    </div>
                 </body>
                ";

                    objVerifyEmail.sendMail(oUser.email, "Activar Cuenta", body);
                }
                HttpContext.Application["verifyAccount"] = 1;

                return(Redirect(Url.Content("~/Access/Verify/")));
            }
            catch (Exception ex)
            {
                return(Redirect(Url.Content("~/Access/") + ex.Message));
            }
        }
        public ActionResult RecuperarPass(string email)
        {
            string      body           = "";
            VerifyEmail objVerifyEmail = new VerifyEmail();
            user        oUser          = new user();

            try
            {
                using (cursomvcEntities db = new cursomvcEntities())
                {
                    try
                    {
                        var lst = from usu in db.user
                                  where usu.email == email && usu.IdState == 1   //Tiene que ser un usuario con cuenta activada
                                  select usu.Id;

                        Random cod = new Random(Convert.ToInt32(lst.First()));
                        int    n   = cod.Next(1000, 1000000);

                        var okUser = db.user.Find(Convert.ToInt32(lst.First()));
                        okUser.password        = Encrypt.GetSHA256(n.ToString());
                        db.Entry(okUser).State = System.Data.Entity.EntityState.Modified;
                        db.SaveChanges();

                        int codigo = n;

                        if (lst.Count() > 0)
                        {
                            //Mandas el correo

                            string c = "\"";


                            body = @"
                        <body>
	                        <style>
                              h3{color:default;}
                              h4{color:lightgreen;}
                            </style>
 
                         <div>   
    
                         <h3>Hola " + okUser.nombre + @".</h3>
                           <p>Damos seguimiento a la recuperación de tu contraseña. Podrás acceder a nuestro blog con el siguiente código.</p>
                            <p>Código de Acceso: " + codigo + @"</p>  
                         </body>
                        ";

                            objVerifyEmail.sendMail(email, "Recuperar Contraseña", body);

                            return(Content("1"));
                        }
                        else
                        {
                            return(Content("El correo proporcionado no se encuentra registrado en nuestro Blog"));
                        }
                    }
                    catch (Exception d)
                    {
                        return(Content("El correo proporcionado no se encuentra registrado en nuestro Blog"));
                    }
                }
            }
            catch (Exception ex)
            {
                return(Content("Ocurrio un error :(" + ex.Message));
            }
        }
Exemple #24
0
        protected void dataSourceUserView_Updated(object sender, ObjectContainerDataSourceStatusEventArgs e)
        {
            Page.Validate("UserProfile");
            if (!Page.IsValid)
            {
                return;
            }

            UserViewData ChangedUserData = (UserViewData)e.Instance;

            try
            {
                if (IsCMSOrStateScope)
                {
                    UserBLL.UpdateIsAdminStatus(ChangedUserData.UserId, ChangedUserData.IsAdmin);
                }
            }
            catch (Exception UpdateAccountEx)
            {
                DisplayMessage("Failed while saving administrator status. Please try later or contact support for assistance.", true);
                return;
            }

            //Update IsActive of UserData with what we got from Updating method.
            //ChangedUserData.IsActive = IsActiveUser;
            //using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required))
            //{
            if (UserBLL.UpdateUserProfile(CreateUserProfile(ChangedUserData), this.AccountInfo.UserId))
            {
                if (!UserData.IsShipDirector && UserData.IsUserStateScope)
                {
                    string ErrorMessage;
                    if (!UserBLL.SaveDescriptors(ChangedUserData.UserId, GetDescriptorsSelectedByAdmin(), ShiptalkLogic.Constants.Defaults.DefaultValues.AgencyIdForNonAgencyUsers, this.AccountInfo.UserId, out ErrorMessage))
                    {
                        DisplayMessage(ErrorMessage, true);
                        return;
                    }

                    if (!UserBLL.UpdateStateSuperDataEditor(ChangedUserData.UserId, ChangedUserData.IsStateSuperDataEditor, this.AccountInfo.UserId))
                    {
                        DisplayMessage("An error occured while updating the super data editor status", true);
                        return;
                    }
                }

                //Update the Is Approver Designate status for CMS/State scope Admins alone.
                //Ignore Ship directors and CMS Admins.
                if (UserData.IsAdmin)
                {
                    if ((!UserData.IsCMSAdmin && UserData.IsUserCMSScope) || (!UserData.IsShipDirector && UserData.IsUserStateScope))
                    {
                        if (!UserBLL.UpdateApproverDesignate(UserData.UserId, GetApproverDesignateSelection(), this.AccountInfo.UserId))
                        {
                            DisplayMessage("Failed while updating approver designate status. Please try later or contact support for assistance.", true);
                            return;
                        }
                    }
                }

                bool ReviewerUpdateFailed = false;
                if (ScopeIdOfUser == Scope.State.EnumValue <int>())
                {
                    if (NewSupervisorId == -1)
                    {
                        NewSupervisorId = 0;
                    }

                    if (NewSupervisorId != UserIdOfOldReviewer)
                    {
                        //Save the new ReviewerID as Supervisor
                        if (!UserBLL.SaveSupervisorForUser(ChangedUserData.UserId, NewSupervisorId, null, this.AccountInfo.UserId))
                        {
                            //If update failed, then
                            ReviewerUpdateFailed = true;
                        }
                    }
                }
                //Lavnaya: Included Change Email process : 09/02/2012
                //If Primary Email is changed, then the email should be sent to user's old email id and as well as to new email id to notify them.
                // Email verification link will be sen to the user's new email id. Users can login using their old email id till they vefy the new email. this process is same as "Edit my Email" functionality.
                //If the Primary EMail id is not changed, then we dont change it in database.

                bool   DoCommit = false;
                string ErrorMsg;
                string NewEmail = string.Empty;

                TextBox Email = formView.FindControl("Email") as TextBox;

                NewEmail = Email.Text;

                if (NewEmail != UserData.PrimaryEmail)
                {
                    if (NewEmail != "" && NewEmail != null)
                    {
                        //Check if the Username already exists
                        if (RegisterUserBLL.DoesUserNameExist(NewEmail))
                        {
                            DisplayMessage("The Primary Email address is already registered. Duplicates are not allowed.", true);
                            return;
                        }
                        else
                        {
                            if (UserBLL.ChangeEmail(ChangedUserData.UserId, UserData.PrimaryEmail, NewEmail, this.AccountInfo.UserId, out ErrorMsg))
                            {
                                if (VerifyEmail.SendEmailVerificationNotificationforEmailChange(false, ChangedUserData.UserId, ChangedUserData.UserId, NewEmail, out ErrorMsg))
                                {
                                    DoCommit = true;
                                }
                            }

                            //if (DoCommit)
                            //{
                            //    //scope.Complete();
                            //    DisplayMessage("Your request has been submitted. You will receive this Change Email request information email at your old Email address and  'Email verification' email at your new Email address shortly. Please follow the instruction to complete the Email verification process . If you do not receive an email after a while, please contact the help desk.", false);
                            //}

                            //}
                        }
                    }
                }


                //Lavnaya: Included Change Email process : 09/02/2012 -- End

                if (ReviewerUpdateFailed)
                {
                    DisplayMessage("Unable to save new supervisor. Please try later or contact support for assistance.", true);
                }


                //else if (!DoCommit)Pbattineni: If (!DoCommit) & and New email is not equal to Primary email then Throw error Message- 10/08/12
                else if (!DoCommit && NewEmail != UserData.PrimaryEmail)
                {
                    DisplayMessage("Sorry. Unable to change your email. Please contact support for assistance.", true);
                }
                else
                {
                    //scope.Complete();
                    DisplayMessage("The submitted information has been saved successfully.", false);
                }
                //formView.DataBind();
                //listViewUserRegionalProfiles.DataBind();
                //Page.DataBind();
            }
            else
            {
                DisplayMessage("Sorry. We were unable to save the information. Please contact support for assistance.", true);
            }
            //}

            //Get Fresh data for rebind.
            FetchUserData();
        }
Exemple #25
0
        private void buttonEditPassword_Click(object sender, EventArgs e)
        {
            VerifyEmail verifyEmail = new VerifyEmail();

            verifyEmail.Show();
        }
    protected void btnVerify_Click(object sender, EventArgs e)
    {
        VerifyBUS vbs = new VerifyBUS();

        //try
        //{
        VerifyBUS vBus = new VerifyBUS();
        string err = ValidateNull();
        DataTable dt = vBus.GetByUserId(getUserLogin().UserId);
        if (dt.Rows.Count >= 3)
        {
            pnSuccess.Visible = false;
            pnError.Visible = true;
            lblError.Text = "Giới hạn tối đa cho phép xác thực là 3. Vui lòng xóa mail cũ !";
        }
        else if (err == "")
        {
            // Get amazone config.
            getConfigAmazone();
            veriryEmail = new VerifyEmail(accessKey, secretKey);
            bool status = veriryEmail.VerifyEmailAddress(txtEmailVerify.Text.Trim());
            if (status == true)
            {
                // Them vao danh sach email xac thuc thanh cong.
                MailConfigBUS mcBUS = new MailConfigBUS();
                VerifyDTO vDto = new VerifyDTO();
                vDto.EmailVerify = txtEmailVerify.Text.Trim();
                vDto.isdelete = 0;
                vDto.userId = getUserLogin().UserId;
                DataTable T = vBus.CheckByEmail(vDto.EmailVerify);
                if(T.Select("UserId="+userLogin.UserId).Length>0)
                {

                    pnSuccess.Visible = pnSuccessverify.Visible = false;
                    pnError.Visible = true;

                    lblError.Text = "Email " + txtEmailVerify.Text + " đã được đăng ký";
                    return;
                }
                if (vBus.CheckByEmail(vDto.EmailVerify).Rows.Count > 0)
                {
                    pnSuccessverify.Visible = true;
                    pnError.Visible = false;
                    lbverify.Text = "Email " + txtEmailVerify.Text + " này đã được verify trong hệ thống.Bạn vui lòng click vào để kích hoạt sử dụng ";
                    return;
                }
                else
                {
                    vBus.tblVerify_insert(vDto);
                }

                // Thêm vào cấu hình mail.
                MailConfigDTO mcDTO = new MailConfigDTO();
                mcDTO.DepartmentID = getUserLogin().DepartmentId;
                mcDTO.userId = getUserLogin().UserId;
                mcDTO.Email = txtEmailVerify.Text.Trim();
                mcDTO.parentId = 1;
                mcDTO.levelId = 1;
                mcDTO.isSSL = true;
                mcDTO.Port = 25;
                mcDTO.Server = server;
                mcDTO.username = username;
                mcDTO.Password = password;
                mcDTO.Name = txtNameConfig.Text;
                if (mcBUS.GetByEmailAndPass(mcDTO.Email, mcDTO.Password, userLogin.UserId).Rows.Count > 0)
                {
                    mcDTO.Id = int.Parse(mcBUS.GetByEmailAndPass(mcDTO.Email, mcDTO.Password, userLogin.UserId).Rows[0]["Id"].ToString());
                    mcBUS.tblMailConfig_Update(mcDTO);
                }
                else
                {
                    mcBUS.tblMailConfig_insert(mcDTO);
                }

                pnError.Visible = false;
                lblSuccess.Text = "Bạn đã xác thực thành công email: " + txtEmailVerify.Text + " Vui lòng kiểm tra email để hoàn thành việc xác thực";
                txtEmailVerify.Text = "";
                txtNameConfig.Text = "";
                pnSuccess.Visible = true;
                LoadVerifyList();

            }
            else
            {
                pnSuccessverify.Visible = true;
                pnError.Visible = false;
                lbverify.Text = "Email " + txtEmailVerify.Text + " này đã được verify trong hệ thống.Bạn vui lòng click vào để kích hoạt sử dụng ";
            }
        }
        else
        {
            pnSuccess.Visible = false;
            pnError.Visible = true;
            lblError.Text = err;
            txtEmailVerify.Focus();
        }
        //}
        //catch (Exception)
        //{
        //}
    }
    private void LoadVerifyList()
    {
        try
        {
            int stt = 0;
            DataTable List = this.CreateListEmail();
            VerifyBUS vBus = new VerifyBUS();
            DataTable dtVerifyList = vBus.GetByUserId(getUserLogin().UserId);
            MailConfigBUS mcBUS = new MailConfigBUS();

            // Load accessKey & secretKey & Password.
            getConfigAmazone();
            veriryEmail = new VerifyEmail(accessKey, secretKey);
            List<string> listEmail = new List<string>();
            try { listEmail = veriryEmail.ListVerifiedEmailAddresses(); }
            catch (Exception ex)
            {
                logs.Error(userLogin.Username + "-Verify", ex);
            }
            foreach (DataRow EmailItem in dtVerifyList.Rows)
            {
                stt++;
                DataRow row = List.NewRow();
                row["No"] = stt;
                row["Email"] = EmailItem["EmailVerify"].ToString();
                if (listEmail.Contains(EmailItem["EmailVerify"].ToString()))
                {
                    row["Status"] = "Đã xác thực";
                }
                else
                {
                    row["Status"] = "Chờ xác thực..";
                }

                string email = EmailItem["EmailVerify"].ToString();
                DataTable mailConfig = mcBUS.GetByEmailAndPass(email, password, userLogin.UserId);
                if (mailConfig.Rows.Count > 0)
                {
                    row["Name"] = mailConfig.Rows[0]["Name"].ToString();
                }
                else
                {
                    row["Name"] = "Chưa cấu hình";
                }
                List.Rows.Add(row);
            }
            this.dtlEmail.DataSource = List;
            this.dtlEmail.DataBind();

        }
        catch (Exception ex)
        {
            logs.Error(userLogin.Username + "-Verify", ex);
        }
    }