public UserAuth CreateUserAuth(UserAuth newUser, string password)
        {
            ABUserAuth ab_newuser = newUser.TranslateTo <ABUserAuth>();

            ValidateNewUser(ab_newuser, password);

            string salt;
            string hash;

            passwordHasher.GetHashAndSaltString(password, out hash, out salt);

            return(dbFactory.Run(db =>
            {
                AssertNoExistingUser(db, ab_newuser);

                var digestHelper = new DigestAuthFunctions();
                ab_newuser.DigestHa1Hash = digestHelper.CreateHa1(ab_newuser.UserName, DigestAuthProvider.Realm, password);
                ab_newuser.PasswordHash = hash;
                ab_newuser.Salt = salt;
                ab_newuser.CreatedDate = DateTime.UtcNow;
                ab_newuser.ModifiedDate = newUser.CreatedDate;

                db.Insert(ab_newuser);

                ab_newuser = db.GetById <ABUserAuth>(db.GetLastInsertId());
                return ab_newuser.TranslateTo <UserAuth>();
            }));
        }
Esempio n. 2
0
 public bool CurrentUser_HasRole(RoleEnum role, RoleEnum role2, ABUserAuth current_user = null)
 {
     if (current_user == null)
     {
         current_user = CurrentUser;
     }
     return(current_user.HasRole(role) || current_user.HasRole(role2));
 }
Esempio n. 3
0
 /// <summary>
 /// Return True if current User has input role
 /// </summary>
 public bool CurrentUser_HasRole(string role, ABUserAuth current_user = null)
 {
     if (current_user == null)
     {
         current_user = User_GetByID(AuthenticatedUserID);
     }
     return(current_user.HasRole(role));
 }
Esempio n. 4
0
        public ActionResult ForgotPasswordSubmit(ABUserAuth model)
        {
            try
            {
                if (String.IsNullOrEmpty(model.Email))
                {
                    ViewBag.Error = "Please enter email.";

                    return(View("ForgotPassword", model));
                }

                if (!IsValidEmailAddress(model.Email))
                {
                    ViewBag.Error("Email format is not valid.");

                    return(View("ForgotPassword", model));
                }

                var user = User_GetByEmail(model.Email);

                if (user == null)
                {
                    ViewBag.Error = "Email you entered is not exist.";

                    return(View("ForgotPassword", model));
                }

                var template = Get_MaillingListTemplate("forgot_password_user");

                var template_helper = new EmailHelper(template.Title, template.Body);

                template_helper.Parameters.Add("Host", CurrentWebsite.Domain.First());

                template_helper.Parameters.Add("Code", encrypt.GetMD5HashData(user.Email + user.PasswordHash));

                template_helper.Parameters.Add("Email", user.Email);

                template_helper.Sender_Email = CurrentWebsite.Email_Support;

                template_helper.Sender_Name = CurrentWebsite.Name;

                template_helper.Receiver.Add(user.Email);

                SendMail(template_helper);

                ViewBag.RedirectTo = Url.Action("Index", "Home", new { });;

                ViewBag.Message = "Please check your email for instruction to get new password.";
            }
            catch (Exception ex)
            {
                ViewBag.RedirectTo = Url.Action("Index", "Home", new { });

                ViewBag.Message = string.Format("{0}: {1}.", "There was an error getting new password", ex.Message);
            }

            return(View("Message"));
        }
Esempio n. 5
0
        public ActionResult Register(string redirectTo)
        {
            var model = new ABUserAuth()
            {
                RedirectTo = redirectTo
            };

            return(View("Register", model));
        }
Esempio n. 6
0
        public ActionResult ChangePass(ABUserAuth model)
        {
            if (CurrentUser.Id != model.Id ||
                CurrentUser.Email != model.Email ||
                CurrentUser.UserName != model.UserName)
            {
                ViewBag.Error = "Please don't try to hack us.";

                return(View("ChangePass", model));
            }

            if (string.IsNullOrEmpty(model.PassNews) ||
                string.IsNullOrEmpty(model.ConfirmPassword))
            {
                ViewBag.Error = "Please enter all required fields.";

                return(View("ChangePass", model));
            }

            if (model.PassNews != model.ConfirmPassword)
            {
                ViewBag.Error = "Please enter same New password and Confirm password fields.";

                return(View("ChangePass", model));
            }

            if (!new Regex(@"(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}$", RegexOptions.Compiled).IsMatch(model.PassNews))
            {
                ViewBag.Error = "Password must contain at least 8 characters, including uppercase/lowercase and numbers";

                return(View("ChangePass", model));
            }

            var newPassword = PasswordGenerate(model.PassNews);

            model.PasswordHash = newPassword.Id;

            model.Salt = newPassword.Name;

            model.ModifiedDate = DateTime.Now;

            Db.UpdateOnly <ABUserAuth>(model, ev => ev.Update(p => new
            {
                p.PasswordHash,

                p.Salt,

                p.ModifiedDate
            }).Where(m => (m.Id == model.Id)));

            ViewBag.RedirectTo = Url.Action("Index", "User", new { });

            ViewBag.Message = "Change password success.";

            return(View("Message"));
        }
        public void SaveUserAuth(UserAuth user)
        {
            ABUserAuth userAuth = user.TranslateTo <ABUserAuth>();

            userAuth.ModifiedDate = DateTime.UtcNow;
            if (userAuth.CreatedDate == default(DateTime))
            {
                userAuth.CreatedDate = userAuth.ModifiedDate;
            }

            dbFactory.Run(db => db.Save(userAuth));
        }
Esempio n. 8
0
        public ActionResult GetNewPasswordSubmit(ABUserAuth model)
        {
            if (string.IsNullOrEmpty(model.PassNews) ||
                string.IsNullOrEmpty(model.ConfirmPassword))
            {
                ViewBag.Error = "Please enter all required fields.";

                return(View("GetNewPassword", model));
            }

            if (model.PassNews != model.ConfirmPassword)
            {
                ViewBag.Error = "Please enter same New password and Confirm password fields.";

                return(View("GetNewPassword", model));
            }

            var user = User_GetByID(model.Id);

            if (user == null || user.Email != model.Email)
            {
                ViewBag.Error = "Please don't try to hack us.";

                return(View("GetNewPassword", model));
            }

            var pass = PasswordGenerate(model.PassNews);

            user.PasswordHash = pass.Id;

            user.Salt = pass.Name;

            user.ModifiedDate = DateTime.Now;

            Db.UpdateOnly <ABUserAuth>(user, ev => ev.Update(p => new
            {
                p.PasswordHash,

                p.Salt,

                p.ModifiedDate
            }).Where(m => (m.Id == user.Id)));

            ViewBag.RedirectTo = Url.Action("SignIn", "Home", new { redirectTo = Url.Action("Index", "User", new { }) });

            ViewBag.Message = "Congratulations! Your account password has been changed successful.";

            return(View("Message"));
        }
        string RenderEmailBody(string content, MaillingListSendModel model, ABUserAuth user)
        {
            Hashtable tokens = new Hashtable();
            var       domain = Request.Url.Host;

            // prepare for the tokens
            // get current website information
            var site = Cache_GetWebSite();

            if (string.IsNullOrEmpty(site.Email_Admin))
            {
                site.Email_Admin = "";
            }

            if (string.IsNullOrEmpty(site.Email_Support))
            {
                site.Email_Support = "";
            }

            if (site.UseSSL)
            {
                domain = "https://" + domain + "/";
            }
            else
            {
                domain = "http://" + domain + "/";
            }

            tokens.Add("#website_domain", domain);
            tokens.Add("#website_name", site.Name);
            tokens.Add("#website_admin_email", site.Email_Admin);
            tokens.Add("#website_info_email", site.Email_Support);

            if (user != null)
            {
                if (string.IsNullOrEmpty(user.FullName))
                {
                    tokens.Add("#user_name", user.UserName);
                }
                else
                {
                    tokens.Add("#user_name", user.FullName);
                }

                tokens.Add("#user_username", user.UserName);
            }

            return(content);
        }
Esempio n. 10
0
        private void ValidateNewUser(ABUserAuth newUser, string password)
        {
            newUser.ThrowIfNull("newUser");
            password.ThrowIfNullOrEmpty("password");

            if (newUser.UserName.IsNullOrEmpty() && newUser.Email.IsNullOrEmpty())
            {
                throw new ArgumentNullException("UserName or Email is required");
            }

            if (!newUser.UserName.IsNullOrEmpty())
            {
                if (!ValidUserNameRegEx.IsMatch(newUser.UserName))
                {
                    throw new ArgumentException("UserName contains invalid characters", "UserName");
                }
            }
        }
Esempio n. 11
0
        public ActionResult Edit(int id)
        {
            UserModel model = new UserModel();
            List<ListModel> roles_lower = this.GetLowerRoles((RoleEnum)Enum.Parse(typeof(RoleEnum), CurrentUser.Roles[0]));
            ABUserAuth user = User_GetByID(id);
            if (user == null ||
                !roles_lower.Select(x => x.Id).Contains(user.Roles[0]) ||
                !(RoleEnum.Admin == (RoleEnum)Enum.Parse(typeof(RoleEnum), CurrentUser.Roles[0]) || user.MaHC.StartsWith(CurrentUser.MaHC != null ? CurrentUser.MaHC : "")))
            {
                return RedirectToAction("Index");
            }
            else
            {
                user.PasswordHash = "";
                UserModel.ToModel(user, ref model);
            }

            ViewData["RolesLower"] = roles_lower;
            return View("Add", model);
        }
Esempio n. 12
0
 private static void AssertNoExistingUser(IDbConnection db, ABUserAuth newUser, ABUserAuth exceptForExistingUser = null)
 {
     if (newUser.UserName != null)
     {
         var existingUser = GetUserAuthByUserName(db, newUser.UserName);
         if (existingUser != null &&
             (exceptForExistingUser == null || existingUser.Id != exceptForExistingUser.Id))
         {
             throw new ArgumentException("User {0} already exists".Fmt(newUser.UserName));
         }
     }
     if (newUser.Email != null)
     {
         var existingUser = GetUserAuthByUserName(db, newUser.Email);
         if (existingUser != null &&
             (exceptForExistingUser == null || existingUser.Id != exceptForExistingUser.Id))
         {
             throw new ArgumentException("Email {0} already exists".Fmt(newUser.Email));
         }
     }
 }
Esempio n. 13
0
 public static void ToEntity(UserModel model, ref ABUserAuth entity)
 {
     entity.Id           = model.Id;
     entity.FullName     = model.FullName;
     entity.DisplayName  = model.FullName;
     entity.UserName     = model.UserName;
     entity.Email        = model.Email;
     entity.PrimaryEmail = model.Email;
     entity.PasswordHash = model.Password;
     entity.ActiveStatus = model.Status;
     entity.CreatedDate  = model.DataCreate;
     entity.ModifiedDate = model.DateUpdate;
     entity.MailAddress  = model.Address;
     entity.PostalCode   = model.Zipcode;
     entity.Country      = model.Country;
     entity.BirthDate    = model.BirthDate;
     entity.Phone        = model.Phone;
     entity.Permissions  = model.Permission;
     entity.Gender       = model.Gender;
     entity.MaHC         = model.MaHC;
 }
Esempio n. 14
0
 public ActionResult Disable(int id)
 {
     try
     {
         string ma_hc = CurrentUser.MaHC != null ? CurrentUser.MaHC : "";
         List<string> roles_lower = this.GetLowerRoles((RoleEnum)Enum.Parse(typeof(RoleEnum), CurrentUser.Roles[0])).Select(x => string.Format("[{0}]", x.Id)).ToList();
         ABUserAuth user = Db.Select<ABUserAuth>(x => x.Where(y => Sql.In(y.Roles, roles_lower) && (RoleEnum.Admin == (RoleEnum)Enum.Parse(typeof(RoleEnum), CurrentUser.Roles[0]) || y.MaHC.StartsWith(ma_hc)) && y.Id == id).Limit(0, 1)).FirstOrDefault();
         if (user == null)
         {
             return JsonError("Vui lòng không hack ứng dụng.");
         }
         if (user.ActiveStatus)
         {
             user.ActiveStatus = false;
             Db.Update(user);
         }
     }
     catch (Exception ex)
     {
         return JsonError(ex.Message);
     }
     return Json(null, JsonRequestBehavior.AllowGet);
 }
Esempio n. 15
0
        public UserAuth UpdateUserAuth(UserAuth eUser, UserAuth nUser, string password)
        {
            // cast to our table
            ABUserAuth existingUser = eUser.TranslateTo <ABUserAuth>();
            ABUserAuth newUser      = nUser.TranslateTo <ABUserAuth>();

            ValidateNewUser(newUser, password);

            return(dbFactory.Run(db =>
            {
                AssertNoExistingUser(db, newUser, existingUser);

                var hash = existingUser.PasswordHash;
                var salt = existingUser.Salt;
                if (password != null)
                {
                    passwordHasher.GetHashAndSaltString(password, out hash, out salt);
                }
                // If either one changes the digest hash has to be recalculated
                var digestHash = existingUser.DigestHa1Hash;
                if (password != null || existingUser.UserName != newUser.UserName)
                {
                    var digestHelper = new DigestAuthFunctions();
                    digestHash = digestHelper.CreateHa1(newUser.UserName, DigestAuthProvider.Realm, password);
                }
                newUser.Id = existingUser.Id;
                newUser.PasswordHash = hash;
                newUser.Salt = salt;
                newUser.DigestHa1Hash = digestHash;
                newUser.CreatedDate = existingUser.CreatedDate;
                newUser.ModifiedDate = DateTime.UtcNow;

                db.Save(newUser);

                return newUser.TranslateTo <UserAuth>();
            }));
        }
Esempio n. 16
0
 public static void ToModel(ABUserAuth entity, ref UserModel model)
 {
     model.Id         = entity.Id;
     model.FullName   = entity.FullName;
     model.FirstName  = entity.FirstName;
     model.LastName   = entity.LastName;
     model.UserName   = entity.UserName;
     model.Email      = entity.Email;
     model.Password   = entity.PasswordHash;
     model.Status     = entity.ActiveStatus;
     model.DataCreate = entity.CreatedDate;
     model.DateUpdate = entity.ModifiedDate;
     model.Address    = entity.MailAddress;
     model.Zipcode    = entity.PostalCode;
     model.Country    = entity.Country;
     model.RoleName   = entity.Roles;
     model.rolesId    = entity.Roles.ToArray();
     model.BirthDate  = entity.BirthDate;
     model.Phone      = entity.Phone;
     model.Permission = entity.Permissions;
     model.Gender     = entity.Gender;
     model.Avatar     = entity.Nickname;
     model.MaHC       = entity.MaHC;
 }
Esempio n. 17
0
        public ActionResult Profile(ABUserAuth model, IEnumerable <HttpPostedFileBase> FileUps)
        {
            if (string.IsNullOrEmpty(model.FirstName) ||
                string.IsNullOrEmpty(model.LastName) ||
                string.IsNullOrEmpty(model.FullName) ||
                string.IsNullOrEmpty(model.Country) ||
                string.IsNullOrEmpty(model.MaHC) ||
                string.IsNullOrEmpty(model.PostalCode) ||
                string.IsNullOrEmpty(model.Phone) ||
                string.IsNullOrEmpty(model.Gender) ||
                string.IsNullOrEmpty(model.Email))
            {
                ViewBag.Error = "Please enter all required fields.";

                return(View("Profile", model));
            }

            // get the country
            var c = Db.Select <Country>(x => x.Where(m => m.Code == model.Country).Limit(1)).FirstOrDefault();

            if (c == null)
            {
                ViewBag.Error = "Your selected country is not found";
                return(View("Profile", model));
            }

            // validate the phone number
            if (!IsValidPhoneByCountry(model.Phone, c.Code, true))
            {
                ViewBag.Error = "We can not validate your phone number with your selected country.";
                return(View("Profile", model));
            }

            if (!IsValidEmailAddress(model.Email))
            {
                ViewBag.Error = "We can not validate your email address format.";
                return(View("Profile", model));
            }

            model.Nickname = (FileUps != null && FileUps.Count() != 0 && FileUps.First() != null) ? UploadFile(model.Id, model.UserName, "", FileUps) : CurrentUser.Nickname;
            model.UserName = model.Email;

            model.ModifiedDate = DateTime.Now;

            Db.UpdateOnly <ABUserAuth>(model, ev => ev.Update(p => new {
                p.FirstName,
                p.LastName,
                p.FullName,
                p.Country,
                p.MaHC,
                p.PostalCode,
                p.Phone,
                p.Gender,
                p.BirthDate,
                p.Nickname,
                p.ModifiedDate,
                p.Email,
                p.UserName
            }).Where(m => (m.Id == CurrentUser.Id)).Limit(1));

            ViewBag.RedirectTo = Url.Action("Index", "User", new { });

            ViewBag.Message = "Update profile success.";

            return(View("Message"));
        }
Esempio n. 18
0
        /// <summary>
        /// this function will do a inital for all tables
        /// </summary>
        public static void InitDbTable(string user, bool GainPermission = false, bool support_schema = false)
        {
            var dbConn = BasicModelBase.ServiceAppHost.TryResolve <IDbConnection>();

            #region DanhMuc
            if (support_schema)
            {
                CreateSchemaIfNotExists(dbConn, "DanhMuc", GainPermission, user);
            }
            dbConn.CreateTableIfNotExists <DanhMuc_HanhChinh>();
            #endregion

            #region CMS
            if (support_schema)
            {
                CreateSchemaIfNotExists(dbConn, "System", GainPermission, user);
                CreateSchemaIfNotExists(dbConn, "CMS", GainPermission, user);
            }
            // User Management
            dbConn.CreateTableIfNotExists <ABUserAuth>();
            dbConn.CreateTableIfNotExists <ABUserOAuthProvider>();
            dbConn.CreateTableIfNotExists <UsersActivation>();

            // language
            dbConn.CreateTableIfNotExists <Language>();

            // for sites
            dbConn.CreateTableIfNotExists <Website>();
            dbConn.CreateTableIfNotExists <Site_ContactusConfig>(); //dbConn.CreateTable<Site_ContactusConfig>(overwrite: true);
            //dbConn.CreateTableIfNotExists<Site_Lang_Dis>();
            dbConn.CreateTableIfNotExists <Site_MemberGroup>();
            dbConn.CreateTableIfNotExists <Site_MemberGroupDetail>();
            dbConn.CreateTableIfNotExists <SiteTopic>();
            dbConn.CreateTableIfNotExists <SiteTopicLanguage>();
            dbConn.CreateTableIfNotExists <SiteSetting>();
            dbConn.CreateTableIfNotExists <Settings>();
            dbConn.CreateTableIfNotExists <SiteNewsletter>();
            dbConn.CreateTableIfNotExists <Site_MaillingListTemplate>();
            dbConn.CreateTableIfNotExists <Site_ContactUs>();
            dbConn.CreateTableIfNotExists <Testimonial>();
            dbConn.CreateTableIfNotExists <SocialAccount>();
            dbConn.CreateTableIfNotExists <Site_Banner>();
            dbConn.CreateTableIfNotExists <Site_FlashHeader>();

            // navigation
            dbConn.CreateTableIfNotExists <Navigation>();

            // news
            dbConn.CreateTableIfNotExists <Site_News_Category>();
            dbConn.CreateTableIfNotExists <Site_News>();

            // blog
            dbConn.CreateTableIfNotExists <Site_Blog_Category>();
            dbConn.CreateTableIfNotExists <Site_Blog>();

            // system
            dbConn.CreateTableIfNotExists <Country>();
            dbConn.CreateTableIfNotExists <Theme>();
            dbConn.CreateTableIfNotExists <Language_Translation>();
            dbConn.CreateTableIfNotExists <MailQueue>();
            dbConn.CreateTableIfNotExists <Exceptions>();
            #endregion

            #region SMS
            if (support_schema)
            {
                CreateSchemaIfNotExists(dbConn, "SMS", GainPermission, user);
            }
            dbConn.CreateTableIfNotExists <SMSTemplateModel>();
            #endregion

            #region Products & Category
            if (support_schema)
            {
                CreateSchemaIfNotExists(dbConn, "Products", GainPermission, user);
            }
            dbConn.CreateTableIfNotExists <Product_Category>(); /* dbConn.CreateTable<Product_Category>(overwrite:true); */
            dbConn.CreateTableIfNotExists <Product>();
            dbConn.CreateTableIfNotExists <Product_Images>();
            dbConn.CreateTableIfNotExists <ProductCategoryImage>();
            dbConn.CreateTableIfNotExists <ProductCategoryMaterial>();
            dbConn.CreateTableIfNotExists <ProductCategoryMaterialDetail>();

            // product price
            dbConn.CreateTableIfNotExists <Price>();

            // option
            dbConn.CreateTableIfNotExists <Product_Option>();
            dbConn.CreateTableIfNotExists <OptionInProduct>();

            // Payment
            dbConn.CreateTableIfNotExists <PayPalStandardPaymentSettings>();

            // Coupon
            dbConn.CreateTableIfNotExists <CouponPromo>();

            // order
            dbConn.CreateTableIfNotExists <AddressModel>();
            dbConn.CreateTableIfNotExists <Order>();
            dbConn.CreateTableIfNotExists <Order_History>();
            dbConn.CreateTableIfNotExists <Order_ProductOptionUsing>();
            dbConn.CreateTableIfNotExists <Order_ProductionJobSheet>();
            dbConn.CreateTableIfNotExists <Order_UploadFilesTicket>();

            // extra shipping
            dbConn.CreateTableIfNotExists <Country_State_ExtraShipping>();
            #endregion

            #region Report
            if (support_schema)
            {
                CreateSchemaIfNotExists(dbConn, "Reports", GainPermission, user);
            }
            dbConn.CreateTableIfNotExists <StaffActivity>();
            #endregion

            #region Extra Shipping

            #endregion

            #region Init System
            if (dbConn.Count <ABUserAuth>(m => m.ActiveStatus) == 0)
            {
                // add default user
                ABUserAuth u = new ABUserAuth()
                {
                    UserName = "******", ActiveStatus = true, CreatedDate = DateTime.Now, DisplayName = "Trung Click4Corp", Email = "*****@*****.**", FirstName = "Imm", LastName = "Dang", FullName = "Imm Dang", Gender = "Male", Language = "EN", Roles = new global::System.Collections.Generic.List <string>()
                };

                var    PasswordHasher = new SaltedHash();
                string salt;
                string hash;
                PasswordHasher.GetHashAndSaltString("123absoft.vn", out hash, out salt);
                u.PasswordHash = hash;
                u.Salt         = salt;
                u.Roles.Add(RoleEnum.Administrator.ToString());
                dbConn.Insert <ABUserAuth>(u);
                u.Id = (int)dbConn.GetLastInsertId();

                if (dbConn.Count <Website>() == 0)
                {
                    Website w = new Website()
                    {
                        CreatedBy = u.Id, CreatedOn = DateTime.Now, Domain = new global::System.Collections.Generic.List <string>(), Name = "ABSoft CMS Site"
                    };
                    w.Domain.Add("localhost");
                    dbConn.Insert <Website>(w);
                }
            }
            #endregion
        }
Esempio n. 19
0
 public bool CurrentUser_HasRole(RoleEnum role, ABUserAuth current_user = null)
 {
     return(CurrentUser_HasRole(role.ToString(), current_user));
 }
Esempio n. 20
0
        public ActionResult UpdateUser(UserModel model, IEnumerable<HttpPostedFileBase> FileUp)
        {
            ViewData["RolesLower"] = this.GetLowerRoles((RoleEnum)Enum.Parse(typeof(RoleEnum), CurrentUser.Roles[0])); ;

            #region VALIDATION: #1
            ABUserAuth user = new ABUserAuth();
            if (model.Id > 0) { user = User_GetByID(model.Id); }
            if (user == null)
            {
                ViewBag.Error = "Vui lòng không hack ứng dụng.";
                return View("Add", model);
            }

            string ma_hc = CurrentUser.MaHC != null ? CurrentUser.MaHC : "";
            List<string> roles_lower = this.GetLowerRoles((RoleEnum)Enum.Parse(typeof(RoleEnum), CurrentUser.Roles[0])).Select(x => string.Format("[{0}]", x.Id)).ToList();
            if (user.Id > 0 &&
                (!roles_lower.Contains(string.Format("[{0}]", user.Roles[0])) ||
                 !(RoleEnum.Admin == (RoleEnum)Enum.Parse(typeof(RoleEnum), CurrentUser.Roles[0]) || user.MaHC.StartsWith(ma_hc))))
            {
                ViewBag.Error = "Vui lòng không hack ứng dụng.";
                return View("Add", model);
            }
            if (!(roles_lower.Contains(string.Format("[{0}]", model.rolesId[0])) &&
                  (RoleEnum.Admin == (RoleEnum)Enum.Parse(typeof(RoleEnum), CurrentUser.Roles[0]) || model.MaHC.StartsWith(ma_hc)) &&
                  Db.Count<DanhMuc_HanhChinh>(x => x.MaHC == model.MaHC) > 0))
            {
                ViewBag.Error = "Vui lòng không hack ứng dụng.";
                return View("Add", model);
            }
            #endregion

            #region VALIDATION: #2
            if (user.Id > 0 && string.IsNullOrEmpty(model.NameAddUser)) { model.UserName = user.UserName; }
            if (user.Id > 0 && string.IsNullOrEmpty(model.EmailChange)) { model.Email = user.Email; }
            if (string.IsNullOrEmpty(model.UserName) || string.IsNullOrEmpty(model.UserName.Trim()))
            {
                ViewBag.Error = "Vui lòng nhập tài khoản.";
                return View("Add", model);
            }
            if (user.Id <= 0)
            {
                if (string.IsNullOrEmpty(model.Password))
                {
                    ViewBag.Error = "Vui lòng nhập mật khẩu.";
                    return View("Add", model);
                }
                else if (!new Regex(@"(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}$", RegexOptions.Compiled).IsMatch(model.Password))
                {
                    ViewBag.Error = "Mật khẩu chứa ít nhất 8 ký tự, bao gồm ký tự hoa/ký tự thường/ký tự số.";
                    return View("Add", model);
                }
            }
            if (!string.IsNullOrEmpty(model.PassNews))
            {
                if (!new Regex(@"(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}$", RegexOptions.Compiled).IsMatch(model.PassNews))
                {
                    ViewBag.Error = "Mật khẩu (mới) chứa ít nhất 8 ký tự, bao gồm ký tự hoa/ký tự thường/ký tự số.";
                    return View("Add", model);
                }
                model.Password = model.PassNews;
            }
            if (user.Id == 0)
            {
                model.PassNews = model.Password;
            }
            if (string.IsNullOrEmpty(model.Email) || !IsValidEmailAddress(model.Email))
            {
                ViewBag.Error = "Email không đúng định dạng.";
                return View("Add", model);
            }
            if (string.IsNullOrEmpty(model.FullName))
            {
                ViewBag.Error = "Vui lòng nhập họ & tên.";
                return View("Add", model);
            }
            #endregion

            #region VALIDATION: #3
            if (user.Id <= 0 && User_GetByUsername(model.UserName) != null)
            {
                ViewBag.Error = "Tài khoản đã được sử dụng.";
                return View("Add", model);
            }
            if (user.Id > 0 && !string.IsNullOrEmpty(model.NameAddUser))
            {
                if (!model.UserName.Equals(model.NameAddUser) && User_GetByUsername(model.NameAddUser) != null)
                {
                    ViewBag.Error = "Tài khoản (mới) đã được sử dụng.";
                    return View("Add", model);
                }
                else
                {
                    model.UserName = model.NameAddUser;
                }
            }
            if (user.Id <= 0 && User_GetByEmail(model.Email) != null)
            {
                ViewBag.Error = "Email đã được sử dụng.";
                return View("Add", model);
            }
            if (user.Id > 0 && !string.IsNullOrEmpty(model.EmailChange))
            {
                if (!IsValidEmailAddress(model.EmailChange))
                {
                    ViewBag.Error = "Email (mới) không đúng định dạng.";
                    return View("Add", model);
                }
                if (!model.Email.Equals(model.EmailChange) && User_GetByEmail(model.EmailChange) != null)
                {
                    ViewBag.Error = "Email (mới) đã được sử dụng.";
                    return View("Add", model);
                }
                else
                {
                    model.Email = model.EmailChange;
                }
            }
            #endregion
            
            if (user.Id <= 0)
            {
                model.DataCreate = DateTime.Now;
                model.DateUpdate = DateTime.Now;
            }
            else
            {
                model.DataCreate = user.CreatedDate;
                model.DateUpdate = DateTime.Now;
                model.Avatar = user.Avatar;
            }
            model.RoleName = model.rolesId.ToList();
            model.Password = user.PasswordHash;
            UserModel.ToEntity(model, ref user);
            user.Roles = model.RoleName;
            user.Permissions = model.Permission;
            user.FirstName = model.FirstName;
            user.LastName = model.LastName;
            user.FullName = string.IsNullOrEmpty(model.FullName) ? string.Format("{0} {1}", model.FirstName, model.LastName) : model.FullName;
            user.DisplayName = user.FullName;
            user.Email = model.Email;
            user.UserName = model.UserName;
            user.Gender = model.Gender;
            user.BirthDate = model.BirthDate;
            user.BirthDateRaw = "";
            if (user.BirthDate.HasValue)
            {
                user.BirthDateRaw = user.BirthDate.Value.ToString("MM/dd/yyyy");
            }
            user.MailAddress = model.Address;
            user.Phone = model.Phone;
            user.PostalCode = model.Zipcode;
            user.Country = model.Country;
            user.ActiveStatus = model.Status;
            user.CreatedDate = model.DataCreate;
            user.ModifiedDate = model.DateUpdate;

            if (FileUp != null && FileUp.Count() > 0 && FileUp.First() != null)
                user.Avatar = UploadFile(user.Id, user.UserName, "", FileUp);

            if (!string.IsNullOrEmpty(model.PassNews))
            {
                var p = PasswordGenerate(model.PassNews);
                user.PasswordHash = p.Id;
                user.Salt = p.Name;
            }

            if (model.Id > 0)
            {
                Db.Update<ABUserAuth>(user);
            }
            else
            {
                Db.Insert<ABUserAuth>(user);
            }
            return RedirectToAction("Index");
        }
Esempio n. 21
0
        public ActionResult History_LoadNext(long id, int page)
        {
            var order = Db.Select <Order>(m => m.Where(x => x.Id == id).Limit(1)).FirstOrDefault();

            if (order == null)
            {
                return(RedirectToAction("Index"));
            }

            int page_size = 9;

            // update the new message flag when page 1 only, because we list the new message first
            if (page == 1 && order.FlagHistoryMessage == (int)Enum_FlagOrderMessage.NewMessageFromPhotobookmart)
            {
                order.AddHistory("Customer read messages from Photobookmart", "System", 0, true);
                // update order to let them know we have new message from customer
                Db.UpdateOnly <Order>(new Order()
                {
                    FlagHistoryMessage = (int)Enum_FlagOrderMessage.No_NewMessage
                },
                                      ev => ev.Update(p => new
                {
                    p.FlagHistoryMessage
                }).Where(m => m.Id == order.Id));
            }

            // count fist
            var count = (int)Db.Count <Order_History>(x => x.Order_Id == id && x.isPrivate == false);
            var pages = count / page_size;

            if (count % page_size > 0)
            {
                pages++;
            }

            var ret   = Db.Select <Order_History>(x => x.Where(m => m.Order_Id == id && m.isPrivate == false).OrderByDescending(k => k.OnDate).Limit((page - 1) * page_size, page_size));
            var users = Db.Select <ABUserAuth>();

            // get user who submit order
            var order_user = users.Where(x => x.Id == order.Customer_Id).FirstOrDefault();

            if (order_user == null)
            {
                order_user = new ABUserAuth();
            }
            foreach (var item in ret)
            {
                // check usertype and avatar
                item.UserAvatar = "";
                if (item.UserId == order_user.Id)
                {
                    item.Direction  = "left";
                    item.UserAvatar = order_user.Avatar;
                    item.UserName   = "******";
                }
                else
                {
                    // system or staff
                    item.Direction  = "right";
                    item.UserAvatar = "Content/default_system_orderhistory_logo.png";
                    //
                    var u = users.Where(x => x.Id == item.UserId).FirstOrDefault();
                    if (u != null)
                    {
                        item.UserName   = string.Format("{0} {1}", u.FirstName, u.LastName);
                        item.UserAvatar = u.Avatar;
                        // incase this user does not have avatar
                        if (string.IsNullOrEmpty(item.UserAvatar))
                        {
                            item.UserAvatar = "content/default_chat_avatar.png";
                        }
                    }
                }

                // date format
                var dif = (int)DateTime.Now.Subtract(item.OnDate).TotalMinutes;
                if (dif < 2)
                {
                    item.OnDateFormat = "Now";
                }
                else if (dif < 60)
                {
                    item.OnDateFormat = string.Format("{0} minutes ago", dif);
                }
                else if (dif <= 60 * 8) // 8 hours
                {
                    dif = dif / 60;
                    item.OnDateFormat = string.Format("About {0} hours ago", dif);
                }
                else
                {
                    item.OnDateFormat = string.Format("{0:dddd, MMMM dd, yyyy HH:mm:ss}", item.OnDate);
                }
            }

            Db.Close();
            if (ret.Count == 0)
            {
                return(Content(""));
            }
            else
            {
                return(PartialView(ret));
            }
        }
Esempio n. 22
0
        public ActionResult RegisterSubmit(ABUserAuth model)
        {
            if (String.IsNullOrEmpty(model.Email) ||
                String.IsNullOrEmpty(model.Password) ||
                String.IsNullOrEmpty(model.ConfirmPassword) ||
                String.IsNullOrEmpty(model.FirstName) ||
                String.IsNullOrEmpty(model.LastName) ||
                String.IsNullOrEmpty(model.Country) ||
                String.IsNullOrEmpty(model.MaHC) ||
                String.IsNullOrEmpty(model.PostalCode) ||
                String.IsNullOrEmpty(model.Phone))
            {
                ViewBag.Error = "Please enter all required fields.";

                return(View("Register", model));
            }

            // get the country
            var c = Db.Select <Country>(x => x.Where(m => m.Code == model.Country).Limit(1)).FirstOrDefault();

            if (c == null)
            {
                ViewBag.Error = "Your selected country is not found";
                return(View("Register", model));
            }

            // validate the phone number
            if (!IsValidPhoneByCountry(model.Phone, c.Code, true))
            {
                ViewBag.Error = "We can not validate your phone number with your selected country.";
                return(View("Register", model));
            }

            if (!IsValidEmailAddress(model.Email))
            {
                ViewBag.Error = "We can not validate your email address format.";
                return(View("Register", model));
            }

            if (model.Password != model.ConfirmPassword)
            {
                ViewBag.Error = "Please enter same Password and Re password fields.";

                return(View("Register", model));
            }

            if (!new Regex(@"(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}$", RegexOptions.Compiled).IsMatch(model.Password))
            {
                ViewBag.Error = "Password must contain at least 8 characters, including uppercase/lowercase and numbers";

                return(View("Register", model));
            }

            //if (!captchaValid)
            //{
            //    ViewBag.Error = "Your captcha is not match.";

            //    return View("Register", model);
            //}

            if (User_GetByEmail(model.Email) != null)
            {
                ViewBag.Error = "There is an user with same Email as you entered. Please use difference Email.";

                return(View("Register", model));
            }

            if (User_GetByUsername(model.UserName) != null)
            {
                ViewBag.Error = "There is an user with same Username as you entered. Please use difference Username.";

                return(View("Register", model));
            }

            var p = PasswordGenerate(model.Password);

            ABUserAuth user = new ABUserAuth()
            {
                Email    = model.Email,
                UserName = model.Email,
                Roles    = new List <string>()
                {
                    RoleEnum.Customer.ToString()
                },
                PasswordHash  = p.Id,
                Salt          = p.Name,
                FirstName     = model.FirstName,
                LastName      = model.LastName,
                Country       = model.Country,
                MaHC          = model.MaHC,
                PostalCode    = model.PostalCode,
                Phone         = model.Phone,
                DigestHa1Hash = encrypt.GetMD5HashData(model.Email),
                CreatedDate   = DateTime.Now,
                ActiveStatus  = true,
            };

            user.FullName    = user.FirstName + " " + user.LastName;
            user.DisplayName = user.FullName;

            try
            {
                Db.Insert <ABUserAuth>(user);

                user.Id = (int)Db.GetLastInsertId();

                var template = Get_MaillingListTemplate("register_notify_user");

                var template_helper = new EmailHelper(template.Title, template.Body);

                template_helper.Parameters.Add("Host", CurrentWebsite.Domain.First());

                template_helper.Parameters.Add("User", user.UserName);

                template_helper.Parameters.Add("Code", user.DigestHa1Hash);

                template_helper.Sender_Email = CurrentWebsite.Email_Support;

                template_helper.Sender_Name = CurrentWebsite.Name;

                template_helper.Receiver.Add(user.Email);

                SendMail(template_helper);

                template = Get_MaillingListTemplate("register_notify_admin");

                template_helper = new EmailHelper(template.Title, template.Body);

                template_helper.Parameters.Add("Host", InternalService.CurrentWebsiteDomainURL);

                template_helper.Parameters.Add("Id", user.Id.ToString());

                template_helper.Parameters.Add("User", user.UserName);

                template_helper.Parameters.Add("Email", user.Email);

                template_helper.Parameters.Add("Date", DateTime.Now.ToString());

                template_helper.Sender_Email = CurrentWebsite.Email_Support;

                template_helper.Sender_Name = CurrentWebsite.Name;

                template_helper.Receiver.Add(CurrentWebsite.Email_Admin);

                SendMail(template_helper);

                ViewBag.Message = "Your Account has been created! We just sent to you one email to confirm your account information. Please make sure to check your spam folder in your mail box. <br>Photobookmart also login for you automatically. Enjoy...";

                // do the auto login
                //return SignInSubmit(new LoginModel() { CheckRemember = true, Pass = model.Password, RedirectTo = model.RedirectTo, UserName = model.UserName });
                var authResponse = AuthService.Post(new Auth
                {
                    UserName = model.Email,
                    Password = model.Password,
                    Continue = ""
                });
            }
            catch (Exception ex)
            {
                ViewBag.RedirectTo = Url.Action("Register", "User", new { });

                ViewBag.Message = string.Format("{0}: {1}.", "There was an error when registering", ex.Message);
            }

            if (!string.IsNullOrEmpty(model.RedirectTo))
            {
                //ViewBag.RedirectTo = Url.Action("SignIn", new { redirectTo = model.RedirectTo });
                ViewBag.RedirectTo = model.RedirectTo;
            }
            else
            {
                //ViewBag.RedirectTo = Url.Action("SignIn");
                ViewBag.RedirectTo = "/";
            }
            return(View("Message"));
        }
Esempio n. 23
0
        public ActionResult ForgotPassword()
        {
            var model = new ABUserAuth();

            return(View("ForgotPassword", model));
        }