public ActionResult Register(Models.RegisterViewModel model) { if (ModelState.IsValid) { if (!model.Accept) { ModelState.AddModelError("", "注册账号需要同意《用户协议》"); } var user = new Identity.Models.User { UserName = model.UserName, //PhoneNumber = model.PhoneNumber }; var result = UserManager.Create(user, model.Password); if (result.Succeeded) { SignInManager.SignIn(user); // 有关如何启用帐户确认和密码重置的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkID=320771 // 发送包含此链接的电子邮件 // 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, "确认你的帐户", "请通过单击 <a href=\"" + callbackUrl + "\">這裏</a>来确认你的帐户"); return(RedirectToAction("Login", "Account")); } AddErrors(result); } // 如果我们进行到这一步时某个地方出错,则重新显示表单 return(View(model)); }
public async Task <ActionResult> Register(Models.RegisterViewModel model) { if (ModelState.IsValid) { var user = new Models.ApplicationUser { UserName = model.UserName, Email = model.Email /*,PhoneNumber = model.Phone*/ }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); // 如需如何進行帳戶確認及密碼重設的詳細資訊,請前往 https://go.microsoft.com/fwlink/?LinkID=320771 // 傳送包含此連結的電子郵件 // 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, "確認您的帳戶", "請按一下此連結確認您的帳戶 <a href=\"" + callbackUrl + "\">這裏</a>"); return(RedirectToAction("Index", "Home")); //將畫面重新導向至 } AddErrors(result); } // 如果執行到這裡,發生某項失敗,則重新顯示表單 return(View(model)); }
public async Task <ActionResult> Register(Models.RegisterViewModel model) { if (ModelState.IsValid) { var user = GetUser(model); var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { // Código temporário //var roleStore = new RoleStore<IdentityRole>(new ApplicationDbContext()); //var roleManager = new RoleManager<IdentityRole>(roleStore); //await roleManager.CreateAsync(new IdentityRole("CanManageCustomers")); //await UserManager.AddToRoleAsync(user.Id, "CanManageCustomers"); await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771 // Enviar um email com este link // 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, "Confirmar sua conta", "Confirme sua conta clicando <a href=\"" + callbackUrl + "\">aqui</a>"); return(RedirectToAction("Index", "Home")); } AddErrors(result); } // Se chegamos até aqui e houver alguma falha, exiba novamente o formulário return(View(model)); }
public async Task <ActionResult> Register(Models.RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email, DrivingLicense = model.DrivingLicense, Phone = model.Phone }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771 // Send an email with this link // 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, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>"); return(RedirectToAction("Index", "Home")); } AddErrors(result); } // If we got this far, something failed, redisplay form return(View(model)); }
public ActionResult Register(Models.RegisterViewModel model) { try { string Usertype = "普通用户"; int Admin_BL = 0; string connectionString = "Data Source=WIN-0MGTRP6ACV5\\MSSQL;Initial Catalog=test;Persist Security Info=false;User ID=sa;Password=Aa123456"; SqlConnection SqlCon = new SqlConnection(connectionString); //数据库连接 SqlCon.Open(); //打开数据库 string sql = "insert into [test].[dbo].[user_1] values" + $"('{model.RegisterTel}','{model.RegisterPassword}','{Usertype}',{Admin_BL})"; SqlCommand cmd = new SqlCommand(sql, SqlCon); cmd.CommandType = CommandType.Text; int ret = (int)cmd.ExecuteNonQuery(); if (ret > 0) { return(RedirectToAction("Success")); } } catch (Exception e) { Console.WriteLine(e); throw; } return(View()); }
public async Task <ActionResult> Register(Models.RegisterViewModel model) { if (ModelState.IsValid) { var file = model.Foto; string foto = null; if (file != null) { var ext = System.IO.Path.GetExtension(file.FileName); string[] extPermitidas = { ".png", ".jpg", ".jpeg", ".gif" }; if (!extPermitidas.Contains(ext)) { TempData["Sucesso"] = 0; TempData["Message"] = "A extensão " + ext + " não é um tipo de extensão de imagem válida!"; return(RedirectToAction("Index")); } foto = Guid.NewGuid().ToString() + System.IO.Path.GetFileName(file.FileName); string path = System.IO.Path.Combine(Server.MapPath("~/images"), foto); file.SaveAs(path); } var user = new ApplicationUser { UserName = model.Email, Email = model.Email, Nome = model.Nome, Foto = foto, Descricao = model.Descricao, Status = "Ocupado" }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { //await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false); await UserManager.SendEmailAsync(user.Id, "Aviso de cadastro", "Você foi cadastrado como consultor no sistema de atendimento com as seguintes informações: \n E-mail: " + user.Email + "\n Senha: " + model.Password); //Email ^ // Para obter mais informações sobre como habilitar a confirmação da conta e redefinição de senha, visite https://go.microsoft.com/fwlink/?LinkID=320771 // Enviar um email com este link // 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, "Confirmar sua conta", "Confirme sua conta clicando <a href=\"" + callbackUrl + "\">aqui</a>"); UserManager.AddToRole(user.Id, "Consultor"); TempData["Sucesso"] = 1; TempData["Message"] = "Cadastrado com sucesso!"; return(RedirectToAction("Index")); } AddErrors(result); } // Se chegamos até aqui e houver alguma falha, exiba novamente o formulário return(View(model)); }
public ActionResult UpdateAccount(string userId) { var personDetails = person.GetPersonDetails(userId); RegisterViewModel model = new Models.RegisterViewModel(); model.Email = personDetails.email; model.FullName = personDetails.fullName; model.UserName = personDetails.user_id; model.Password = personDetails.password; return(View(model)); }
// //SetUpAvailableRoles För EDIT void SetupAvailableRoles(Models.RegisterViewModel model) { model.AvailableRole = new List <SelectListItem> { new SelectListItem { Value = null, Text = "..Choose a role.." }, new SelectListItem { Value = "Admin", Text = "Admin" }, new SelectListItem { Value = "ProductManager", Text = "Product manager" }, }; }
public ActionResult Create(Models.RegisterViewModel user) { AccountController ac = new AccountController(); Task <ActionResult> a = ac.Register(user); string role_id = new UsersRoleDAO().Single(x => x.Name == "Manager").Id; string id = new UsersDAO().Single(x => x.UserName == user.UserName).Id; AspNetUserRoles au = new DAO.AspNetUserRoles() { UserId = id, RoleId = role_id }; new UserInRolesDAO().insert(au); return(Redirect("index")); }
public ActionResult Register(string userId = null) { if (userId == null) { return(View()); } else { var personDetails = person.GetPersonDetails(userId); RegisterViewModel model = new Models.RegisterViewModel(); model.Email = personDetails.email; model.FullName = personDetails.fullName; model.UserName = personDetails.user_id; model.Password = personDetails.password; return(View(model)); } }
public ActionResult ChangePassword(Models.RegisterViewModel updatedUser) { // Get the current user's emailAddress to find the current user in the database. string emailAddress = User.Identity.GetUserName(); FundRaisers currentUser = db.FundRaisers.FirstOrDefault(u => u.Email == emailAddress); // Only change the user's password in the database if the password field is not left blank. if (updatedUser.Password != "") { string newPassword = Crypto.HashPassword(updatedUser.Password); currentUser.Password = newPassword; currentUser.ConfirmPassword = newPassword; } db.Entry(currentUser).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index", "Home")); }
public ActionResult Details() { int id = Services.UserMethods.GetUserID(System.Web.HttpContext.Current.User.Identity.Name); if (Request.IsAuthenticated && id != 0) // Database.UsersEntity.GetUserID(System.Web.HttpContext.Current.User.Identity.Name) { var model = new Models.RegisterViewModel(); model = Services.UserMethods.GetUser(Services.UserMethods.GetUserID(System.Web.HttpContext.Current.User.Identity.Name)); return(View(model)); } else { RedirectToAction("Login", "Account"); } return(View()); }
public ActionResult UserSettings(Models.RegisterViewModel updatedUser) { // Get the current user's emailAddress to find the current user in the database. string emailAddress = User.Identity.GetUserName(); var currentUser = db.FundRaisers.FirstOrDefault(u => u.Email == emailAddress); // Update the currentUser's respective fields. string newPassword = Crypto.HashPassword(updatedUser.Password); currentUser.Password = newPassword; currentUser.ConfirmPassword = newPassword; currentUser.FirstName = updatedUser.FirstName; currentUser.LastName = updatedUser.LastName; db.Entry(currentUser).State = EntityState.Modified; db.SaveChanges(); // Go back to /Users/ProfilePage return(RedirectToAction("Index", "Home")); }
public async Task <IActionResult> Register(Models.RegisterViewModel model) { if (ModelState.IsValid) { TCPUser newUser = new TCPUser { Email = model.email, UserName = model.userName, FirstName = model.firstName, LastName = model.lastName, PhoneNumber = model.phoneNumber }; IdentityResult creationResult = this._signInManager.UserManager.CreateAsync(newUser).Result; if (creationResult.Succeeded) { IdentityResult passwordResult = this._signInManager.UserManager.AddPasswordAsync(newUser, model.password).Result; if (passwordResult.Succeeded) { Braintree.CustomerSearchRequest search = new Braintree.CustomerSearchRequest(); search.Email.Is(model.email); var searchResult = await _braintreeGateway.Customer.SearchAsync(search); if (searchResult.Ids.Count == 0) { //Create a new Braintree Customer await _braintreeGateway.Customer.CreateAsync(new Braintree.CustomerRequest { Email = model.email, FirstName = model.firstName, LastName = model.lastName, Phone = model.phoneNumber }); } else { //Update the existing Braintree customer Braintree.Customer existingCustomer = searchResult.FirstItem; await _braintreeGateway.Customer.UpdateAsync(existingCustomer.Id, new Braintree.CustomerRequest { FirstName = model.firstName, LastName = model.lastName, Phone = model.phoneNumber }); } var confirmationToken = await _signInManager.UserManager.GenerateEmailConfirmationTokenAsync(newUser); confirmationToken = System.Net.WebUtility.UrlEncode(confirmationToken); string currentUrl = Request.GetDisplayUrl(); //This will get me the URL for the current request System.Uri uri = new Uri(currentUrl); //This will wrap it in a "URI" object so I can split it into parts string confirmationUrl = uri.GetLeftPart(UriPartial.Authority); //This gives me just the scheme + authority of the URI confirmationUrl += "/account/confirm?id=" + confirmationToken + "&userId=" + System.Net.WebUtility.UrlEncode(newUser.Id); await this._signInManager.SignInAsync(newUser, false); var emailResult = await this._emailService.SendEmailAsync( model.email, "Welcome to The Chesed Project!", "<p>Thanks for signing up, " + model.userName + "!</p><p><a href=\"" + confirmationUrl + "\">Confirm your account<a></p>", "Thanks for signing up, " + model.userName + "!" ); if (!emailResult.Success) { throw new Exception(string.Join(',', emailResult.Errors.Select(x => x.Message))); } return(RedirectToAction("Index", "Home")); } else { foreach (var error in creationResult.Errors) { ModelState.AddModelError(error.Code, error.Description); } } } else { foreach (var error in creationResult.Errors) { ModelState.AddModelError(error.Code, error.Description); } } } return(View()); }
private static ApplicationUser GetUser(Models.RegisterViewModel model) { return(new ApplicationUser { UserName = model.Email, Email = model.Email }); }
public async Task <ActionResult> SubscribeUser(mcmsSubscribeUser mcmssubscribeuser, string IsDevice) { try { //Header Check variable.UserPhoneNo = objCheckMsisdnUserStatus.GetHeaderWhileActionRequested(Request); RegisterViewModel RModel = new Models.RegisterViewModel(); //assign login status failed _IsSubscribedWithRemainingDate.LoginResult = ConstantValues.LOGIN_STATUS_FAILED_ID; //if header exists if (variable.UserPhoneNo != null && !variable.UserPhoneNo.Equals("")) { //assign UserName/PhoneNo _IsSubscribedWithRemainingDate.UserPhoneNo = variable.UserPhoneNo; //Check weather user is subcribed or new user.... var resultmodel = db.objCheckSubcription.Where(t => t.UserName == variable.UserPhoneNo).Select(t => t).ToList(); //User is not exists add User Info if (resultmodel.Count == 0) { //for register a new user RModel.UserName = variable.UserPhoneNo; RModel.Password = variable.UserPhoneNo; RModel.ConfirmPassword = variable.UserPhoneNo; //get user id of new user AccountController ObjAccount = new AccountController(); variable.UserId = ObjAccount.RegisterCalled(RModel); // if User Create then add user info in mcms_SubcriptionCheck table if (variable.UserId != null && !variable.UserId.Equals("")) { // SubscribeStatus = true; mcms_SubcriptionCheck aCheck = new mcms_SubcriptionCheck(); aCheck.Id = variable.UserId; aCheck.UserName = RModel.UserName; aCheck.SubscribeDate = DateTime.Now; aCheck.ExpireDate = DateTime.Now.AddDays(30); variable.ExpiredDateTime = aCheck.ExpireDate; aCheck.Status = ConstantValues.STATUS_SUBSCRIBE_INIT_ID;//attempt to Subscribe id= 7 db.objCheckSubcription.Add(aCheck); db.SaveChanges(); //now call api fore genrate soap request variable.CheckResult = await SoapManager(variable.UserPhoneNo, ConstantValues.STATUS_SUBSCRIBE_NAME); //if soap response success 1 if (variable.CheckResult == ConstantValues.SOAP_RESPONSE_RESULT_SUCCESS_ID) //1 { //now update aCheck.Status from INIT_ID to ConstantValues.STATUS_SUBSCRIBE_ID UpdateSubcriptionCheckStatus(ConstantValues.STATUS_SUBSCRIBE_ID, variable.UserPhoneNo); //login status success _IsSubscribedWithRemainingDate.LoginResult = ConstantValues.LOGIN_STATUS_SUCCESS_ID; _IsSubscribedWithRemainingDate.StatusID = ConstantValues.STATUS_SUBSCRIBE_ID; //To do update aCheck.Status=ConstantValues.STATUS_SUBSCRIBE_ID _IsSubscribedWithRemainingDate.ExpiredRemainingDate = Convert.ToInt32((aCheck.ExpireDate - aCheck.SubscribeDate).TotalDays); //check renew true or false //check if ExpiredRemainingDate is less 30 renew true else renew false if (_IsSubscribedWithRemainingDate.ExpiredRemainingDate < ConstantValues.SUB_DATE_RANGE) { _IsSubscribedWithRemainingDate.Renew = true; } else { _IsSubscribedWithRemainingDate.Renew = false; } } else { _IsSubscribedWithRemainingDate.StatusID = ConstantValues.STATUS_UN_SUBSCRIBE_ID; // _IsSubscribedWithRemainingDate.ExpiredRemainingDate = Convert.ToInt32((aCheck.ExpireDate - aCheck.SubscribeDate).TotalDays - 1); } } //new user but user is not create else { //any reson user is not created _IsSubscribedWithRemainingDate.StatusID = ConstantValues.STATUS_UN_SUBSCRIBE_ID; } } } //if user does not found else { _IsSubscribedWithRemainingDate.StatusID = ConstantValues.STATUS_NOT_ROBI_ID;; } } catch (Exception mx) { var a = mx.Message; _IsSubscribedWithRemainingDate.StatusID = ConstantValues.STATUS_EXCEPTION_ID; } // if request come from Device=android return json if (IsDevice == ConstantValues.Device) { return(Json(new { _IsSubscribedWithRemainingDate }, JsonRequestBehavior.AllowGet)); } else { if (_IsSubscribedWithRemainingDate.StatusID == ConstantValues.STATUS_SUBSCRIBE_ID) { ViewBag.Date = variable.ExpiredDateTime; if (_IsSubscribedWithRemainingDate.LoginResult == ConstantValues.LOGIN_STATUS_SUCCESS_ID) { return(View("SubscribeSucess")); } else { return(View("LoginError")); } } else if (_IsSubscribedWithRemainingDate.StatusID == ConstantValues.STATUS_UN_SUBSCRIBE_ID) { return(View("SubscribeUnSucess")); } else { return(View("SubscribeUnSucess")); } } }
public async Task <ActionResult> ProfileView(int?mode) { if (mode == null) { mode = 0; } ViewBag.mode = mode; String userID = User.Identity.GetUserId(); if (userID == null || userID.Length == 0) { return(View()); } aspnetuserclaim aspUserClaim = db.aspnetuserclaims.Where(i => i.UserId == userID).Single(); switch (mode) { case 0: //Profile { string query = "SELECT * FROM userinfo WHERE userinfo.Id = '" + userID + "'"; userinfo UserInfo = await db.userinfoes.SqlQuery(query).SingleOrDefaultAsync(); query = "SELECT * FROM aspnetusers WHERE Id = '" + userID + "'"; aspnetuser aspnetUserInfo = await db.aspnetusers.SqlQuery(query).SingleOrDefaultAsync(); Models.RegisterViewModel model = new Models.RegisterViewModel(); model.Email = User.Identity.Name; //model.Password = ""; //model.ConfirmPassword = ""; model.UserName = UserInfo.UserName; model.Birthday = (DateTime)(UserInfo.Date_Of_Birth == null ? new DateTime() : UserInfo.Date_Of_Birth); model.Picture = UserInfo.Profile_Pic; model.Gender = (int)UserInfo.Gender; model.GenderPref = (int)UserInfo.Gender_Pref; model.PhoneNumber = aspnetUserInfo.PhoneNumber; model.Ethnicity = UserInfo.Ethnicity; model.Interests = UserInfo.Interests; model.City = UserInfo.City; model.County = UserInfo.County; model.Country = UserInfo.Country; model.Postcode = UserInfo.Postcode; model.AccountType = (int)(UserInfo.Account_Type == null ? 0 : UserInfo.Account_Type); ViewBag.GalleryPics = UserInfo.Gallery_Pics; ViewBag.PrivateGalleryPics = UserInfo.Private_Gallery_Pics; return(View("ProfileView", model)); } case 1: //Gallery { String GalleryPics = ""; if (userID != null) { string query = "SELECT * FROM userinfo WHERE userinfo.Id = '" + userID + "'"; System.Data.Entity.Infrastructure.DbSqlQuery <userinfo> userInfos = db.userinfoes.SqlQuery(query); userinfo UserInfo = null; if (userInfos != null) { UserInfo = await userInfos.SingleOrDefaultAsync(); } if (UserInfo != null && UserInfo.Gallery_Pics != null) { GalleryPics = UserInfo.Gallery_Pics; } } return(View("ProfileView", (object)GalleryPics)); } case 2: //Private Gallery { String GalleryPics = ""; if (userID != null) { string query = "SELECT * FROM userinfo WHERE userinfo.Id = '" + userID + "'"; System.Data.Entity.Infrastructure.DbSqlQuery <userinfo> userInfos = db.userinfoes.SqlQuery(query); userinfo UserInfo = null; if (userInfos != null) { UserInfo = await userInfos.SingleOrDefaultAsync(); } if (UserInfo != null && UserInfo.Gallery_Pics != null) { GalleryPics = UserInfo.Private_Gallery_Pics; } } return(View("ProfileView", (object)GalleryPics)); } } return(View()); }
public ActionResult CreateUser() { var model = new Models.RegisterViewModel(); return(View(model)); }
public ActionResult Register(Models.RegisterViewModel newuser) { if (newuser.Password.Equals(newuser.ConfirmPassword)) { //INSERTING NEW USER using (SqlConnection sqlConnection = new SqlConnection(connectString)) { sqlConnection.Open(); string query = "INSERT INTO UserDetails(UserName,Email,Pass) VALUES (@name,@email,@password)"; SqlCommand sqlCommand = new SqlCommand(query, sqlConnection); sqlCommand.Parameters.AddWithValue("@name", newuser.Name); sqlCommand.Parameters.AddWithValue("@email", newuser.Email); sqlCommand.Parameters.AddWithValue("@password", newuser.Password); string conpass = newuser.ConfirmPassword; sqlCommand.ExecuteNonQuery(); } //OBTAINING USER ID FOR INSERTING FIRST LOGINDETAIL-SESSION START var user = new DataTable(); using (var sqlCon = new SqlConnection(connectString)) { sqlCon.Open(); var query = "Select * from UserDetails where Email='" + newuser.Email + "';"; var sqlDa = new SqlDataAdapter(query, sqlCon); sqlDa.Fill(user); } int id = (int)user.Rows[0][0]; //STARTING FIRST SESSION using (SqlConnection sqlConnection = new SqlConnection(connectString)) { sqlConnection.Open(); string query = "INSERT INTO LoginDetails(UserId) VALUES (@id)"; SqlCommand sqlCommand = new SqlCommand(query, sqlConnection); sqlCommand.Parameters.AddWithValue("@id", id); sqlCommand.ExecuteNonQuery(); } //ENDING FIRST SESSION DateTime localDate = DateTime.Now; using (SqlConnection sqlConnection = new SqlConnection(connectString)) { sqlConnection.Open(); string query1 = "Update LoginDetails Set sessionend=@end where loginID=(select max(loginid) from logindetails where userid=@id);"; SqlCommand sqlCommand1 = new SqlCommand(query1, sqlConnection); sqlCommand1.Parameters.AddWithValue("@end", localDate); sqlCommand1.Parameters.AddWithValue("@id", id); sqlCommand1.ExecuteNonQuery(); } //REDIRECTING TO LOGIN PAGE FOR FIRST LOGIN TempData["msg"] = "<script>alert('You have successfully registered. Please login for using your account.')</script>"; return(RedirectToAction("Login", "Home")); } else { //PASSWORDS DIDNT MATCH //TempData["msg"] = "<script>alert('Your passwords didn't match. Try again.')</script>"; TempData["msg"] = "<script>alert('Your passwords did not match. Please try again.')</script>"; return(RedirectToAction("Index", "Home")); } }