Пример #1
0
        public ActionResult ChangePassword(AccountModels.ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {

                // ChangePassword will throw an exception rather
                // than return false in certain failure scenarios.
                bool changePasswordSucceeded;
                try
                {
                    MembershipUser currentUser = Membership.GetUser(User.Identity.Name, true /* userIsOnline */);
                    changePasswordSucceeded = currentUser.ChangePassword(model.OldPassword, model.NewPassword);
                }
                catch (Exception)
                {
                    changePasswordSucceeded = false;
                }

                if (changePasswordSucceeded)
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
Пример #2
0
        public ActionResult LogOn(AccountModels.LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (Membership.ValidateUser(model.UserName, model.Password))
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
Пример #3
0
        public ActionResult Login(AccountModels.LoginModel model)
        {
            var found = _context.Set<User>().FirstOrDefault(x => x.Name == model.Username);
            if (found == null)
                ModelState.AddModelError("Name", "Invalid user or password");

            if (ModelState.IsValid)
            {
                if (!Hash.ValidatePassword(model.Password, found.Password))
                    ModelState.AddModelError("Name", "Invalid user or password");

                FormsAuthentication.SetAuthCookie(model.Username, model.RememberMe);
                return RedirectToAction("Index", "Home");
            }
            return View(model);
        }
Пример #4
0
 public ActionResult CreateAccount(AccountModels.RegisterModel model)
 {
     var context = DependencyResolver.Current.GetService<DbContext>();
     if (ModelState.IsValid)
     {
         var user = new User()
         {
             Name = model.Username,
             Password = Hash.CreateHash(model.Password),
             Email = model.Email
         };
         context.Set<User>().Add(user);
         context.SaveChanges();
         FormsAuthentication.SetAuthCookie(model.Username, true);
         return RedirectToAction("Index", "Home");
     }
     return View(model);
 }
Пример #5
0
        public ActionResult Register(RegisterDto registerDto)
        {
            if (!ModelState.IsValid)
            {
                return(View(registerDto));
            }

            var subject = "Welcome to our website!";
            var code    = new AccountModels().RandomString(10);
            var content = "Hi " + registerDto.Name + "!. Your account has is successfully created. You need to confirm your email. Your password is: " + code;

            var result = Register(registerDto.AccountType, registerDto.Name, registerDto.PhoneNumber, registerDto.Email, registerDto.Username, registerDto.Address, code);

            if (result)
            {
                var sendMail = SendMail(registerDto.Email, subject, content);
                ViewBag.Success = true;
                return(View(registerDto));
            }

            return(View(registerDto));
        }
Пример #6
0
        public async Task <ActionResult> ResetPassword(AccountModels model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            var user = await _authManager.FindByNameAsync(model.ResetPasswordViewModel.Email);

            if (user == null)
            {
                // Don't reveal that the user does not exist
                return(RedirectToAction("ResetPasswordConfirmation", "Account"));
            }
            var result = await _authManager.ResetPasswordAsync(user.Id, model.ResetPasswordViewModel.Code, model.ResetPasswordViewModel.Password);

            if (result.Succeeded)
            {
                return(RedirectToAction("ResetPasswordConfirmation", "Account"));
            }
            AddErrors(result);
            return(View());
        }
Пример #7
0
 public ActionResult Login(AccountModels model, string returnUrl)
 {
     if (ModelState.IsValid)
     {
         if (Session["VerificationCode"] == null || Session["VerificationCode"].ToString() != model.VerificationCode)
         {
             ModelState.AddModelError("VerificationCode", "验证码错误,请重新输入");
         }
         else
         {
             var userData = _UserInfoService.GetWhere(m => m.LoginName == model.UserName && m.IsLock == false).FirstOrDefault();
             if (FormsAuthentication.Authenticate(model.UserName, model.PassWord))
             {
                 SetCookie(model, userData);
                 return(RedirectToUrl(returnUrl));
             }
             else
             {
                 if (userData != null)
                 {
                     if (userData.LoginPwd == StringEncryptionHelp.Md5Encrypt(model.PassWord))
                     {
                         SetCookie(model, userData);
                         return(RedirectToUrl(returnUrl));
                     }
                     else
                     {
                         ModelState.AddModelError("PassWord", "别瞎登录,密码不对");
                     }
                 }
                 else
                 {
                     ModelState.AddModelError("UserName", "sb,没有这个用户");
                 }
             }
         }
     }
     return(View(model));
 }
Пример #8
0
 public ActionResult pay2048(AccountModels accountModels)
 {
     if (Session["has_pay"] != null && accountModels.address_text != null)
     {
         Session.Remove("has_pay");
         accountModels.score = 0;
         for (int i = 0; i < accountModels.accountModeList.Count; ++i)
         {
             accountModels.all_price += accountModels.accountModeList[i].total_price;
         }
         accountModels.all_price = accountModels.all_price / 100 + accountModels.all_price;
         return(View(accountModels));
     }
     if (accountModels.address_text == null)
     {
         return(RedirectToAction("order_fail"));
     }
     else
     {
         return(Redirect("/PurchaseList"));
     }
 }
Пример #9
0
        public async Task <AccountModels> RegisterAsync(AccountModels account)
        {
            AccountEntity dalAccount = _mapper.Map <AccountEntity>(account);

            bool duplicate = await _accountRepository.CheckDuplicateAsync(dalAccount);

            if (duplicate)
            {
                return(null);
            }

            if (account.Password != null)
            {
                byte[] saltForNewAccount = PasswordHasher.GenerateSalt();
                dalAccount.Salt         = saltForNewAccount;
                dalAccount.PasswordHash = PasswordHasher.GenerateHash(account.Password, saltForNewAccount);
            }

            AccountEntity newAccount = await _accountRepository.CreateAccountAsync(dalAccount);

            return(_mapper.Map <AccountModels>(newAccount));
        }
Пример #10
0
 public ActionResult order_success(AccountModels accountModels)
 {
     if (accountModels.score >= accountModels.all_price)
     {
         Session.Remove("has_pay");
         ShopBusinessLogic.MemberPurchase memberPurchase = new ShopBusinessLogic.MemberPurchase();
         var      account_list = accountModels.accountModeList;
         string   mem_phone    = Session["mem_phone"].ToString();
         DateTime now_time     = DateTime.Now;
         for (int i = 0; i < account_list.Count; ++i)
         {
             var now_plist_id = now_time.ToString("yyyyMMddHHmmssfff") + mem_phone;
             memberPurchase.addPurchaseLists(now_plist_id, mem_phone, account_list[i].goods_id, account_list[i].goods_num, now_time);
             memberPurchase.deletePurchaseCar(mem_phone, account_list[i].goods_id);
         }
         return(View(accountModels));
     }
     else
     {
         return(Redirect("/PurchaseCar"));
     }
 }
Пример #11
0
        public async Task <ActionResult> ForgotPassword(AccountModels model)
        {
            if (ModelState.IsValid)
            {
                var user = await _authManager.FindByNameAsync(model.ForgotPasswordViewModel.Email);

                if (user == null || !(await _authManager.IsEmailConfirmedAsync(user.Id)))
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    return(View("ForgotPasswordConfirmation"));
                }

                // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                // Send an email with this link
                // string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
                // var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                // await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>");
                // return RedirectToAction("ForgotPasswordConfirmation", "Account");
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Пример #12
0
        public async Task <ActionResult> ChangePassword(AccountModels model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            var result = await _authManager.ChangePasswordAsync(User.Identity.GetUserId(), model.ChangePasswordViewModel.OldPassword, model.ChangePasswordViewModel.NewPassword);

            if (result.Succeeded)
            {
                var user = await _authManager.FindByIdAsync(User.Identity.GetUserId());

                if (user != null)
                {
                    await _authManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);
                }
                //todo: translate
                this.AddToastMessage("Success", "You successfully changed your password", ToastType.Success);
                return(View());
            }
            AddErrors(result);
            return(View(model));
        }
Пример #13
0
 public ActionResult ResetPassword(ResetPassWordModel model)
 {
     if (ModelState.IsValid)
     {
         string strCMND = model.CMND;
         string strSrv  = model.Server;
         AuthConfig.ConnectionAuth(strSrv);
         AccountModels acc  = new AccountModels();
         ADUsersInfo   user = acc.GetEmployeeUserByIDNumber(strCMND);
         if (user == null)
         {
             ModelState.AddModelError("ResetPasswordFaild", "The CMND provided is incorrect.");
         }
         else
         {
             AuthConfig.SetSession("UserName", user.ADUserName);
             return(Redirect("ChangePassword"));
         }
     }
     ViewBag.Title      = Properties.Settings.Default.WebTitle;
     ViewData["lstSrv"] = new LoginModel().InitCompanys();
     return(View(model));
 }
Пример #14
0
        public ActionResult Delete(AccountModels ad)
        {
            string phone = Session["mem_phone"].ToString();

            ShopBusinessLogic.LoginMember loginMember = new ShopBusinessLogic.LoginMember();
            string delete_address     = ad.address;
            string delete_address_tag = ad.address_tag;

            loginMember.DeleteMemberAddress(phone, delete_address, delete_address_tag);
            var address_list = loginMember.ShowMemberAddress(Session["mem_phone"].ToString()).Select(address_info => new MemberAddress()
            {
                address     = address_info.address,
                address_tag = address_info.address_tag,
            }).ToList();
            var resView = new AccountModels()
            {
                accountModeList = ad.accountModeList,
                mem_phone       = Session["mem_phone"].ToString(),
                addresses       = address_list,
                all_price       = ad.all_price,
            };

            return(PartialView("AccountPart1", resView));
        }
Пример #15
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = model.Email, Email = model.Email
                };
                var result = await UserManager.CreateAsync(user, model.Password);

                // Own Account Table
                ProjectDbContext db         = new ProjectDbContext();
                AccountModels    newAccount = new AccountModels();
                newAccount.Account_email     = model.Email;
                newAccount.AccountData       = new AccountData();
                newAccount.AccountData.Email = model.Email;
                db.Users.Add(newAccount);
                db.SaveChanges();

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

                    // Aby uzyskać więcej informacji o sposobie włączania potwierdzania konta i resetowaniu hasła, odwiedź stronę https://go.microsoft.com/fwlink/?LinkID=320771
                    // Wyślij wiadomość e-mail z tym łączem
                    // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    // await UserManager.SendEmailAsync(user.Id, "Potwierdź konto", "Potwierdź konto, klikając <a href=\"" + callbackUrl + "\">tutaj</a>");

                    return(RedirectToAction("Index", "Home"));
                }
                AddErrors(result);
            }

            // Dotarcie do tego miejsca wskazuje, że wystąpił błąd, wyświetl ponownie formularz
            return(View(model));
        }
Пример #16
0
        public IHttpActionResult ChangePassword(int id, [FromBody] ChangePasswordModels model)
        {
            JavaScriptSerializer js = new JavaScriptSerializer();
            string logForm          = "Form : " + js.Serialize(model);
            string logAPI           = "[Put] " + Request.RequestUri.ToString();

            if (!ModelState.IsValid || model == null)
            {
                Startup._sfAppLogger.Warn(logAPI + " || Input Parameter not expected || " + logForm);
                return(BadRequest("Invalid data"));
            }

            try
            {
                AccountModels accountModel = new AccountModels();
                accountModel.ChangeEmployeePassword(id, model);
                return(Ok("Success"));
            }
            catch (Exception ex)
            {
                switch (ex.Message)
                {
                case "404":
                    return(NotFound());

                case "401":
                    return(Unauthorized());
                }

                StringBuilder logMessage = LogUtility.BuildExceptionMessage(ex);
                logMessage.AppendLine(logForm);
                Startup._sfAppLogger.Error(logAPI + logMessage);

                return(InternalServerError(ex));
            }
        }
        // POST /api/users/1/accounts
        public HttpResponseMessage Post(string id, AccountModels.SubmitAccountRequest request)
        {
            var user = GetUser(id);

            if (user == null)
            {
                var message = new HttpResponseMessage(HttpStatusCode.NotFound);

                message.ReasonPhrase = String.Format("The user id {0} specified in the request is not valid", id);
                return message;
            }
            //TODO: validate routing number

            PaymentAccountType accountType = PaymentAccountType.Checking;

            if(request.AccountType.ToUpper() == "CHECKING")
                accountType = PaymentAccountType.Checking;
            else if(request.AccountType.ToUpper() == "SAVINGS")
                accountType = PaymentAccountType.Savings;
            else
            {
                var message = new HttpResponseMessage(HttpStatusCode.BadRequest);
                message.ReasonPhrase = String.Format("Account Type specified in the request is invalid.  Valid account types are {0} or {1}", "Savings", "Checking");

                return message;
            }

            PaymentAccount account;

            try
            {
                account = _ctx.PaymentAccounts.Add(new Domain.PaymentAccount()
                {
                    Id = Guid.NewGuid(),
                    AccountNumber = _securityService.Encrypt(request.AccountNumber),
                    RoutingNumber = _securityService.Encrypt(request.RoutingNumber),
                    NameOnAccount = _securityService.Encrypt(request.NameOnAccount),
                    AccountType = accountType,
                    UserId = user.UserId,
                    IsActive = true,
                    CreateDate = System.DateTime.Now
                });

                _ctx.SaveChanges();
            }
            catch (Exception ex)
            {
                var message = new HttpResponseMessage(HttpStatusCode.InternalServerError);
                message.ReasonPhrase = String.Format("Internal Service Error. {0}", ex.Message);

                return message;
            }

            var response = new HttpResponseMessage(HttpStatusCode.Created);
            //TODO: add uri for created account to response header

            return response;
        }
        // PUT /api/users/1/accounts/5
        public HttpResponseMessage Put(string id, string accountId, AccountModels.UpdateAccountRequest request)
        {
            var user = GetUser(id);

            if (user == null)
            {
                var message = new HttpResponseMessage(HttpStatusCode.NotFound);

                message.ReasonPhrase = String.Format("The user {0} specified in the request is not valid", id);
                return message;
            }

            var account = GetAccount(accountId);

            if (account == null)
            {
                var message = new HttpResponseMessage(HttpStatusCode.NotFound);
                message.ReasonPhrase = String.Format("The account {0} specified in the request is not valid", accountId);

                return message;
            }
            //TODO: validate routing number

            PaymentAccountType accountType = PaymentAccountType.Checking;

            if (request.AccountType.ToUpper() == "CHECKING")
                accountType = PaymentAccountType.Checking;
            else if (request.AccountType.ToUpper() == "SAVINGS")
                accountType = PaymentAccountType.Savings;
            else
            {
                var message = new HttpResponseMessage(HttpStatusCode.BadRequest);
                message.ReasonPhrase = String.Format("Account Type specified in the request is invalid.  Valid account types are {0} or {1}", "Savings", "Checking");

                return message;
            }

            try
            {
                account.AccountNumber = _securityService.Encrypt(request.AccountNumber);
                account.AccountType = accountType;
                //account.IsActive = true;
                account.LastUpdatedDate = System.DateTime.Now;
                account.NameOnAccount = _securityService.Encrypt(request.NameOnAccount);
                account.RoutingNumber = _securityService.Encrypt(request.RoutingNumber);

                _ctx.SaveChanges();
            }
            catch (Exception ex)
            {
                var message = new HttpResponseMessage(HttpStatusCode.InternalServerError);
                message.ReasonPhrase = String.Format("Internal Server Error. {0}", ex.Message);

                return message;
            }

            return new HttpResponseMessage(HttpStatusCode.OK);
        }
Пример #19
0
        public ActionResult Register(AccountModels.RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                //// Attempt to register the user
                //MembershipCreateStatus createStatus;
                //Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus);

                //if (createStatus == MembershipCreateStatus.Success)
                //{
                //    FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);
                //    return RedirectToAction("Index", "Home");
                //}
                //else
                //{
                //    ModelState.AddModelError("", ErrorCodeToString(createStatus));
                //}
                //var newMember = _MemberRepository.SignUp(model.Email, model.DisplayName, model.Password);
                //var result = Uow.Members.Register(model);

                var member = Uow.Members.Register(model);
                if(member!= null)
                    Authenticate(member);
                else
                {
                    return View(model);
                }
                return RedirectToAction("Index", "Home");
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
Пример #20
0
        public ActionResult LogOn(AccountModels.LogOnModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                ModelState.AddModelError("", "The user name or password provided is incorrect.");
                return View(model);
            }

            if (!Uow.Members.ValidateMember(model))
            {
                Log.InfoJson(new { Task = "LogOnFail", User = model.Email, IP = Request.ResolveRemoteAddr() });
                ModelState.AddModelError("LogOn", "The username or password provided is incorrect.");
                CreateTokens(returnUrl);
                return View(model);
            }

            var member = Uow.Members.GetByEmail(model.Email);

            Authenticate(member);

            Log.InfoJson(new { Task = "LogOnSuccess", User = model.Email, IP = Request.ResolveRemoteAddr() });

            if (IsValidReturnUrl(returnUrl)) return Redirect(returnUrl);

            return RedirectToAction("Index", "Home");

            //return View(model);
        }
Пример #21
0
        //帳密驗證
        private UserClaims loginAuthentication(string id, string password, string role)
        {
            UserClaims userClaims = new UserClaims();

            userClaims.IsAuthenticated = false;
            userClaims.CompanyId       = 0;

            switch (role)
            {
            case "superadmin":
                using (var ctx = new SFDatabaseEntities())
                {
                    var superAdmin = ctx.SuperAdmin
                                     .Where(s => s.Email == id && s.DeletedFlag == false)
                                     .Select(s => new { s.Password }).FirstOrDefault();

                    try
                    {
                        if (Crypto.VerifyHashedPassword(superAdmin.Password, password))
                        {
                            userClaims.IsAuthenticated = true;
                        }
                    }
                    catch
                    {
                    }
                }
                break;

            case "admin":
                using (var ctx = new SFDatabaseEntities())
                {
                    var employee = ctx.Employee
                                   .Where(s => s.Email == id && s.DeletedFlag == false && s.Company.DeletedFlag == false)
                                   .Select(s => new { s.Password }).FirstOrDefault();

                    try
                    {
                        if (Crypto.VerifyHashedPassword(employee.Password, password))
                        {
                            userClaims.IsAuthenticated = true;
                        }
                    }
                    catch
                    {
                    }
                }
                break;

            case "device":
                AccountModels accountModels = new AccountModels();
                userClaims.IsAuthenticated = accountModels.CheckIoTDevicePassword(id, password);
                break;

            case "external":
                using (var ctx = new SFDatabaseEntities())
                {
                    var company = ctx.Company
                                  .Where(s => s.ExtAppAuthenticationKey == password && s.DeletedFlag == false)
                                  .Select(s => new { s.Id }).FirstOrDefault();
                    if (company != null)
                    {
                        userClaims.IsAuthenticated = true;
                        userClaims.CompanyId       = company.Id;
                    }
                }
                break;
            }
            return(userClaims);
        }
 // PUT /api/{userId}/paymentaccounts/{id}
 public void Put(string userId, string id, AccountModels.UpdateAccountRequest request)
 {
 }
Пример #23
0
        public ActionResult Login(AccountModels Model)
        {
            //SQL Select Member
            var sqlStr = string.Format("select Account, Username, Password, MailCheck, PwdChangeCheck, StatusNo from [dbo].[Member] where Account = {0}", SqlVal2(Model.Account));

            //SQL Check
            var data = _DB_GetData(sqlStr);

            //資料庫內是否有此帳號
            if (data.Rows.Count > 0)
            {
                //帳號與密碼是否相符
                if (Model.Account == data.Rows[0].ItemArray.GetValue(0).ToString() &&
                    SHA256_Compare(data.Rows[0].ItemArray.GetValue(2).ToString(), Model.Password))
                {
                    //登入成功,但遭到停權
                    if (data.Rows[0].ItemArray.GetValue(5).ToString() == "2")
                    {
                        //登入成功,但遭到停權
                        Model.ok            = false;
                        Model.ResultMessage = "登入失敗,您的帳號已遭到『停權』。";
                        return(View(Model));
                    }
                    else if (data.Rows[0].ItemArray.GetValue(3).ToString() != "1")//登入成功,但尚未驗證信箱
                    {
                        //前往驗證信箱畫面
                        return(RedirectToAction("MailVerify", "Account", new Verify()
                        {
                            Account = Model.Account,
                            Username = data.Rows[0].ItemArray.GetValue(1).ToString()
                        }));
                    }
                    else if (data.Rows[0].ItemArray.GetValue(4).ToString() == "1") //帳號的密碼是否需要修改
                    {
                        //前往修改密碼畫面
                        return(RedirectToAction("ChangePassword", "Account", new AccountModels()
                        {
                            Account = Model.Account
                        }));
                    }
                    else
                    {
                        // 加入cookie,預設使用者關閉瀏覽器時清除
                        Response.Cookies.Append("userName", data.Rows[0].ItemArray.GetValue(1).ToString());
                        Response.Cookies.Append("account", data.Rows[0].ItemArray.GetValue(0).ToString());

                        //登入成功,已驗證信箱
                        return(Redirect("/home/index"));
                    }
                }
                else
                {
                    //登入失敗 帳號或密碼錯誤
                    Model.ok            = false;
                    Model.ResultMessage = "登入失敗,帳號或密碼錯誤";
                    return(View(Model));
                }
            }
            else
            {
                //登入失敗 找不到此帳號
                Model.ok            = false;
                Model.ResultMessage = "登入失敗,找不到此帳號";
                return(View(Model));
            }
        }
Пример #24
0
        public ActionResult Register(AccountModels.RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                MembershipCreateStatus createStatus;
                Membership.CreateUser(model.UserName, model.Password, model.Email, "question", "answer", true, null, out createStatus);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("", ErrorCodeToString(createStatus));
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
        public override void Up()
        {
            CreateTable(
                "dbo.Accounts",
                c => new
            {
                ID           = c.Int(nullable: false, identity: true),
                UserName     = c.String(nullable: false, maxLength: 249),
                PasswordHash = c.String(nullable: false),
                RoleID       = c.Int(nullable: false),
            })
            .PrimaryKey(t => t.ID)
            .ForeignKey("dbo.Roles", t => t.RoleID)
            .Index(t => t.UserName, unique: true)
            .Index(t => t.RoleID);

            CreateTable(
                "dbo.Customers",
                c => new
            {
                ID              = c.Int(nullable: false),
                Name            = c.String(nullable: false),
                PhoneNumber     = c.String(nullable: false),
                Email           = c.String(nullable: false, maxLength: 249),
                DeliveryAddress = c.String(nullable: false),
            })
            .PrimaryKey(t => t.ID)
            .ForeignKey("dbo.Accounts", t => t.ID, cascadeDelete: true)
            .Index(t => t.ID)
            .Index(t => t.Email, unique: true);

            CreateTable(
                "dbo.Carts",
                c => new
            {
                CustomerID = c.Int(nullable: false),
                ProductID  = c.Int(nullable: false),
                Amount     = c.Int(nullable: false),
            })
            .PrimaryKey(t => new { t.CustomerID, t.ProductID })
            .ForeignKey("dbo.Customers", t => t.CustomerID)
            .ForeignKey("dbo.Products", t => t.ProductID)
            .Index(t => t.CustomerID)
            .Index(t => t.ProductID);

            CreateTable(
                "dbo.Products",
                c => new
            {
                ID          = c.Int(nullable: false, identity: true),
                Name        = c.String(nullable: false, maxLength: 249),
                Quantity    = c.Int(nullable: false),
                Description = c.String(),
                Status      = c.Boolean(nullable: false),
                Price       = c.Int(nullable: false),
                ProducerID  = c.Int(nullable: false),
                CategoryID  = c.Int(nullable: false),
                SellerID    = c.Int(nullable: false),
            })
            .PrimaryKey(t => t.ID)
            .ForeignKey("dbo.Categories", t => t.CategoryID)
            .ForeignKey("dbo.Producers", t => t.ProducerID)
            .ForeignKey("dbo.Sellers", t => t.SellerID)
            .Index(t => t.Name, unique: true)
            .Index(t => t.ProducerID)
            .Index(t => t.CategoryID)
            .Index(t => t.SellerID);

            CreateTable(
                "dbo.AvatarOfProducts",
                c => new
            {
                ProductID = c.Int(nullable: false),
                Avatar    = c.Binary(nullable: false),
            })
            .PrimaryKey(t => t.ProductID)
            .ForeignKey("dbo.Products", t => t.ProductID, cascadeDelete: true)
            .Index(t => t.ProductID);

            CreateTable(
                "dbo.Categories",
                c => new
            {
                ID   = c.Int(nullable: false, identity: true),
                Name = c.String(nullable: false, maxLength: 249),
            })
            .PrimaryKey(t => t.ID)
            .Index(t => t.Name, unique: true);

            CreateTable(
                "dbo.Comments",
                c => new
            {
                ID          = c.Int(nullable: false, identity: true),
                CommentTime = c.DateTime(nullable: false),
                Content     = c.String(),
                CustomerID  = c.Int(nullable: false),
                ProductID   = c.Int(nullable: false),
            })
            .PrimaryKey(t => t.ID)
            .ForeignKey("dbo.Customers", t => t.CustomerID, cascadeDelete: true)
            .ForeignKey("dbo.Products", t => t.ProductID, cascadeDelete: true)
            .Index(t => t.CustomerID)
            .Index(t => t.ProductID);

            CreateTable(
                "dbo.Producers",
                c => new
            {
                ID   = c.Int(nullable: false, identity: true),
                Name = c.String(nullable: false, maxLength: 249),
            })
            .PrimaryKey(t => t.ID)
            .Index(t => t.Name, unique: true);

            CreateTable(
                "dbo.ProductsOfOrders",
                c => new
            {
                OrderID   = c.Int(nullable: false),
                ProductID = c.Int(nullable: false),
                Amount    = c.Int(nullable: false),
            })
            .PrimaryKey(t => new { t.OrderID, t.ProductID })
            .ForeignKey("dbo.Orders", t => t.OrderID, cascadeDelete: true)
            .ForeignKey("dbo.Products", t => t.ProductID, cascadeDelete: true)
            .Index(t => t.OrderID)
            .Index(t => t.ProductID);

            CreateTable(
                "dbo.Orders",
                c => new
            {
                ID         = c.Int(nullable: false, identity: true),
                OrderTime  = c.DateTime(nullable: false),
                Status     = c.Int(nullable: false),
                CustomerID = c.Int(nullable: false),
                InvoiceID  = c.Int(),
            })
            .PrimaryKey(t => t.ID)
            .ForeignKey("dbo.Customers", t => t.CustomerID)
            .Index(t => new { t.CustomerID, t.OrderTime }, unique: true);

            CreateTable(
                "dbo.Invoices",
                c => new
            {
                ID            = c.String(nullable: false, maxLength: 249),
                DateOfInvoice = c.DateTime(nullable: false),
                TotalCost     = c.Double(nullable: false),
                OrderID       = c.Int(nullable: false),
            })
            .PrimaryKey(t => t.ID)
            .ForeignKey("dbo.Orders", t => t.OrderID)
            .Index(t => t.OrderID);

            CreateTable(
                "dbo.Sellers",
                c => new
            {
                ID               = c.Int(nullable: false),
                Name             = c.String(nullable: false),
                PhoneNumber      = c.String(nullable: false),
                Email            = c.String(nullable: false, maxLength: 249),
                WarehouseAddress = c.String(nullable: false),
            })
            .PrimaryKey(t => t.ID)
            .ForeignKey("dbo.Accounts", t => t.ID)
            .Index(t => t.ID)
            .Index(t => t.Email, unique: true);

            CreateTable(
                "dbo.SpecificationValues",
                c => new
            {
                ProductSpecificationID = c.Int(nullable: false),
                Value = c.String(nullable: false, maxLength: 128),
            })
            .PrimaryKey(t => new { t.ProductSpecificationID, t.Value })
            .ForeignKey("dbo.ProductSpecifications", t => t.ProductSpecificationID)
            .Index(t => t.ProductSpecificationID);

            CreateTable(
                "dbo.ProductSpecifications",
                c => new
            {
                ID          = c.Int(nullable: false, identity: true),
                Name        = c.String(nullable: false, maxLength: 249),
                Description = c.String(),
            })
            .PrimaryKey(t => t.ID)
            .Index(t => t.Name, unique: true);

            CreateTable(
                "dbo.StarRatings",
                c => new
            {
                CustomerID    = c.Int(nullable: false),
                ProductID     = c.Int(nullable: false),
                NumberOfStart = c.Int(nullable: false),
            })
            .PrimaryKey(t => new { t.CustomerID, t.ProductID })
            .ForeignKey("dbo.Customers", t => t.CustomerID, cascadeDelete: true)
            .ForeignKey("dbo.Products", t => t.ProductID, cascadeDelete: true)
            .Index(t => t.CustomerID)
            .Index(t => t.ProductID);

            CreateTable(
                "dbo.Roles",
                c => new
            {
                ID           = c.Int(nullable: false, identity: true),
                Name         = c.String(nullable: false, maxLength: 249),
                Descriptions = c.String(),
            })
            .PrimaryKey(t => t.ID)
            .Index(t => t.Name, unique: true);

            CreateTable(
                "dbo.SpecificationValueProducts",
                c => new
            {
                SpecificationValue_ProductSpecificationID = c.Int(nullable: false),
                SpecificationValue_Value = c.String(nullable: false, maxLength: 128),
                Product_ID = c.Int(nullable: false),
            })
            .PrimaryKey(t => new { t.SpecificationValue_ProductSpecificationID, t.SpecificationValue_Value, t.Product_ID })
            .ForeignKey("dbo.SpecificationValues", t => new { t.SpecificationValue_ProductSpecificationID, t.SpecificationValue_Value }, cascadeDelete: true)
            .ForeignKey("dbo.Products", t => t.Product_ID, cascadeDelete: true)
            .Index(t => new { t.SpecificationValue_ProductSpecificationID, t.SpecificationValue_Value })
            .Index(t => t.Product_ID);

            CreateTable(
                "dbo.Wishlists",
                c => new
            {
                Customer_ID = c.Int(nullable: false),
                Product_ID  = c.Int(nullable: false),
            })
            .PrimaryKey(t => new { t.Customer_ID, t.Product_ID })
            .ForeignKey("dbo.Customers", t => t.Customer_ID, cascadeDelete: true)
            .ForeignKey("dbo.Products", t => t.Product_ID, cascadeDelete: true)
            .Index(t => t.Customer_ID)
            .Index(t => t.Product_ID);

            Sql("insert into Roles(Name) Values('Admin')");
            Sql("insert into Roles(Name) Values('Seller')");
            Sql("insert into Roles(Name) Values('Customer')");
            Sql("insert into Roles(Name) Values('Shipper')");

            var passwordHash = AccountModels.Encrypt("Admin", true);

            Sql("insert into Accounts(UserName, PasswordHash, RoleID) Values('Admin', '" + passwordHash + "', " + RoleIds.Admin + ")");
            Sql("insert into Accounts(UserName, PasswordHash, RoleID) Values('Seller1', '" + passwordHash + "', " + RoleIds.Seller + ")");
            Sql("insert into Accounts(UserName, PasswordHash, RoleID) Values('Seller2', '" + passwordHash + "', " + RoleIds.Seller + ")");
            Sql("insert into Accounts(UserName, PasswordHash, RoleID) Values('Customer1', '" + passwordHash + "', " + RoleIds.Customer + ")");
            Sql("insert into Accounts(UserName, PasswordHash, RoleID) Values('Customer2', '" + passwordHash + "', " + RoleIds.Customer + ")");


            Sql("insert into Sellers(ID, Name, PhoneNumber, Email, WarehouseAddress) Values('2', 'Vinh', '0765764050', '*****@*****.**', 'Vinh Long')");
            Sql("insert into Sellers(ID, Name, PhoneNumber, Email, WarehouseAddress) Values('3', 'Vinh', '0765764050', '*****@*****.**', 'Vinh Long')");
            Sql("insert into Customers(ID, Name, PhoneNumber, Email, DeliveryAddress) Values('4', 'Vinh', '0765764050', '*****@*****.**', 'Vinh Long')");
            Sql("insert into Customers(ID, Name, PhoneNumber, Email, DeliveryAddress) Values('5', 'Vinh', '0765764050', '*****@*****.**', 'Vinh Long')");
        }
Пример #26
0
        public ActionResult Create(user _model, string RetypePassword, string[] AssignRoles)
        {
            IRBACRoleProvider       _RoleProvider       = IoC.Resolve <IRBACRoleProvider>();
            IuserService            _userService        = IoC.Resolve <IuserService>();
            IRBACMembershipProvider _MemberShipProvider = IoC.Resolve <IRBACMembershipProvider>();
            AccountModels           model = new AccountModels();

            if (string.IsNullOrWhiteSpace(_model.username))
            {
                Messages.AddErrorMessage("Cần nhập những thông tin bắt buộc.");
                List <String> lst = new List <string>(_RoleProvider.GetAllRoles());
                model.RetypePassword = _model.password = "";
                model.AllRoles       = lst.ToArray();
                model.UserRoles      = AssignRoles ?? new string[] { };
                model.tmpUser        = _model;
                return(View("New", model));
            }
            try
            {
                string status = "";
                AssignRoles = AssignRoles ?? new string[] { };
                if (!_model.password.Equals(RetypePassword))
                {
                    Messages.AddErrorMessage("Nhập đúng mật khẩu của bạn.");
                    List <String> lst = new List <string>(_RoleProvider.GetAllRoles());
                    model.RetypePassword = _model.password = "";
                    model.AllRoles       = lst.ToArray();
                    model.UserRoles      = new string[] { };
                    model.tmpUser        = _model;
                    return(View("New", model));
                }
                else
                {
                    _MemberShipProvider.CreateUser(_model.username, _model.password, _model.email, _model.PasswordQuestion, _model.PasswordAnswer, _model.IsApproved, null, out status);
                    if (status != "Success")
                    {
                        List <String> lst = new List <string>(_RoleProvider.GetAllRoles());
                        model.RetypePassword = _model.password = "";
                        model.AllRoles       = lst.ToArray();
                        model.UserRoles      = new string[] { };
                        model.tmpUser        = _model;
                        Messages.AddErrorMessage("Tài khoản đã có trên hệ thống hoặc dữ liệu không hợp lệ.");
                        return(View("New", model));
                    }
                    if (AssignRoles == null)
                    {
                        Messages.AddFlashMessage("Bạn tạo tài khoản thành công nhưng chưa phân quyền!");
                        return(RedirectToAction("index"));
                    }
                    _RoleProvider.UpdateUsersToRoles(_model.username, AssignRoles);
                    Messages.AddFlashMessage("Tạo tài khoản thành công.");

                    logSrv.CreateNew(FXContext.Current.CurrentUser.userid, "User - Create : " + string.Format("Create: {0} by {1}", _model.username, HttpContext.User.Identity.Name), "Create User Success ", LogType.Success, HttpContext.Request.UserHostAddress, HttpContext.Request.Browser.Browser);

                    return(RedirectToAction("index"));
                }
            }
            catch (Exception ex)
            {
                logSrv.CreateNew(FXContext.Current.CurrentUser.userid, "User - Create ", "Create User Error: " + ex, LogType.Error, HttpContext.Request.UserHostAddress, HttpContext.Request.Browser.Browser);

                Messages.AddErrorMessage("Chưa tạo được người dùng.");
                List <String> lst = new List <string>(_RoleProvider.GetAllRoles());
                model.RetypePassword = _model.password = "";
                model.AllRoles       = lst.ToArray();
                model.UserRoles      = new string[] { };
                model.tmpUser        = _model;
                return(View("New", model));
            }
        }