public async Task<ActionResult> Login(LoginViewModel model, string returnUrl) { if (!ModelState.IsValid) { return View(model); } // This doesn't count login failures towards account lockout // To enable password failures to trigger account lockout, change to shouldLockout: true var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false); switch (result) { case SignInStatus.Success: //return RedirectToLocal(returnUrl); Session["usuario"] = new AspNetUsers() {UserName = User.Identity.Name }; return RedirectToAction("Empresas", "Directorio"); case SignInStatus.LockedOut: return View("Lockout"); case SignInStatus.RequiresVerification: return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe }); case SignInStatus.Failure: default: ModelState.AddModelError("", "Invalid login attempt."); return View(model); } }
public Preferences(SharedContext context, long userId) { _context = context; _user = _context.USER_TABLE.Find(userId); _aspUser = _context.AspNetUsers.Find(_user.AspNetUserId); }
public ActionResult SignUp([Bind(Include = "Email,UserName")] AspNetUsers aspNetUsers) { bool hasErrors = false; string password = Request.Form["Password"]; string password2 = Request.Form["Password2"]; if (!ModelState.IsValid) { ViewBag.ErrMessage = "There are error(s) in your input"; hasErrors = true; } if (!this.IsCaptchaValid("Validate your captcha")) { ViewBag.ErrMessage = "Your captcha answer is incorrect."; hasErrors = true; } if (password != password2) { ViewBag.ErrMessage = "Passwords don't match."; hasErrors = true; } if (password.Trim() == "") { ViewBag.ErrMessage = "Password must be filled in."; hasErrors = true; } if (aspNetUsers.UserName.Trim() == "") { ViewBag.ErrMessage = "Username must be filled in."; hasErrors = true; } int count = (from i in db.AspNetUsers where (i.UserName == aspNetUsers.UserName) select i).Count(); if (0 < count) { ViewBag.ErrMessage = "User name already exists."; hasErrors = true; } if (!ModelState.IsValid) { ViewBag.ErrMessage = "There are error(s) in your input"; hasErrors = true; } if (hasErrors) { return(View()); } else { aspNetUsers.Id = Guid.NewGuid().ToString(); aspNetUsers.EmailConfirmed = true; aspNetUsers.PasswordHash = GetPasswordHash(password); aspNetUsers.SecurityStamp = ""; aspNetUsers.PhoneNumber = ""; aspNetUsers.PhoneNumberConfirmed = false; aspNetUsers.TwoFactorEnabled = false; aspNetUsers.LockoutEndDateUtc = null; aspNetUsers.LockoutEnabled = false; aspNetUsers.AccessFailedCount = 0; aspNetUsers.AspNetRoles.Add(db.AspNetRoles.Find("2")); db.AspNetUsers.Add(aspNetUsers); Users users = new Users(); users.UserId = aspNetUsers.Id; users.FirstName = ""; users.LastName = ""; users.Email = aspNetUsers.Email; users.Created = DateTime.Now; users.IsDeleted = false; db.Users.Add(users); db.SaveChanges(); Session["UserInfo"] = aspNetUsers; Session["UserName"] = aspNetUsers.UserName; Session["UserId"] = aspNetUsers.Id; Session["IsAdmin"] = false; return(RedirectToAction("../Users/Profile")); } }
public int Update(AspNetUsers account) { _db.AspNetUsers.Update(account); _db.SaveChangesAsync(); return(1); }
/// <summary> /// Update a user /// </summary> /// <param name="user"> /// The user. /// </param> /// <returns> /// The <see cref="IdentityResult"/>. /// </returns> public IdentityResult Update(AspNetUsers user) { return(this.Get <AspNetUsersManager>().Update(user)); }
/// <summary> /// Add a user to a role /// </summary> /// <param name="user"> /// The user. /// </param> /// <param name="roleName"> /// The role Name. /// </param> public void AddToRole(AspNetUsers user, string roleName) { this.Get <AspNetUsersManager>().AddToRole(user.Id, roleName); }
/// <summary> /// Creates a ClaimsIdentity representing the user /// </summary> /// <param name="user"> /// The user. /// </param> /// <param name="authenticationType"> /// The authentication Type. /// </param> /// <returns> /// The <see cref="ClaimsIdentity"/>. /// </returns> public ClaimsIdentity CreateIdentity(AspNetUsers user, string authenticationType) { return(this.Get <AspNetUsersManager>().CreateIdentity(user, authenticationType)); }
void SubtractFunds(AspNetUsers currentUser, int item) { db.Wallet.Find(currentUser.Id).WalletAmount -= db.Items.Find(item).Price; }
public async Task <IHttpActionResult> InsertSkills(List <RegisterBindingModel> userl) { //if (!ModelState.IsValid) //{ //string messages = string.Join("; ", ModelState.Values // .SelectMany(x => x.Errors) // .Select(x => x.ErrorMessage)); //return Json(new { success = false, issue = "", errors = messages }); //} ZonaFl.Business.SubSystems.SUser usern = new Business.SubSystems.SUser(); ZonaFl.Business.SubSystems.SCategory usersk = new Business.SubSystems.SCategory(); ZonaFl.Business.SubSystems.SSkill sskill = new Business.SubSystems.SSkill(); RegisterBindingModel user = userl[0]; if (user.Empresa == null) { user.Empresa = false; } if (user.Freelance == null) { user.Freelance = false; } RegisterBindingModel rmb = new RegisterBindingModel(); rmb.Skills = user.Skills; rmb.Company = user.Company; Persistence.Entities.Company company = new Persistence.Entities.Company(); if (user.Company != null) { company.InjectFrom(user.Company.FirstOrDefault()); } List <Persistence.Entities.Skill> skills = rmb.Skills.Select(e => new Persistence.Entities.Skill().InjectFrom(e)).Cast <Persistence.Entities.Skill>().ToList(); AspNetUsers aspuser = new AspNetUsers(); var useru = UserManager.FindByEmail(user.Email); for (int i = 0; i < skills.Count(); i++) { ZonaFl.Persistence.Entities.Category category = null; var skill = sskill.FindSkillByName(user.Skills[i].Name); string[] stringSeparators = new string[] { "\n" }; string result = user.Skills[i].CategorySkill.Split(stringSeparators, StringSplitOptions.None)[0]; category = usersk.FindCategoryByName(result); if (category == null) { try { category = usersk.InsertCategory(result); } catch (Exception er) { return(Json(new { success = false, issue = user, errors = er.Message, tipo = user, UserEmail = useru.Email })); } } skills[i].IdHtml = user.Skills[i].IdHtml; skills[i].Category = category; skills[i].CategoryId = category.Id; } useru.City = user.City; useru.Country = user.Country; useru.UserName = user.UserName; useru.DescUser = user.DescUser; useru.PhoneNumber = user.PhoneNumber.ToString(); useru.FirstMiddleName = user.FirstMiddleName; useru.Image = user.Image; useru.Empresa = user.Empresa; aspuser.InjectFrom(useru); aspuser.NoTrabajadores = user.NumeroEmp; try { Business.Log4NetLogger logger2 = new Business.Log4NetLogger(); if (!useru.Empresa) { if (skills.Count > 0) { skills = usern.InsertSkillsByUser(skills, aspuser); logger2.Info("Inserción Usuario Categoria:" + useru.Id + "," + "UsuarioCategoria:" + skills.FirstOrDefault().CategoryId + ",Email:" + aspuser.Email); } } } catch (Exception er) { return(Json(new { success = false, issue = user, errors = er.Message, tipo = aspuser, UserEmail = useru.Email })); } try { SUser suser = new SUser(); aspuser.Empresa = useru.Empresa; aspuser.Freelance = useru.Freelance; IdentityResult result = await UserManager.UpdateAsync(useru); var userupdate = suser.UpdateUser(aspuser); if (useru.Empresa) { company.IdUser = useru.Id; company.Name = userl[0].Company.Last().Name; company.Mail = userl[0].Company.Last().Mail; company.Site = user.UrlEmpresa; company.Sector = userl[0].Company.Last().Sector; company.RazonSocial = userl[0].Company.Last().RazonSocial; company.Telefono = userl[0].Company.Last().Telefono; company.Nit = userl[0].Company.Last().Nit; company.NumeroEmp = aspuser.NoTrabajadores == null ? 0 : (int)aspuser.NoTrabajadores; company.Description = userl[0].Company.Last().Description; Persistence.Entities.Company companyp = usern.InsertCompany(company); } if (!result.Succeeded) { return(GetErrorResult(result)); } } catch (Exception er) { return(Json(new { success = false, issue = user, errors = er.Message, tipo = user, UserEmail = useru.Email })); //return InternalServerError(er); } aspuser.Empresa = useru.Empresa; aspuser.Freelance = useru.Freelance; aspuser.Id = useru.Id; return(Json(new { success = true, issue = user, errors = "", tipo = aspuser, UserEmail = useru.Email })); //return Ok(); }
public async Task <IHttpActionResult> LoginUser(string UserName, string Email, string PasswordHash, bool Empresa, bool Freelance) { //string UserName = "******"; //string Email = "*****@*****.**"; //string PasswordHash = "j7948810"; //bool Empresa = true; //bool Freelance = false; var user = new ApplicationUser() { UserName = UserName, Email = Email, Empresa = Empresa, Freelance = Freelance }; AspNetUsers aspuser = new AspNetUsers(); try { ZonaFl.Business.SubSystems.SUser usern = new Business.SubSystems.SUser(); ApplicationUser useru = null; if (user.UserName.Contains("@")) { useru = UserManager.FindByEmail(user.UserName); } else { useru = UserManager.FindByName(user.UserName); } if (useru != null) { if (UserManager.IsEmailConfirmed(useru.Id)) { bool validuser = false; if (useru != null) { validuser = UserManager.CheckPassword(useru, PasswordHash); if (validuser) { var identity = new System.Security.Principal.GenericIdentity(useru.UserName); SetPrincipal(new System.Security.Principal.GenericPrincipal(identity, null)); } else { return(Json(new { success = false, issue = user, errors = "Contraseña o usuario incorrecto, favor volver a ingresar los datos", tipo = user, UserEmail = aspuser.Email })); } var useri = HttpContext.Current.User; HttpContext.Current.User = useri; //RegisterBindingModel regbm = new RegisterBindingModel(); //regbm.InjectFrom(useru); //HttpSessionStateBase session = new HttpSessionStateWrapper(HttpContext.Current.Session); //SessionBag.Current.User = regbm; } if (useru.Freelance) { return(Json(new { success = validuser, issue = useru, errors = "", tipo = useru, UserEmail = useru.Email, Url = Url.Content("/Offer/Index/" + useru.Id).ToString() })); } else if (useru.Empresa) { return(Json(new { success = validuser, issue = useru, errors = "", tipo = useru, UserEmail = useru.Email, Url = Url.Content("/Projects/Index/" + useru.Id).ToString() })); } else { return(Json(new { success = validuser, issue = useru, errors = "", tipo = useru, UserEmail = useru.Email, Url = Url.Content("/Administration/Users/Index?email=" + useru.Email).ToString() })); } } else { return(Json(new { success = false, issue = user, errors = "Usuario con correo electrónico no confirmado, favor revisar su correo electronico para confirmar la creación de la cuenta", tipo = user, UserEmail = aspuser.Email })); } } else { return(Json(new { success = false, issue = user, errors = "Usuario o password incorecto, favor digitar correctamente sus credenciales", tipo = user, UserEmail = aspuser.Email })); } } catch (Exception ex) { return(Json(new { success = false, issue = user, errors = ex.Message, tipo = user, UserEmail = aspuser.Email, Trace = ex.StackTrace })); } return(Json(new { success = true, issue = "Registro de usuario", errors = "", tipo = "Registro de usuario", UserEmail = user.Email, Url = Url.Content("/Freelance/Logout").ToString() })); }
/// <summary> /// This method returns the supervisors in a datatable /// </summary> /// <returns></returns> public DataTable ReturnSupervisors() { AspNetUsers user = new AspNetUsers(); return(user.GetSupervisors()); }
/// <summary> /// 创建一个AspNetUsers /// </summary> /// <param name="validationErrors">返回的错误信息</param> /// <param name="db">数据库上下文</param> /// <param name="entity">一个AspNetUsers</param> /// <returns></returns> public bool Create(ref ValidationErrors validationErrors, LYProjectEntities db, AspNetUsers entity) { int count = 1; foreach (string item in entity.AspNetRoles.Select(x => x.Id)) { AspNetRoles sys = new AspNetRoles { Id = item }; db.AspNetRoles.Attach(sys); entity.AspNetRoles.Add(sys); count++; } repository.Create(db, entity); if (count == repository.Save(db)) { return(true); } else { validationErrors.Add("创建出错了"); } return(false); }
/// <summary> /// 编辑一个AspNetUsers /// </summary> /// <param name="validationErrors">返回的错误信息</param> /// <param name="db">数据上下文</param> /// <param name="entity">一个AspNetUsers</param> /// <returns>是否编辑成功</returns> public bool Edit(ref ValidationErrors validationErrors, LYProjectEntities db, AspNetUsers entity) { /* * 不操作 原有 现有 * 增加 原没 现有 * 删除 原有 现没 */ if (entity == null) { return(false); } int count = 1; AspNetUsers editEntity = repository.Edit(db, entity); List <string> addAspNetRolesId = new List <string>(); List <string> deleteAspNetRolesId = new List <string>(); DataOfDiffrent.GetDiffrent(entity.AspNetRoles.Select(x => x.Id).ToList(), entity.AspNetRoles.Select(x => x.Id).ToList(), ref addAspNetRolesId, ref deleteAspNetRolesId); if (addAspNetRolesId != null && addAspNetRolesId.Count() > 0) { foreach (var item in addAspNetRolesId) { AspNetRoles sys = new AspNetRoles { Id = item }; db.AspNetRoles.Attach(sys); editEntity.AspNetRoles.Add(sys); count++; } } if (deleteAspNetRolesId != null && deleteAspNetRolesId.Count() > 0) { List <AspNetRoles> listEntity = new List <AspNetRoles>(); foreach (var item in deleteAspNetRolesId) { AspNetRoles sys = new AspNetRoles { Id = item }; listEntity.Add(sys); db.AspNetRoles.Attach(sys); } foreach (AspNetRoles item in listEntity) { editEntity.AspNetRoles.Remove(item);//查询数据库 count++; } } if (count == repository.Save(db)) { return(true); } else { validationErrors.Add("编辑AspNetUsers出错了"); } return(false); }
public GroupSummaryForUser GetGroupSummary(string userEmail, string courseCode) { GroupSummaryForUser gsfu = new GroupSummaryForUser(); AspNetUsers up = _repUserProfile.Get(filter: f => f.Email == userEmail).FirstOrDefault(); Course course = _repCourse.Get(filter: f => f.CourseCode == courseCode, includes: "Groups,CourseUserRoles").FirstOrDefault(); EntityModel.CourseUser cur = _repCourseUserRole.Get(filter: f => f.CourseId == course.CourseId && f.UserId == up.Id, includes: "Group").FirstOrDefault(); if (cur.GroupId.HasValue) { gsfu.registeredGroup = new GroupSummary() { GroupCode = cur.Group.GroupCode, GroupName = cur.Group.GroupName, activeTimeZone = cur.Group.TimeZone, Objective = cur.Group.Objective }; } else { gsfu.registeredGroup = null; } List <string> answers = cur.AnswerSet.Split(',').ToList(); gsfu.suggestedGroups = new List <GroupSummary>(); foreach (EntityModel.CourseUser cu in course.CourseUserRoles) { if (cu.UserId != up.Id && !string.IsNullOrWhiteSpace(cu.AnswerSet)) { int matchPercentage = getMatchPercentage(answers, cu.AnswerSet.Split(',').ToList()); if (matchPercentage >= 50) { if (cu.GroupId.HasValue) { if (!cur.GroupId.HasValue || cur.GroupId != cu.GroupId) { Group grp = _repGroup.Get(filter: f => f.GroupId == cu.GroupId).FirstOrDefault(); if (!gsfu.suggestedGroups.Any(x => x.GroupCode == grp.GroupCode)) { gsfu.suggestedGroups.Add(new GroupSummary() { GroupName = grp.GroupName, GroupCode = grp.GroupCode, Objective = grp.Objective, activeTimeZone = grp.TimeZone }); } } } } } } gsfu.AllGroups = new List <GroupSummary>(); foreach (var grp in course.Groups) { if (!cur.GroupId.HasValue || cur.GroupId != grp.GroupId) { gsfu.AllGroups.Add(new GroupSummary() { GroupCode = grp.GroupCode, GroupName = grp.GroupName, Objective = grp.Objective, activeTimeZone = grp.TimeZone }); } } return(gsfu); }
public UserResponse CreateProfileUser(UserDTO user, ApiContext apiContext) { _context = (MICAUMContext)DbManager.GetContext(apiContext.ProductType, apiContext.ServerType); var userDetails = user.UserDetails.First(); //var userAddress = user.UserAddress.FirstOrDefault(); EmailTest emailTest = new EmailTest(); if (string.IsNullOrEmpty(userDetails.UserId)) { var aspNet = _context.AspNetUsers.SingleOrDefault(x => x.UserName == userDetails.Email); if (aspNet == null) { userDetails.RoleId = null; userDetails.UserName = userDetails.Email; userDetails.CreatedDate = DateTime.Now; //userDetails.ProfileImage = userDetails.ProfileImage; AspNetUsers _users = _mapper.Map <AspNetUsers>(user); if (string.IsNullOrEmpty(_users.Id)) { _users.Id = Guid.NewGuid().ToString(); _users.UserName = userDetails.Email; _users.Email = userDetails.Email; _users.FirstTimeLogin = 0; _users.PasswordHash = Utilities.GenerateDefaultPassword(); emailTest.To = userDetails.Email; emailTest.Subject = "User profile creation"; emailTest.Message = "Your account has been created with Username:"******"\n" + "Please use this for login."; _context.AspNetUsers.Add(_users); } _context.SaveChanges(); var _usersDTOs = _mapper.Map <UserDTO>(_users); SendEmailAsync(emailTest); return(new UserResponse { Status = BusinessStatus.Created, users = _usersDTOs, Id = _usersDTOs.Id, ResponseMessage = $"User created successfully! \n Login with: {_usersDTOs.Email}" }); } else { return(new UserResponse { Status = BusinessStatus.Error, ResponseMessage = $"User already exists" }); } } else { //var userAddress = user.UserAddress.ToList(); AspNetUsers _users = _mapper.Map <AspNetUsers>(user); var _usersDetail = _mapper.Map <TblUserDetails>(userDetails); //var _useraddress = _mapper.Map<TblUserAddress>(userAddress); var _useraddress1 = _mapper.Map <HashSet <TblUserAddress> >(user.UserAddress); //_context.TblUserDetails.Update(_usersDetail); //_context.TblUserAddress.Update(_useraddress); _context.Update(_usersDetail); foreach (var item in _useraddress1) { _context.Update(item); } _context.SaveChanges(); return(new UserResponse { Status = BusinessStatus.Created, users = user, Id = _usersDetail.UserId, ResponseMessage = $"User modified successfully!" }); } }
public virtual AspNetUsers Login(AspNetUsers obj) { return(db.GetTable <AspNetUsers>().Where(x => x.UserName == obj.UserName).FirstOrDefault()); }
public void Connect(string userName, string email, Microsoft.AspNet.SignalR.Hubs.IHubCallerConnectionContext <dynamic> Clients2, string id) { emailIDLoaded = email; //var id = Context.ConnectionId; //using (DB_102707_zonaflEntities dc = new DB_102707_zonaflEntities()) //{ ChatUserDetailRepository <ChatUserDetail> chatud = new ChatUserDetailRepository <ChatUserDetail>(); OfferRepository <Offer> offerrepo = new OfferRepository <Offer>(); OfferUserRepository <OfferUser> offeurrepo = new OfferUserRepository <OfferUser>(); OfferUserRepository <AspNetUsers> userrepo = new OfferUserRepository <AspNetUsers>(); ChatUserDetail item = chatud.GetList(new { EmailID = email }).FirstOrDefault(); //ChatUserDetail item=chatud.GetList("where EmailID='" + email+"'").FirstOrDefault(); //var item = dc.ChatUserDetails.FirstOrDefault(x => x.EmailID == email); if (item != null) { chatud.Delete(item.Id); //dc.ChatUserDetails.Remove(item); //dc.SaveChanges(); // Disconnect Clients2.All.onUserDisconnectedExisting(item.ConnectionId, item.UserName); } AspNetUsers user = userrepo.GtUserByEmail(email); if (chatud.GetList(new { EmailId = user.Email }).FirstOrDefault() == null) { var userdetails = new ChatUserDetail { ConnectionId = id, UserName = userName, EmailID = email }; chatud.Insert(userdetails); } List <ChatUserDetail> Users = new List <ChatUserDetail>(); if (!user.Freelance) { List <Offer> offertsuser = offerrepo.GetOffertsByContractorEmail(email); string valueoffer = string.Join(",", offertsuser.Select(e => e.Id).ToArray()); Users = chatud.GetUsersByOfferContractorid(valueoffer); } else { List <OfferUser> offertsuser = offeurrepo.GetOffersUser(user.Id); string valueoffer = string.Join(",", offertsuser.Select(e => e.IdOffer).ToArray()); Users = chatud.GetContractorsByOffers(valueoffer); } //var Users = chatud.GetList().ToList(); if (Users.Where(x => x.EmailID == email).ToList().Count == 0) { //var userdetails = new ChatUserDetail //{ // ConnectionId = id, // UserName = userName, // EmailID = email //}; //chatud.Insert(userdetails); //dc.SaveChanges(); // send to caller var connectedUsers = chatud.GetList(); ChatMessageDetailRepository <ChatMessageDetail> chatmd = new ChatMessageDetailRepository <ChatMessageDetail>(); var CurrentMessage = chatmd.GetList();//dc.ChatMessageDetails.ToList(); Clients2.Caller.onConnected(id, userName, connectedUsers, CurrentMessage); // } // send to all except caller client Clients2.AllExcept(id).onNewUserConnected(id, userName, email); } }
/// <summary> /// Deletes and ban's the user. /// </summary> /// <param name="userID">The user id.</param> /// <param name="user">The MemberShip User.</param> /// <param name="userIpAddress">The user's IP address.</param> /// <returns> /// Returns if Deleting was successfully /// </returns> public bool DeleteAndBanUser(int userID, AspNetUsers user, string userIpAddress) { // Update Anti SPAM Stats this.GetRepository <Registry>().IncrementBannedUsers(); // Ban IP ? if (this.Get <BoardSettings>().BanBotIpOnDetection) { this.GetRepository <BannedIP>().Save( null, userIpAddress, $"A spam Bot who was trying to register was banned by IP {userIpAddress}", userID); // Clear cache this.Get <IDataCache>().Remove(Constants.Cache.BannedIP); if (this.Get <BoardSettings>().LogBannedIP) { this.Get <ILogger>().Log( userID, "IP BAN of Bot", $"A spam Bot who was banned by IP {userIpAddress}", EventLogTypes.IpBanSet); } } // Ban Name ? this.GetRepository <BannedName>().Save( null, user.UserName, "Name was reported by the automatic spam system."); // Ban User Email? this.GetRepository <BannedEmail>().Save( null, user.Email, "Email was reported by the automatic spam system."); // Delete the images/albums both from database and physically. var uploadDir = HttpContext.Current.Server.MapPath( string.Concat(BaseUrlBuilder.ServerFileRoot, BoardFolders.Current.Uploads)); var dt = this.GetRepository <UserAlbum>().ListByUser(userID); dt.ForEach(dr => this.Get <IAlbum>().AlbumImageDelete(uploadDir, dr.ID, userID, null)); // delete posts... var messageIds = this.GetRepository <Message>().GetAllUserMessages(userID).Select(m => m.ID).Distinct() .ToList(); messageIds.ForEach(x => this.GetRepository <Message>().Delete(x, true, string.Empty, 1, true)); this.Get <AspNetUsersManager>().Delete(user); this.GetRepository <User>().Delete(userID); if (this.Get <BoardSettings>().LogUserDeleted) { this.Get <ILogger>().Log( BoardContext.Current.PageUserID, "UserMembershipHelper.DeleteUser", $"User {user.UserName} was deleted by the automatic spam check system.", EventLogTypes.UserDeleted); } // clear the cache this.Get <IDataCache>().Remove(Constants.Cache.UsersOnlineStatus); this.Get <IDataCache>().Remove(Constants.Cache.BoardUserStats); this.Get <IDataCache>().Remove(Constants.Cache.UsersDisplayNameCollection); return(true); }
public async Task <IActionResult> OnPostConfirmationAsync(string returnUrl = null) { returnUrl = returnUrl ?? Url.Content("~/"); // Get the information about the user from the external login provider var info = await _signInManager.GetExternalLoginInfoAsync(); if (info == null) { ErrorMessage = "Error loading external login information during confirmation."; return(RedirectToPage("./Login", new { ReturnUrl = returnUrl })); } if (ModelState.IsValid) { var user = new AspNetUsers { UserName = Input.Email, Email = Input.Email }; var result = await _userManager.CreateAsync(user); if (result.Succeeded) { result = await _userManager.AddLoginAsync(user, info); if (result.Succeeded) { _logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider); // If account confirmation is required, we need to show the link if we don't have a real email sender if (_userManager.Options.SignIn.RequireConfirmedAccount) { return(RedirectToPage("./RegisterConfirmation", new { Email = Input.Email })); } await _signInManager.SignInAsync(user, isPersistent : false); var userId = await _userManager.GetUserIdAsync(user); var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); var callbackUrl = Url.Page( "/Account/ConfirmEmail", pageHandler: null, values: new { area = "Identity", userId = userId, code = code }, protocol: Request.Scheme); await _emailSender.SendEmailAsync(Input.Email, "Confirm your email", $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>."); return(LocalRedirect(returnUrl)); } } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } LoginProvider = info.LoginProvider; ReturnUrl = returnUrl; return(Page()); }
/// <summary> /// Returns true if the user is in the specified role /// </summary> /// <param name="user"> /// The user. /// </param> /// <param name="role"> /// The role. /// </param> /// <returns> /// The <see cref="bool"/>. /// </returns> public bool IsInRole(AspNetUsers user, string role) { return(this.Get <AspNetUsersManager>().IsInRole(user.Id, role)); }
public PartialViewResult ChangeUserPersonData(ProcedureGetUserData_Result modal, HttpPostedFileBase Photo) { if (!ModelState.IsValid) { return(PartialView(modal)); } AspNetUsers user = db.AspNetUsers.Find(User.Identity.GetUserId()); user.Country = modal.Country; user.MailingAddress = modal.MailingAddress; user.PhoneNumber = modal.PhoneNumber; user.Telephone = modal.Telephone; string result = ""; if (Photo != null) { //檢查員工 if (cm.checkIsEmployee(User.Identity.GetUserName())) { //檢查權限更新頭像的權限ID為1 if (cm.checkHasPower(User.Identity.GetUserName(), 1)) { byte[] Tmpphotobytes = new byte[Photo.InputStream.Length]; Photo.InputStream.Read(Tmpphotobytes, 0, Tmpphotobytes.Length); ConfirmPhoto cp = new ConfirmPhoto { Photo = Tmpphotobytes }; db.ConfirmPhoto.Add(cp); db.SaveChanges(); //檢查覆核 string userUserName = User.Identity.GetUserName(); string userName = User.Identity.Name; string confirmDescription = ""; confirmDescription += "<div style='border:1px solid black;margin: 2px'>"; confirmDescription += "<p>欲更新頭像:</p>"; confirmDescription += "<div style='border:1px solid black;margin: 2px'>"; confirmDescription += "<img src='" + Url.Action("GetConfirmImageFile", "Manage", new { area = "" }) + "?pid=" + cp.Id + "' style='height:200px;width:200px;border-radius:50%'/>"; confirmDescription += "</div>"; confirmDescription += "</div>"; int? outurpchSn; string ckConfirm = cm.checkNeedConfirm(out outurpchSn, User.Identity.GetUserName(), 1, Url.Action("UserConfirmUserPower", "ConfirmUserPower", new { area = "" }), confirmDescription); //string ckConfirm = ""; if (ckConfirm == "") { //byte[] photobytes = new byte[Photo.InputStream.Length]; //Photo.InputStream.Read(photobytes, 0, photobytes.Length); user.Photo = Tmpphotobytes; } else { result = ckConfirm; //string base64 = Convert.ToBase64String(bytes); //byte[] bytes = Convert.FromBase64String(base64); if (outurpchSn.HasValue) { //byte[] photobytes = new byte[Photo.InputStream.Length]; //Photo.InputStream.Read(photobytes, 0, photobytes.Length); //string PhotoByteStr = Convert.ToBase64String(photobytes); StringBuilder PhotoByteStr = new StringBuilder(); foreach (byte pbtmp in Tmpphotobytes) { StringBuilder ppptmp = new StringBuilder(); ppptmp.Append(pbtmp); ppptmp.Append(","); PhotoByteStr.Append(ppptmp.ToString()); } string tableName1 = ""; string primaryColumnName1 = ""; string primaryColumnValue1 = ""; SaveExecConfirmDataModelActionEnum execAction1; string primaryColumnType1 = ""; List <SaveExecConfirmDataModel> cecdm2 = new List <SaveExecConfirmDataModel>(); tableName1 = "AspNetUsers"; primaryColumnName1 = "Id"; primaryColumnValue1 = User.Identity.GetUserId(); execAction1 = SaveExecConfirmDataModelActionEnum.Update; primaryColumnType1 = "string"; List <string> cColumnName = new List <string>(); List <string> cColumnValue = new List <string>(); List <string> cColumnType = new List <string>(); cColumnName.Add("Photo"); cColumnValue.Add(PhotoByteStr.ToString()); cColumnType.Add("Byte[]"); SaveExecConfirmDataModel cecdm1 = new SaveExecConfirmDataModel { urpchSn = outurpchSn.Value, tableName = tableName1, primaryColumnName = primaryColumnName1, primaryColumnValue = primaryColumnValue1, primaryColumnType = primaryColumnType1, execAction = execAction1, cColumnName = cColumnName, cColumnValue = cColumnValue, cColumnType = cColumnType }; cm.SaveExecConfirmData(cecdm1); } } } else { result = "沒有權限"; } } else { byte[] photobytes = new byte[Photo.InputStream.Length]; Photo.InputStream.Read(photobytes, 0, photobytes.Length); user.Photo = photobytes; } } db.SaveChanges(); //dbUser.UpdateWithoutNull(user); if (db.IsEmployee.Find(User.Identity.GetUserName()) != null) { ViewBag.AccountType = "員工"; } else { ViewBag.AccountType = "會員"; } var userdata = db.ProcedureGetUserData(User.Identity.GetUserId()).First(); if (result != "") { TempData["AlertConfirm"] = result; } return(PartialView(userdata)); }
/// <summary> /// Create a user with the given password /// </summary> /// <param name="user"> /// The user. /// </param> /// <param name="password"> /// The password. /// </param> /// <returns> /// The <see cref="IdentityResult"/>. /// </returns> public IdentityResult Create(AspNetUsers user, string password) { return(this.Get <AspNetUsersManager>().Create(user, password)); }
public void Update(AspNetUsers entity) { _dbContext.Entry(entity).State = EntityState.Modified; _dbContext.SaveChanges(); }
public int Add(AspNetUsers account) { _db.AspNetUsers.Add(account); _db.SaveChangesAsync(); return(1); }
public void Create(AspNetUsers entity) { _dbContext.Entry(entity).State = EntityState.Added; _dbContext.AspNetUsers.Add(entity); _dbContext.SaveChanges(); }
public AspNetUsers GetData(string id) { AspNetUsers account = _db.AspNetUsers.Find(id); return(account); }
public async Task <ActionResult> Register(RegisterViewModel model, string Roles) { SelectList roles = new SelectList(db.AspNetRoles, "Id", "Name"); ViewBag.Roles = roles; var _users = db.AspNetUsers.ToList(); List <SelectListItem> _UsersRoles = new List <SelectListItem>(); foreach (var _user in _users) { var currentRoles = UserManager.GetRolesAsync(_user.Id); _UsersRoles.Add(new SelectListItem() { Text = _user.UserName, Value = currentRoles.Result.FirstOrDefault() }); } ViewBag.UsersAndRoles = _UsersRoles; ExcelMembers excelMembers = new ExcelMembers(); Error error = excelMembers.SplitFullName(model.UserLastFirstName, null, 0, out string lastName, out string firstName, out string middleName); if (error.errCode != ErrorDetail.Success) { ModelState.AddModelError("User Name Error", error.errMsg + ". Please enter last name and first name, separated by a comma."); return(View(model)); } if (ModelState.IsValid) { string selectedRole = roles.Where(t => t.Value == Roles).FirstOrDefault().Text; var user = new ApplicationUser { UserName = model.Email + ":" + selectedRole, Email = model.Email }; // placing selected Role Name to User Name in AspNetUsers table var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { using (LRCEntities context = new LRCEntities()) { try { AspNetUsers aUser = context.AspNetUsers.Where(s => s.Email.ToUpper() == model.Email.ToUpper()).FirstOrDefault(); aUser.LastFirstName = model.UserLastFirstName; context.SaveChanges(); } catch (DbEntityValidationException ex) { error.errCode = ErrorDetail.DataImportError; error.errMsg = ErrorDetail.GetMsg(error.errCode); foreach (DbEntityValidationResult validationError in ex.EntityValidationErrors) { error.errMsg += ". Object: " + validationError.Entry.Entity.ToString(); foreach (DbValidationError err in validationError.ValidationErrors) { error.errMsg += ". " + err.ErrorMessage; } } } } if (error.errCode != ErrorDetail.Success) { ModelState.AddModelError("User Name Update Failed", error.errMsg); return(View(model)); } return(RedirectToAction("RegistrationRequestSentToAdmin", "Account")); } AddErrors(result); } // If we got this far, something failed, redisplay form return(View(model)); }
public static void RegisterGrids() { MVCGridDefinitionTable.Add("InOutUserGrid", new MVCGridBuilder <vst_InOut>() .WithAuthorizationType(AuthorizationType.AllowAnonymous) .AddColumns(cols => { // Add your columns here cols.Add("Fecha").WithColumnName(Resources.Descripciones.GridGastoFecha) .WithFiltering(false) .WithHeaderText(" ") //.WithHeaderText(Resources.Descripciones.GridGastoFecha) .WithCellCssClassExpression(p => "col-sm-1") //.WithValueExpression(i => i.Fecha.HasValue ? i.Fecha.Value.ToShortDateString() : ""); .WithValueExpression(i => i.Fecha.ToShortDateString()); cols.Add("TipoGasto") //.WithColumnName(Resources.Descripciones.GridTipoGasto) .WithFiltering(true) .WithHeaderText(" ") .WithCellCssClassExpression(p => "col-sm-2") //.WithHeaderText(Resources.Descripciones.GridTipoGasto) .WithValueExpression(i => i.Descripcion); // use the Value Expression to return the cell text for this column cols.Add("SubTipoGasto") //.WithColumnName(Resources.Descripciones.GridTipoGasto) .WithFiltering(true) .WithHeaderText(" ") .WithCellCssClassExpression(p => "col-sm-2") //.WithHeaderText(Resources.Descripciones.GridTipoGasto) .WithValueExpression(i => i.Descripcion_Subtipo); // use the Value Expression to return the cell text for this column cols.Add("Concepto").WithColumnName(Resources.Descripciones.GridGastoConcepto) .WithCellCssClassExpression(p => "col-sm-4") .WithHeaderText(" ") //.WithHeaderText(Resources.Descripciones.GridGastoConcepto) .WithValueExpression(i => i.Concepto) // use the Value Expression to return the cell text for this column .WithFiltering(true); cols.Add("Precio").WithColumnName(Resources.Descripciones.GridGastoImporte) .WithFiltering(true) .WithHeaderText(" ") .WithCellCssClassExpression(p => "col-sm-1") //.WithHeaderText(Resources.Descripciones.GridGastoImporte) .WithValueExpression(i => i.Precio.ToString()); // use the Value Expression to return the cell text for this column /* * cols.Add("Delete").WithHtmlEncoding(false) * .WithFiltering(false) * .WithSorting(false) * .WithHeaderText(" ") * .WithCellCssClassExpression(p => "col-sm-2") * .WithValueExpression(i => i.idGasto.ToString()) * .WithValueTemplate("<a href = '/Gastos/Edit/{value}'><img src='/Img/iconos/edit.png'></a>" + " <a href = '/Gastos/Del/{value}'><img src='/Img/iconos/delete24.png'</a>" + " <a href = '/Gastos/Copy/{value}'><img src='/Img/iconos/copy.png'</a>" + ); */ cols.Add("Butons").WithHtmlEncoding(false) .WithFiltering(false) .WithSorting(false) .WithHeaderText(" ") .WithCellCssClassExpression(p => "col-sm-2") .WithValueExpression(i => i.idGasto.ToString()) .WithValueExpression((p, c) => { StringBuilder sb = new StringBuilder(); if (bool.Parse(p.GastoEditable.GetValueOrDefault().ToString())) { string Action = c.UrlHelper.Action("Edit", "Gastos", new { id = p.idGasto }); string href = " href= " + Action + " class=approve >"; sb.Append(" <a "); // sb.Append(target); sb.Append(href); sb.Append("<img src = '/Img/iconos/edit.png' >"); sb.Append("</a> "); Action = c.UrlHelper.Action("Delete", "Gastos", new { id = p.idGasto }); href = " href= " + Action + " class=approve >"; sb.Append(" <a "); // sb.Append(target); sb.Append(href); sb.Append("<img src = '/Img/iconos/Delete24.png' >"); sb.Append("</a> "); //sb.Append("<img src = \"/Img/iconos/Delete24.png\" style=\"cursor: hand; cursor: pointer\" name = \"image\" data-toggle = \"modal\" data-target = \"#myModalDelGasto\" data-id = \"" + p.idGasto + "\" data-datos = \"" + p.Concepto + "\" />"); if (p.GastoRecurrente == false) { Action = c.UrlHelper.Action("Copy", "Gastos", new { id = p.idGasto }); href = " href= " + Action + " class=approve >"; sb.Append(" <a "); sb.Append(href); sb.Append("<img src = '/Img/iconos/copy.png' >"); sb.Append("</a> "); } //sb.Append("<img src = \"/Img/iconos/ver.png\" style=\"cursor: hand; cursor: pointer\" name = \"image\" data-toggle = \"modal\" data-target = \"#myModalVerGasto\" data-id = \"" + p.idGasto + "\" data-datos = \"" + p.Concepto + "|" + p.Descripcion + "|" + p.Precio + "|" + p.Fecha + "|" + p.GrupoGasto + "|" + p.GastoComputable + "\" />"); } else { //sb.Append("<img src = \"/Img/iconos/ver.png\" style=\"cursor: hand; cursor: pointer\" name = \"image\" data-toggle = \"modal\" data-target = \"#myModalVerGasto\" data-id = \"" + p.idGasto + "\" data-datos = \"" + p.Concepto + "|" + p.Descripcion + "|" + p.Precio + "|" + p.Fecha + "|" + p.GrupoGasto + "|" + p.GastoComputable + "\" />"); string Action = c.UrlHelper.Action("Ver", "Gastos", new { id = p.idGasto }); string href = " href= " + Action + " class=approve >"; sb.Append(" <a "); //sb.Append(target); sb.Append(href); sb.Append("<img src = '/Img/iconos/ver.png' >"); sb.Append("</a> "); Action = c.UrlHelper.Action("Copy", "Gastos", new { id = p.idGasto }); href = " href= " + Action + " class=approve >"; sb.Append(" <a "); sb.Append(href); sb.Append("<img src = '/Img/iconos/copy.png' >"); sb.Append("</a> "); } return(sb.ToString()); }); }) .WithPageParameterNames("user") .WithPaging(true, 10) //.WithSorting(true, "Concepto", SortDirection.Dsc) .WithRowCssClassExpression(x => (x.GastoRecurrente == true) ? "info" : (x.Precio > 300) ? "danger" : "") .WithSummaryMessage(" {0} - {1} ({2})") .WithFiltering(true) .WithProcessingMessage("....") .WithNextButtonCaption("") .WithPreviousButtonCaption("") .WithRetrieveDataMethod((options) => { string _pEmail = options.QueryOptions.GetPageParameterString("user"); string _pIdioma = System.Threading.Thread.CurrentThread.CurrentCulture.ToString().Substring(0, 2); var result = new QueryResult <vst_InOut>(); using (var context = new ExpensesEF.Entities()) { int _idioma = context.Idiomas.Where(x => x.codigo == _pIdioma).FirstOrDefault().idIdioma; //string _user = context.AspNetUsers.Where(x => x.Email == _pEmail).FirstOrDefault().Id.ToString(); AspNetUsers _usuario = context.AspNetUsers.Where(x => x.Email == _pEmail).FirstOrDefault(); string _user = _usuario.Id.ToString(); bool _GastoSinRecurrentes = _usuario.VerGastosSinOConRecurrentes.GetValueOrDefault(); string _concepto = ""; if (options.QueryOptions.Filters.Count > 0) { _concepto = ((options.QueryOptions.GetFilterString("Concepto") == null) ? "" : options.QueryOptions.GetFilterString("Concepto").ToString()); } System.Linq.IQueryable <vst_InOut> query; if (_GastoSinRecurrentes) { //query = (context.vst_InOut.Where(x => x.idIdioma == _idioma && (x.IdIdiomaSubTipo == _idioma || x.IdIdiomaSubTipo == null) && x.idUserGasto == _user && (x.Concepto.Contains(_concepto) && x.Descripcion.Contains(_TipoGasto))).OrderByDescending(x => x.Fecha).ThenByDescending(x => x.idGasto).AsQueryable()); query = (context.vst_InOut.Where(x => x.idIdioma == _idioma && (x.IdIdiomaSubTipo == _idioma || x.IdIdiomaSubTipo == null) && x.idUserGasto == _user && (x.Concepto.Contains(_concepto) || x.Descripcion.Contains(_concepto) || x.Descripcion_Subtipo.Contains(_concepto))).OrderByDescending(x => x.Fecha).ThenByDescending(x => x.idGasto).AsQueryable()); } else { //query = (context.vst_InOut.Where(x => x.GastoRecurrente == false && x.idIdioma == _idioma && (x.IdIdiomaSubTipo == _idioma || x.IdIdiomaSubTipo == null) && x.idUserGasto == _user && (x.Concepto.Contains(_concepto) && x.Descripcion.Contains(_TipoGasto))).OrderByDescending(x => x.Fecha).ThenByDescending(x => x.idGasto).AsQueryable()); query = (context.vst_InOut.Where(x => x.GastoRecurrente == false && x.idIdioma == _idioma && (x.IdIdiomaSubTipo == _idioma || x.IdIdiomaSubTipo == null) && x.idUserGasto == _user && (x.Concepto.Contains(_concepto) || x.Descripcion.Contains(_concepto) || x.Descripcion_Subtipo.Contains(_concepto))).OrderByDescending(x => x.Fecha).ThenByDescending(x => x.idGasto).AsQueryable()); } result.TotalRecords = query.Count(); if (options.QueryOptions.GetLimitOffset().HasValue) { query = query.Skip(options.QueryOptions.GetLimitOffset().Value).Take(options.QueryOptions.GetLimitRowcount().Value); } result.Items = query.ToList(); } return(result); } ) //.WithRowCssClassExpression(new ExpensesEF.Entities().AspNetUsers.Where(x=>) ? "info" : (x.Precio > 300) ? "danger" : "") ); MVCGridDefinitionTable.Add("GastosRecurrentesGrid", new MVCGridBuilder <vst_GastosRecurrentes>() .WithAuthorizationType(AuthorizationType.AllowAnonymous) .AddColumns(cols => { cols.Add("Concepto").WithColumnName(Resources.Descripciones.GridGastoConcepto) .WithFiltering(true) .WithHeaderText(" ") .WithCellCssClassExpression(p => "col-sm-3") .WithValueExpression(i => i.Concepto.ToString()); cols.Add("Precio").WithColumnName(Resources.Descripciones.GridGastoImporte) .WithFiltering(true) .WithHeaderText(" ") .WithCellCssClassExpression(p => "col-sm-1") .WithValueExpression(i => i.Precio.ToString()); cols.Add("Periodicidad") .WithFiltering(true) .WithHeaderText(" ") .WithCellCssClassExpression(p => "col-sm-1") .WithValueExpression(i => i.Descripcion.ToString()); cols.Add("Activo") .WithHeaderText(" ") .WithCellCssClassExpression(p => "col-sm-1") .WithValueExpression(i => i.TextoActivo.ToString()); cols.Add("Computable") .WithHeaderText(" ") .WithCellCssClassExpression(p => "col-sm-2") .WithValueExpression(i => i.TextoComputable.ToString()); cols.Add("Fecha").WithColumnName(Resources.Descripciones.GridGastoFecha) .WithFiltering(false) .WithHeaderText(" ") .WithCellCssClassExpression(p => "col-sm-1") .WithValueExpression(i => i.SiguienteEjecucion.ToShortDateString()); cols.Add("Butons").WithHtmlEncoding(false) .WithFiltering(false) .WithSorting(false) .WithHeaderText(" ") .WithCellCssClassExpression(p => "col-sm-2") .WithValueExpression(i => i.idGastoRecurrente.ToString()) .WithValueExpression((p, c) => { StringBuilder sb = new StringBuilder(); /* * string Action = c.UrlHelper.Action("EditRecurrente", "Gastos", new { id = p.idGastoRecurrente }); * string href = " href= " + Action + " class=approve >"; * sb.Append(" <a "); * // sb.Append(target); * sb.Append(href); * sb.Append("<img src = '/Img/iconos/edit.png' >"); * sb.Append("</a> "); * * * Action = c.UrlHelper.Action("DelRecurrente", "Gastos", new { id = p.idGastoRecurrente }); * href = " href= " + Action + " class=approve >"; * sb.Append(" <a "); * * sb.Append(href); * sb.Append("<img src = '/Img/iconos/delete24.png' >"); * sb.Append("</a> "); */ //class=\"btn btn-primary btn-lg\" //"<img src = '/Img/iconos/delete24.png' >" + " //string _text = "<button type = \"button\" data-toggle=\"modal\" data-target=\"#myModal\" data-myvalue=\"" + p.idGastoRecurrente + "\">" + "dassd" + "</button>"; //string _text = "<button type = \"button\" data-toggle=\"modal\" data-target=\"#myModal\" data-myvalue=\"" + p.idGastoRecurrente + "\" data-myvalue2=\"" + "ver" + "\" >" + "edit" + "</button>"; string _text = "<input type = \"image\" src = \"/Img/iconos/edit.png\" name = \"image\" data-toggle = \"modal\" data-target = \"#myModalEdit\" data-id = \"" + p.idGastoRecurrente + "\" data-datos = \"" + p.Concepto + "|" + p.idTipoPago + "|" + p.idtipoGastoRecurrente + "|" + p.Periocidad + "|" + p.Precio + "|" + p.GastoComputable + "|" + p.Activo + "|" + p.Descripcion_SubTipo + "\" />"; _text += "<input type = \"image\" src = \"/Img/iconos/Delete24.png\" name = \"image\" data-toggle = \"modal\" data-target = \"#myModalDel\" data-id = \"" + p.idGastoRecurrente + "\" data-datos = \"" + p.Concepto + "\" />"; sb.Append(_text); return(sb.ToString()); }); }) .WithPageParameterNames("user") .WithPaging(true, 20) .WithSorting(true, "Concepto", SortDirection.Dsc) .WithSummaryMessage(" {0} - {1} ({2})") .WithFiltering(true) .WithProcessingMessage("....") .WithNextButtonCaption("") .WithPreviousButtonCaption("") .WithRetrieveDataMethod((options) => { string _pEmail = options.QueryOptions.GetPageParameterString("user"); string _pIdioma = System.Threading.Thread.CurrentThread.CurrentCulture.ToString().Substring(0, 2); var result = new QueryResult <vst_GastosRecurrentes>(); using (var context = new ExpensesEF.Entities()) { int _idioma = context.Idiomas.Where(x => x.codigo == _pIdioma).FirstOrDefault().idIdioma; string _user = context.AspNetUsers.Where(x => x.Email == _pEmail).FirstOrDefault().Id.ToString(); var query = (context.vst_GastosRecurrentes.Where(x => x.idIdioma == _idioma && (x.IdIdiomaSubTipo == _idioma || x.IdIdiomaSubTipo == null) && x.idUserGastoRecurrente == _user).OrderByDescending(x => x.SiguienteEjecucion).ThenByDescending(x => x.idGastoRecurrente).AsQueryable()); result.TotalRecords = query.Count(); if (options.QueryOptions.GetLimitOffset().HasValue) { query = query.Skip(options.QueryOptions.GetLimitOffset().Value).Take(options.QueryOptions.GetLimitRowcount().Value); } result.Items = query.ToList(); } return(result); } ) ); }
/// <summary> /// The create board. /// </summary> /// <param name="adminName">The admin name.</param> /// <param name="adminPassword">The admin password.</param> /// <param name="adminEmail">The admin email.</param> /// <param name="boardName">The board name.</param> /// <param name="createUserAndRoles">The create user and roles.</param> /// <returns>Returns if the board was created or not</returns> protected bool CreateBoard( [NotNull] string adminName, [NotNull] string adminPassword, [NotNull] string adminEmail, [NotNull] string boardName, bool createUserAndRoles) { int newBoardId; var cult = StaticDataHelper.Cultures(); var langFile = "english.xml"; cult.Where(c => c.CultureTag == this.Culture.SelectedValue) .ForEach(c => langFile = c.CultureFile); if (createUserAndRoles) { var user = new AspNetUsers { Id = Guid.NewGuid().ToString(), ApplicationId = this.PageContext.BoardSettings.ApplicationId, UserName = adminName, LoweredUserName = adminName, Email = adminEmail, IsApproved = true }; // Create new admin users var result = this.Get <IAspNetUsersHelper>().Create(user, adminPassword); if (!result.Succeeded) { this.PageContext.AddLoadMessage( $"Create User Failed: {result.Errors.FirstOrDefault()}", MessageTypes.danger); return(false); } // Create groups required for the new board this.Get <IAspNetRolesHelper>().CreateRole("Administrators"); this.Get <IAspNetRolesHelper>().CreateRole("Registered"); // Add new admin users to group this.Get <IAspNetRolesHelper>().AddUserToRole(user, "Administrators"); // Create Board newBoardId = this.DbCreateBoard( boardName, langFile, user); } else { // new admin var newAdmin = this.Get <IAspNetUsersHelper>().GetUser(); // Create Board newBoardId = this.DbCreateBoard( boardName, langFile, newAdmin); } if (newBoardId <= 0 || !Config.MultiBoardFolders) { return(true); } // Successfully created the new board var boardFolder = this.Server.MapPath(Path.Combine(Config.BoardRoot, $"{newBoardId}/")); // Create New Folders. if (!Directory.Exists(Path.Combine(boardFolder, "Images"))) { // Create the Images Folders Directory.CreateDirectory(Path.Combine(boardFolder, "Images")); // Create Sub Folders Directory.CreateDirectory(Path.Combine(boardFolder, "Images\\Avatars")); Directory.CreateDirectory(Path.Combine(boardFolder, "Images\\Categories")); Directory.CreateDirectory(Path.Combine(boardFolder, "Images\\Forums")); Directory.CreateDirectory(Path.Combine(boardFolder, "Images\\Medals")); } if (!Directory.Exists(Path.Combine(boardFolder, "Uploads"))) { Directory.CreateDirectory(Path.Combine(boardFolder, "Uploads")); } return(true); }
/// <summary> /// The user authenticated. /// </summary> /// <param name="user"> /// The user. /// </param> private void UserAuthenticated(AspNetUsers user) { this.Get <IAspNetUsersHelper>().SignIn(user, this.RememberMe.Checked); this.Page.Response.Redirect(this.Request.RawUrl); }
public ActionResult LoginUser(RegisterBindingModel model) { var user = new ApplicationUser() { UserName = model.UserName, Email = model.Email, Empresa = model.Empresa, Freelance = model.Freelance }; AspNetUsers aspuser = new AspNetUsers(); try { ZonaFl.Business.SubSystems.SUser usern = new Business.SubSystems.SUser(); ApplicationUser useru = null; if (user.UserName.Contains("@")) { useru = UserManager.FindByEmail(user.UserName); } else { useru = UserManager.FindByName(user.UserName); } if (useru != null) { if (useru.EmailConfirmed) { bool validuser = false; if (useru != null) { validuser = UserManager.CheckPassword(useru, model.PasswordHash); if (validuser) { var identity = new System.Security.Principal.GenericIdentity(useru.UserName); //SetPrincipal(new System.Security.Principal.GenericPrincipal(identity, null)); } else { return(Json(new { success = false, issue = user, errors = "Contraseña o usuario incorrecto, favor volver a ingresar los datos", tipo = user, UserEmail = aspuser.Email })); } //var useri = HttpContext.Current.User; //HttpContext.Current.User = useri; //RegisterBindingModel regbm = new RegisterBindingModel(); //regbm.InjectFrom(useru); //HttpSessionStateBase session = new HttpSessionStateWrapper(HttpContext.Current.Session); //SessionBag.Current.User = regbm; } if (useru.Freelance) { //return RedirectToAction("Index", "Offer", new { id = useru.Id }); return(Json(new { success = validuser, issue = useru, errors = "", tipo = useru, UserEmail = useru.Email, Url = Url.Content("/Offer/Index/" + useru.Id).ToString() })); } else if (useru.Empresa) { return(Json(new { success = validuser, issue = useru, errors = "", tipo = useru, UserEmail = useru.Email, Url = Url.Content("/Projects/Index/" + useru.Id).ToString() })); } else { return(Json(new { success = validuser, issue = useru, errors = "", tipo = useru, UserEmail = useru.Email, Url = Url.Content("/Administration/Users/Index?email=" + useru.Email).ToString() })); } } else { return(Json(new { success = false, issue = user, errors = "Usuario dado de baja o correo electrónico no confirmado, favor comunicarse con el administrador del sistema", tipo = user, UserEmail = aspuser.Email })); } } else { return(Json(new { success = false, issue = user, errors = "Usuario no encontrado, favor comunicarse con el administrador del sistema", tipo = user, UserEmail = aspuser.Email })); } } catch (Exception ex) { //throw new Exception(ex.Message); return(Json(new { success = false, issue = user, errors = ex.Message, tipo = user, UserEmail = aspuser.Email })); } return(Json(new { success = true, issue = model, errors = "", tipo = model, UserEmail = user.Email, Url = Url.Content("/Home/index").ToString() })); }