public async Task <IActionResult> ExternalLoginConfirmation(ExternalLoginViewModel model, string returnUrl = null) { if (ModelState.IsValid) { // Get the information about the user from the external login provider var info = await _signInManager.GetExternalLoginInfoAsync(); if (info == null) { throw new ApplicationException("Error loading external login information during confirmation."); } var user = new Data.Models.User { UserName = model.Email, Email = model.Email }; var result = await _userManager.CreateAsync(user); if (result.Succeeded) { result = await _userManager.AddLoginAsync(user, info); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent : false); _logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider); return(RedirectToLocal(returnUrl)); } } AddErrors(result); } ViewData["ReturnUrl"] = returnUrl; return(View(nameof(ExternalLogin), model)); }
private User CommitToItem(Data.Models.User item) { var user = _db.Users.FirstOrDefault(u => u.UserId == item.UserId); if (user != null) { item = user; } item.EmailId = txtEmail.Text.Trim(); item.Name = txtName.Text.Trim(); item.Pwd = UtilityBL.Encrypt(txtPassword.Text, true); item.RoleId = Convert.ToInt32(ddlRoles.SelectedValue); item.Role = _db.Roles.Find(Convert.ToInt32(ddlRoles.SelectedValue)); item.ReportingId = Convert.ToInt32(ddlReporting.SelectedValue); item.User2 = _db.Users.Find(Convert.ToInt32(ddlReporting.SelectedValue)); item.Mobile = txtPhone.Text.Trim(); item.Active = true; item.Cities.Clear(); var cityList = GetSelectedCities(); foreach (var city in cityList) { item.Cities.Add(city); } item.PartnerCategorys.Clear(); var category = GetSelectedPartnerCategory(); foreach (var partner in category) { item.PartnerCategorys.Add(partner); } return(item); }
public bool CheckNickname(string nickname) { var users = UR.GetAllDates(); foreach (var i in users) { if (i.NickName == nickname) { User = i; } } if (User != null) { if (User.NickName == null) { return(false); } else { return(true); } } else { return(false); } }
public async Task <int> GetUserId() { if (_appCache.Contains(UserIdKey)) { return(_appCache.Get <int>(UserIdKey)); } int userId; var user = await _userService.GetByUserNameAsync(UserName); if (user == null) { // No user exists so let's create one user = new Data.Models.User { Name = UserName, UserName = UserName }; userId = await _userService.CreateAsync(user /*, _appConfigHelper.SystemUserId*/); } else { userId = user.Id; } _appCache.Add(UserIdKey, userId); return(userId); }
public bool CheckMail(string mail) { var users = UR.GetAllDates(); foreach (var i in users) { if (i.Email == mail) { User = i; } } if (User != null) { if (User.Email == null) { return(false); } else { return(true); } } else { return(false); } }
public async Task <ActionResult <Data.Models.User> > PatchUser(int userId, JsonPatchDocument <Data.Models.UserForUpdate> patchDocument) { try { Data.Entities.User dbUser = await _repository.GetUserAsync(userId); if (dbUser == null) { return(NotFound()); } var updatedUser = _mapper.Map <Data.Models.UserForUpdate>(dbUser); patchDocument.ApplyTo(updatedUser, ModelState); _mapper.Map(updatedUser, dbUser); if (await _repository.SaveChangesAsync()) { Data.Models.User savedUser = _mapper.Map <Data.Models.User>(await _repository.GetUserAsync(userId)); return(Ok(savedUser)); } else { return(StatusCode(StatusCodes.Status500InternalServerError, "Unable to save to database")); } } catch (Exception ex) { return(StatusCode(StatusCodes.Status500InternalServerError, "Unable to patch user " + ex.Message)); } }
public void Create(Data.Models.User user) { ApplicationDbContext db = new ApplicationDbContext(); db.Users.Add(user); db.SaveChanges(); }
public JsonResult NewUser(Data.Models.User user) { // Check if name is not used double if (string.IsNullOrWhiteSpace(user.Name) || _dataContext.Users.Any(a_item => a_item.Name == user.Name && a_item.ID != user.ID)) { return(Json(false)); } if (user.IsNew) { _dataContext.Users.Add(user); } else { var existingUser = _dataContext.Users.Single(a_item => a_item.ID == user.ID); existingUser.Name = user.Name; } _dataContext.SaveChanges(); var cookie = new HttpCookie(UserController.CoockieName, user.ID.ToString()) { Expires = DateTime.Now.AddDays(10) }; Response.AppendCookie(cookie); return(Json(true)); }
public bool Register(Data.Models.User user) { var result = UM.CreateAsync(User); return(true); }
private void SaveCiyData(Data.Models.User item) { var treeViewCity = (TreeView)frmUserInsert.FindControl("treeViewCity"); List <City> cities = new List <City>(); foreach (TreeNode node in treeViewCity.Nodes) { if (node.ChildNodes.Count > 0) { foreach (TreeNode child in node.ChildNodes) { if (child.Checked) { var id = Convert.ToInt32(child.Value); var city = _db.Cities.FirstOrDefault(c => c.CityId == id); if (city != null) { cities.Add(city); } } } } } item.Cities = cities; }
public async Task <ActionResult <Data.Models.User> > CreateNewUser(Data.Models.UserForCreate newUser) { Data.Entities.User dbNewUser = null; try { dbNewUser = _mapper.Map <Data.Entities.User>(newUser); } catch (Exception ex) { return(BadRequest("Input is in invalid format: " + ex.Message)); } if (dbNewUser == null) { return(BadRequest("Input is in invalid format")); } await _repository.AddAsync <Data.Entities.User>(dbNewUser); await _repository.SaveChangesAsync(); Data.Models.User addedUser = _mapper.Map <Data.Models.User>(dbNewUser); var url = _linkgenerator.GetPathByAction(HttpContext, "GetUserByUserId", "Users", addedUser); return(this.Created(url, addedUser)); }
public async Task <ActionResult <Data.Models.User> > UpdateUser(int userId, Data.Models.UserForUpdate updatedUser) { try { Data.Entities.User dbUser = await _repository.GetUserAsync(userId); if (dbUser == null) { return(NotFound()); } _mapper.Map(updatedUser, dbUser); if (await _repository.SaveChangesAsync()) { Data.Models.User savedUser = _mapper.Map <Data.Models.User>(dbUser); return(Ok(savedUser)); } else { return(BadRequest("Failed to update.")); } } catch (Exception ex) { return(StatusCode(StatusCodes.Status500InternalServerError, "Database exception: " + ex.Message)); } }
public bool CreateVet(EditableVeterinaryViewModel model) { try { var vet = new Data.Models.User() { ID = Guid.NewGuid(), Name = model.Name, Status = model.Status, Identification = model.Identification, NationalInsuranceNumber = model.NationalInsuranceNumber, CouncilNumber = model.CouncilNumber, EntryTime = model.EntryTime, DepartureTime = model.DepartureTime, Type = Enums.User.UserType.Vet, VeterinaryAllowedSpecies = EnumHelper.ListEnumToEnumFlag(model.AllowedSpecies.Select(a => (Enums.Pet.Specie)a)) }; _unitOfWork.User.Add(vet); _unitOfWork.Commit(); return(true); } catch (Exception ex) { return(false); } }
public ServiceResponse <Data.Models.User> CreateUser(Data.Models.User user) { try { _db.Users.Add(user); _db.SaveChanges(); return(new ServiceResponse <Data.Models.User> { IsSuccess = true, Message = "New User Added", Time = DateTime.UtcNow, Data = user }); } catch (Exception e) { return(new ServiceResponse <Data.Models.User> { IsSuccess = false, Message = e.StackTrace, Time = DateTime.UtcNow, Data = null }); } }
public async Task <string> GenerateJwtTokenAsync(Data.Models.User user, bool isRemember) { var claims = new List <Claim> { new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()), new Claim(ClaimTypes.Name, user.UserName) }; var roles = await _userManager.GetRolesAsync(user); foreach (var role in roles) { claims.Add(new Claim(ClaimTypes.Role, role)); } var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config.GetSection("AppSettings:Token").Value)); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature); var tokenDes = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(claims), Expires = isRemember ? DateTime.Now.AddDays(1) : DateTime.Now.AddHours(2), SigningCredentials = creds }; var tokenHandler = new JwtSecurityTokenHandler(); var token = tokenHandler.CreateToken(tokenDes); return(tokenHandler.WriteToken(token)); }
//public int? GetUserProfileId(int userId) //{ // return this._userRepository.Table.Where(w => w.Id == userId).Select(s => s.UserProfile_Id).FirstOrDefault(); //} public int Update(string fname, string lname, string email, int userId) { var profileId = this._userRepository.Table.Where(w => w.Id == userId).Select(s => s.UserProfile_Id).FirstOrDefault(); Data.Models.UserProfile oldProfile = _userProfileRepository.Table.Where(w => w.Id == profileId).FirstOrDefault(); Data.Models.User oldEmail = _userRepository.Table.Where(w => w.Id == userId).FirstOrDefault(); if (_userRepository.Table.Any(a => a.Email == email && a.Id != userId)) { return(101); } oldEmail.Email = email; _userRepository.Update(oldEmail); if (oldProfile != null) { oldProfile.FirstName = fname; oldProfile.LastName = lname; _userProfileRepository.Update(oldProfile); } else { var newUserProfile = new Data.Models.UserProfile { FirstName = fname, LastName = lname, IsActive = true, IsBlocked = false }; _userProfileRepository.Insert(newUserProfile); var userExisting = _userRepository.Table.FirstOrDefault(w => w.Id == userId); userExisting.UserProfile_Id = newUserProfile.Id; _userRepository.Update(userExisting); } return(0); }
public async Task <IActionResult> Register(RegisterViewModel model, string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; if (ModelState.IsValid) { var user = new Data.Models.User { UserName = model.Email, Email = model.Email }; var result = await _userManager.CreateAsync(user, model.Password); if (result.Succeeded) { _logger.LogInformation("User created a new account with password."); var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); var callbackUrl = Url.EmailConfirmationLink(user.Id, code, Request.Scheme); await _emailSender.SendEmailConfirmationAsync(model.Email, callbackUrl); await _signInManager.SignInAsync(user, isPersistent : false); _logger.LogInformation("User created a new account with password."); return(RedirectToLocal(returnUrl)); } AddErrors(result); } // If we got this far, something failed, redisplay form return(View(model)); }
public async Task <IActionResult> Register(UserForRegisterDto userForRegister) { userForRegister.UserName = userForRegister.UserName.ToLower(); if (await _userManager.FindByNameAsync(userForRegister.UserName) != null) { return(Conflict(new ReturnMessage() { Status = false, Title = Resource.ErrorMessages.Error, Message = Resource.ErrorMessages.ExistUserMessage, Code = "409" })); } var userToCreate = new Data.Models.User() { UserName = userForRegister.UserName, Address = "", City = "", DateOfBirth = DateTime.Now, Gender = true, IsActive = true, Status = true, Name = userForRegister.Name, PhoneNumber = userForRegister.PhoneNumber }; var photoToCreate = new Photo() { UserId = userToCreate.Id, Description = "Profile Pic", Alt = "Profile Pic", IsMain = true, Url = string.Format($"{Request.Scheme}://{Request.Host.Value ?? ""}{Request.PathBase.Value ?? "" }/wwwroot/Files/Images/ProfilePic.png"), PublicId = "0", }; var result = await _userManager.CreateAsync(userToCreate, userForRegister.Password); if (result.Succeeded) { await _authService.AddUserPhoto(photoToCreate); var userForReturn = _mapper.Map <UserDetailDto>(userToCreate); return(CreatedAtRoute("GetUser", new { controller = "User", id = userToCreate.Id }, userForReturn)); } else { _logger.LogWarning($"user : {userForRegister.Name} Email: {userForRegister.UserName} {Resource.ErrorMessages.DbErrorRegister} "); return(BadRequest(new ReturnMessage() { Code = "400", Message = Resource.ErrorMessages.NoRegister, Status = false, Title = Resource.ErrorMessages.Error })); } }
public static Models.User ToShallowUserJson(this Data.Models.User userData) { return(new Models.User { id = userData.UserId, username = userData.Username, }); }
public static Models.User ToUserJson(this Data.Models.User userData) { return(new Models.User { id = userData.UserId, username = userData.Username, likedPieces = userData.LikedPieces.Select(x => x.ToShallowPieceJson()).ToArray(), }); }
public frmMain(Data.Models.User user) { InitializeComponent(); bunifuFormDock1.SubscribeControlToDragEvents(pnlHeader, true); micron.BindDatagridViewEvents(grid, typeof(Data.Models.User)); this._user = user; grid.ReadOnly = !_user.IsAdmin; //only admins can edit }
/// <summary> /// Reset the delete account petition /// </summary> /// <param name="u">The user who doesn't want to delete the account</param> /// <param name="dbContext">The database context</param> public static void reset(Data.Models.User u, Data.ApplicationDBContext dbContext) { try { u.dateDeleted = null; dbContext.SaveChanges(); } catch (Exception) { } }
public User Get(string sId) { Data.Models.User foundUser = UserRepository.Get(sId); if (foundUser == null) { return(null); } return(new User(foundUser)); }
public User GetByName(string name) { Data.Models.User foundUser = UserRepository.GetByName(name); if (foundUser == null) { return(null); } return(new User(foundUser)); }
public static Data.Models.User CreateUser() { var user = new Data.Models.User(); Console.Write("Please enter your name: "); user.Name = Console.ReadLine(); Console.Write("Please enter your age: "); user.Age = Convert.ToInt32(Console.ReadLine()); return(user); }
public async Task <bool> UpdateUserPass(Data.Models.User user, string newPassword) { byte[] passwordHash, passwordSalt; _utilities.CreatePasswordHash(newPassword, out passwordHash, out passwordSalt); //user.PasswordHash = passwordHash; //user.PasswordSalt = passwordSalt; _db.UserRepository.Update(user); return(await _db.SaveAsync()); }
public Data.Models.Employee ToEmployee(Data.Models.User user) { return(new Data.Models.Employee { IsActive = true, CreateDate = DateTime.Now, ModifyDate = DateTime.Now, Name = Name, Surname = Surname, User = user, IsVerified = false }); }
public Data.Models.User Register(Data.Models.User user, IEnumerable <Role> roles) { var exists = _userService.Get(user.Email); if (exists == null) { _userService.Add(user, roles); return(user); } return(null); }
public async Task <UserDto> Create(CreateUserRequestModel model) { var user = new Data.Models.User { UserName = model.UserName, Email = model.UserName, RoleId = model.Role }; await _userManager.CreateAsync(user, model.Password); return(await FindByUserName(user.UserName)); }
public async Task <IHttpActionResult> Register(RegisterBindingModel model) { if (!this.ModelState.IsValid) { return(this.BadRequest(this.ModelState)); } var user = new User { UserName = model.Username, Email = model.Email }; IdentityResult result = await this.UserManager.CreateAsync(user, model.Password); return(!result.Succeeded ? this.GetErrorResult(result) : this.Ok()); }