protected void RegisterUser_CreatedUser(object sender, EventArgs e) { IUser UserServices = new UserServices(); UserModelDTO NewUser = new UserModelDTO(); if (PersonalInfoContainer.FindControl("FirstName") is TextBox) { NewUser.FirstName = ((TextBox)PersonalInfoContainer.FindControl("FirstName")).Text; } if (PersonalInfoContainer.FindControl("LastName") is TextBox) { NewUser.LastName = ((TextBox)PersonalInfoContainer.FindControl("LastName")).Text; } NewUser.UserName = RegisterUser.UserName; NewUser.UserID = UserServices.GetUserID(NewUser.UserName); NewUser.personTypeID = UserServices.GetUserType("User"); NewUser.Password = RegisterUser.Password; bool check = UserServices.CreateNewUser(NewUser); FormsAuthentication.SetAuthCookie(RegisterUser.UserName, false /* createPersistentCookie */); string continueUrl = RegisterUser.ContinueDestinationPageUrl; if (String.IsNullOrEmpty(continueUrl)) { continueUrl = "~/"; } Response.Redirect(continueUrl); }
public async Task <Object> PostUserModel(UserModelDTO model) { string userId = User.Claims.First(c => c.Type == "UserId").Value; var user = await _userManager.FindByIdAsync(userId); user.Email = model.Email; var oldUsername = user.UserName; user.UserName = model.UserName; if (user.UserName != oldUsername) { _poemRepository.RenameAuthorPoems(oldUsername, user.UserName); } try { var result = await _userManager.UpdateAsync(user); var code = await _userManager.GeneratePasswordResetTokenAsync(user); result = await _userManager.ResetPasswordAsync(user, code, model.Password); return(Ok(result)); } catch (Exception ex) { throw ex; } }
public UserModelDTO LoginUser(UserModelDTO model) { model = _authenticationService.AuthenticateUser(model); if (!model.Authenticated) { return(model); } model = _authorizationService.AuthorizeUser(model); // If the user dosnt exsist if (!_userRepository.Exsist(model.UserName)) { // Add the user to the database _userRepository.Insert(_mapper.Map <UserModelDAO>(model)); } model.Id = _userRepository.GetIdByname(model.UserName); model = GenerateToken(model); model.Password = string.Empty; return(model); }
//Опис: Методот регистрира нов корисник //Влезни параметри: објект од класата UserModelDTO public void RegisterUser(UserModelDTO userModel) { #if DEBUG ApplicationUser user = new ApplicationUser { UserName = userModel.Username, Email = userModel.Email, PublicKey = "testKey", }; #else ApplicationUser user = new ApplicationUser { UserName = userModel.Username, Email = userModel.Email, PublicKey = userModel.PublicKey, }; #endif try { _userManager.UserValidator = new CustomUserValidator <ApplicationUser>(_userManager); _userManager.Create(user, userModel.Password); _userManager.AddToRole(user.Id, userModel.UserRole); } catch (DbUpdateException ex) { SqlException s = ex.InnerException.InnerException as SqlException; if (s != null && s.Number == 2627) { throw new DuplicateUserException(userModel); } } }
public UserModelDTO Update([FromBody] UserModelDTO user) { UserModel updatedUser = mapperConfig.iMapper.Map <UserModelDTO, UserModel>(user); UserModelDTO updatedUserDTO = mapperConfig.iMapper.Map <UserModel, UserModelDTO>(userService.Update(updatedUser)); return(updatedUserDTO); }
public UserModelDTO AuthorizeUser(UserModelDTO model) { // Credentials for password-based authentication, used for the LDAP request _ldapConnection.Credential = new NetworkCredential(model.UserName, model.Password); try { // Log information about authorizing _logger?.LogInformation("Trying to authorize user {Username}", model.UserName); // Bind to the LDAP server _ldapConnection.Bind(); _principalContext = new PrincipalContext(ContextType.Domain, _configuration[_configuration.GetConnectionString("LdapIpAdress")], model.UserName, model.Password); // If the user is member of "ZBC-Ansatte(Alle)", if (model.UserPrincipal != null && model.UserPrincipal.IsMemberOf(_principalContext, IdentityType.SamAccountName, "ZBC-Ansatte(Alle)")) { // then give the user a role of employee model.Role = Role.Employee; } // Else if the user is member of "skp_it_slagelse", //else if (model.UserPrincipal != null && model.UserPrincipal.IsMemberOf(_principalContext, IdentityType.SamAccountName, "skp_it_slagelse")) // TODO: Update group name //{ // // then give the user a role of Administrator // model.Role = Role.Administrator; //} // Else if the user is member of "zbc_alle_elever", else if (model.UserPrincipal != null && model.UserPrincipal.IsMemberOf(_principalContext, IdentityType.SamAccountName, "zbc_alle_elever")) { // then give the user a role of student model.Role = Role.Student; } // Log that the user has been authorized _logger?.LogInformation("The user {Username} has been authorized as {Role}", new object[] { model.UserName, model.Role }); // Return the modified userModel return(model); } catch (Exception ex) { // Log that there has been an error.. _logger?.LogError(ex, "An exception was caught while trying to authorize user {Username}", model.UserName); // and return the unmodified userModel return(model); } finally { // Finally dispose the connection to the LDAP server _ldapConnection.Dispose(); } }
public async Task <ActionResult> PostNewUser( [FromBody] UserModelDTO user) { UserModel newUser = mapperConfig.iMapper.Map <UserModelDTO, UserModel>(user); newUser = await userService.AddUserAsync(newUser); UserModelDTO newUserDTO = mapperConfig.iMapper.Map <UserModel, UserModelDTO>(newUser); return(Ok(newUserDTO)); }
public UserModelDTO AuthenticateUser(UserModelDTO model) { // Credentials for password-based authentication, used for the LDAP request _ldapConnection.Credential = new NetworkCredential(model.UserName, model.Password); try { // Log information about authenticate _logger?.LogInformation("Trying to authenticate user {Username}", model.UserName); // Bind to the LDAP server _ldapConnection.Bind(); _principalContext = new PrincipalContext(ContextType.Domain, _configuration[_configuration.GetConnectionString("LdapIpAdress")], model.UserName, model.Password); // Requesting the userPrincipal from the Active Directory Domain Services, searching by SamAccountName _userPrincipal = UserPrincipal.FindByIdentity(_principalContext, IdentityType.SamAccountName, model.UserName); // If the user exists.. if (_userPrincipal != null) { // set the user to authenticated.. model.Authenticated = true; // and save the user principal for authorization model.UserPrincipal = _userPrincipal; // Log that the user has been authenticated _logger?.LogInformation("The user {Username} has been authenticate", model.UserName); } // Return the modified userModel return(model); } catch (Exception ex) { // Log that there has been an error.. _logger?.LogError(ex, "An exception was caught while trying to authenticate user {Username}", model.UserName); // and return the unmodified userModel return(model); } finally { // Finally dispose the connection to the LDAP server _ldapConnection.Dispose(); } }
public async Task <IHttpActionResult> Register(UserModelDTO userModel) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } IdentityResult result = await _authRepository.Register(userModel); IHttpActionResult errorResult = GetErrorResult(result); if (errorResult != null) { return(errorResult); } return(Ok()); }
// ASP.NET Identity //Опис: //Влезни параметри: објект од класата UserModelDTO public async Task <IdentityResult> Register(UserModelDTO userModel) { #if DEBUG ApplicationUser user = new ApplicationUser { UserName = userModel.Username, PublicKey = "testKey", }; #else ApplicationUser user = new ApplicationUser { UserName = userModel.Username, PublicKey = userModel.PublicKey, }; #endif var result = await _userManager.CreateAsync(user, userModel.Password); return(result); }
public async Task <Object> PostUserModel(UserModelDTO model) { var userModel = new UserModel() { UserName = model.UserName, Email = model.Email }; try { var result = await _userManager.CreateAsync(userModel, model.Password); return(Ok(result)); } catch (Exception ex) { throw ex; } }
public async Task <UserModelDTO> RegisterUser(UserModelDTO userModel) { if (userModel.Password.Length < 6) { throw new Exception("Лозинката мора да содржи најмалку 6 карактери"); } else if (userModel.Password != userModel.ConfirmPassword) { throw new Exception("Лозинките не се совпаѓаат"); } else if (userModel.UserRole.Length > 0) { var roleExists = await _authRepository.FindRoleInRoles(userModel.UserRole); if (!roleExists) { throw new Exception("Внесовте непостоечка ролја"); } } var user = await _authRepository.FindUserInUsers(userModel.Username); if (!user) { try { _authRepository.RegisterUser(userModel); return(userModel); } catch (DuplicateUserException ex) { throw new HttpException(ex.Message); } } else { throw new DuplicateUserException(userModel); } }
private UserModelDTO GenerateToken(UserModelDTO model) { var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(_configuration.GetSection("AppSettings")["Secret"]); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, model.UserName), new Claim(ClaimTypes.Role, model.Role) }), Expires = DateTime.UtcNow.AddMinutes(30), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); model.Token = tokenHandler.WriteToken(token); return(model); }
public DuplicateUserException(UserModelDTO user) { _user = user; }
public async Task <UserModelDTO> RegisterUser(UserModelDTO userModel) { char[] specialChars = "!@#$%^&*()".ToCharArray(); var validationErrors = new List <string>(); if (userModel.Password.Length < 6) { validationErrors.Add("Лозинката мора да содржи најмалку 6 карактери"); } if (userModel.Password != userModel.ConfirmPassword) { validationErrors.Add("Лозинките не се совпаѓаат"); } if (!userModel.Password.Any(char.IsLetter)) { validationErrors.Add("Лозинката мора да содржи барем една буква"); } if (!userModel.Password.Any(char.IsUpper)) { validationErrors.Add("Лозинката мора да содржи барем една голема буква"); } if (!userModel.Password.Any(char.IsLower)) { validationErrors.Add("Лозинката мора да содржи барем една мала буква"); } if (!userModel.Password.Any(char.IsDigit)) { validationErrors.Add("Лозинката мора да содржи барем еден број"); } if (userModel.Password.IndexOfAny(specialChars) == -1) { validationErrors.Add("Лозинката мора да содржи барем еден специјален карактер !@#$%^&*()"); } if (validationErrors.Count > 0) { string errorMessage = string.Empty; foreach (var validationError in validationErrors) { errorMessage += validationError + "." + Environment.NewLine; } if (!string.IsNullOrEmpty(errorMessage)) { throw new Exception(errorMessage); } } if (userModel.UserRole.Length > 0) { var roleExists = await _authRepository.FindRoleInRoles(userModel.UserRole); if (!roleExists) { throw new Exception("Внесовте непостоечка ролја"); } } var user = await _authRepository.FindUserInUsers(userModel.Username); if (!user) { try { _authRepository.RegisterUser(userModel); return(userModel); } catch (DuplicateUserException ex) { throw new HttpException(ex.Message); } } else { throw new DuplicateUserException(userModel); } }
//Method that creates new user public bool CreateNewUser(UserModelDTO NewUser) { bool check = false; using (TransactionScope Trans = new TransactionScope()) { try { using (var context = new CinemaEntities()) { //Enetring into Users Table try { User NewUserIn = new User(); NewUserIn.UserID = NewUser.UserID; NewUserIn.Password = NewUser.Password; if (NewUserIn.EntityState == EntityState.Detached) { context.Users.AddObject(NewUserIn); } context.SaveChanges(); } catch { } //Entering into Person Table try { Person NewPersonIn = new Person(); NewPersonIn.FirstName = NewUser.FirstName; NewPersonIn.LastName = NewUser.LastName; NewPersonIn.PersonTypeID = NewUser.personTypeID; NewPersonIn.PersonID = Guid.NewGuid(); if (NewPersonIn.EntityState == EntityState.Detached) { context.People.AddObject(NewPersonIn); } context.SaveChanges(); } catch { } ////Entering into Authonticated User Table //try //{ // AuthenticatedUser NewAuthUser = new AuthenticatedUser(); // NewAuthUser.PersonID = NewUser.PersonID; // NewAuthUser.UserID = NewUser.UserID; // NewAuthUser.AuthenticatedUserID = Guid.NewGuid(); // if (NewAuthUser.EntityState == EntityState.Detached) // { // context.AuthenticatedUsers.AddObject(NewAuthUser); // } // context.SaveChanges(); //} //catch { } } } catch { check = false; Trans.Dispose(); return check; } check = true; Trans.Complete(); return check; } }
//Method that creates new user public bool CreateNewUser(UserModelDTO NewUser) { bool check = false; using (TransactionScope Trans = new TransactionScope()) { try { using (var context = new CinemaEntities()) { //Enetring into Users Table try { User NewUserIn = new User(); NewUserIn.UserID = NewUser.UserID; NewUserIn.Password = NewUser.Password; if (NewUserIn.EntityState == EntityState.Detached) { context.Users.AddObject(NewUserIn); } context.SaveChanges(); } catch { } //Entering into Person Table try { Person NewPersonIn = new Person(); NewPersonIn.FirstName = NewUser.FirstName; NewPersonIn.LastName = NewUser.LastName; NewPersonIn.PersonTypeID = NewUser.personTypeID; NewPersonIn.PersonID = Guid.NewGuid(); if (NewPersonIn.EntityState == EntityState.Detached) { context.People.AddObject(NewPersonIn); } context.SaveChanges(); } catch { } ////Entering into Authonticated User Table //try //{ // AuthenticatedUser NewAuthUser = new AuthenticatedUser(); // NewAuthUser.PersonID = NewUser.PersonID; // NewAuthUser.UserID = NewUser.UserID; // NewAuthUser.AuthenticatedUserID = Guid.NewGuid(); // if (NewAuthUser.EntityState == EntityState.Detached) // { // context.AuthenticatedUsers.AddObject(NewAuthUser); // } // context.SaveChanges(); //} //catch { } } } catch { check = false; Trans.Dispose(); return(check); } check = true; Trans.Complete(); return(check); } }