public static dynamic UserAuthorizationAsync(UserCredentialModel userCredential) { try { using (_roofCareDbContext) { var user = (from u in _roofCareDbContext.Users select new { u.UserId, u.Username, u.Password, u.FullName, u.UserImage, u.UserType, }).ToList().FirstOrDefault(x => x.Username.Equals(userCredential.Username, StringComparison.OrdinalIgnoreCase) && x.Password.Equals(userCredential.Password)); if (user != null) { return(Responses.AuthenticationResponse(true, user.UserId, "Log in successful", user.Username, user.FullName, user.UserType, user.UserImage)); } else { return(Responses.AuthenticationResponse(false, 0, "Invalid username or password.", null, null, null, null)); } } } catch (Exception ex) { return(Responses.AuthenticationResponse(false, 0, ex.Message, null, null, null, null)); } }
public Response <UserCredentialModel> UpdateUserCredential(UserCredentialModel userCredential) { var apiUrl = baseRoute + "UpdateUserCredential"; var param = new NameValueCollection(); return(communicationManager.Post <UserCredentialModel, Response <UserCredentialModel> >(userCredential, apiUrl)); }
public static List <UserCredentialModel> ToUserFullDetails(DbDataReader readers) { if (readers == null) { return(null); } var models = new List <UserCredentialModel>(); while (readers.Read()) { var model = new UserCredentialModel { Id = Convert.IsDBNull(readers["Id"]) ? string.Empty : Convert.ToString(readers["Id"]), FullName = Convert.IsDBNull(readers["FullName"]) ? string.Empty : Convert.ToString(readers["FullName"]), Email = Convert.IsDBNull(readers["Email"]) ? string.Empty : Convert.ToString(readers["Email"]), ContactNo = Convert.IsDBNull(readers["ContactNo"]) ? string.Empty : Convert.ToString(readers["ContactNo"]), CreatedAt = Convert.IsDBNull(readers["CreatedAt"]) ? string.Empty : Convert.ToDateTime(readers["CreatedAt"]).ToShortDateString(), UserTypeId = Convert.ToInt32(readers["UserTypeId"]), IsActive = Convert.ToBoolean(readers["IsActive"]), OrganizationId = Convert.IsDBNull(readers["OrganizationId"]) ? string.Empty : Convert.ToString(readers["OrganizationId"]), LoginID = Convert.IsDBNull(readers["LoginID"]) ? string.Empty : Convert.ToString(readers["LoginID"]), Password = Convert.IsDBNull(readers["Password"]) ? string.Empty : Convert.ToString(readers["Password"]) }; models.Add(model); } return(models); }
public ActionResult Index(UserCredentialModel user) { if (ModelState.IsValid) { if (user.UserId != CommonUtility.GetAppSetting <string>("AdminUserId")) { ModelState.AddModelError("UserId", "User Id is invalid"); return(View(user)); } if (user.Password != CommonUtility.GetAppSetting <string>("AdminPwd")) { ModelState.AddModelError("Password", "Password is invalid"); return(View(user)); } else { Session["UserId"] = user.UserId; if (!string.IsNullOrEmpty(user.RedirectUrl)) { return(Redirect(Url.Content(user.RedirectUrl.ToBase64Decode()))); } else { return(RedirectToAction("Index", "Home", new { area = "Admin" })); } } } else { return(View(user)); } }
/// <summary> /// Indexes this instance. /// </summary> /// <returns></returns> public ActionResult Index(string redirectionUrl = null) { UserCredentialModel user = new UserCredentialModel(); user.RedirectUrl = string.IsNullOrEmpty(redirectionUrl) ? user.RedirectUrl : redirectionUrl; return(View(user)); }
public async Task GetAuthenticationToken_ReturnsOK() { // Arrange var request = new UserCredentialModel().Entity; //Act var result = await Task.Run(() => this._service.GetAuthenticationToken(request)); // Assert Assert.AreNotEqual(string.Empty, result, "error in returning a valid token"); }
public IActionResult getalluser() { //return new ObjectResult(false); var userCredentialModel = new UserCredentialModel { Id = 1, Username = "******", Password = "******", RememberMe = false }; return(Ok(userCredentialModel)); }
public async Task IsAuthenticated_ReturnsOK() { // Arrange var request = new UserCredentialModel().Entity; //Act var result = await this._service.IsAuthenticated(request); // Assert //base.RepositoryMock.Verify(q => q.GetCountAsync(expression), // "error in calling the correct method"); // Verifies that Repository.GetCountAsync was called Assert.AreEqual(true, result, "error in returning correct value"); }
public IActionResult authenticateuser([FromBody] UserCredentialModel userCredentialModel) { try { string msg = string.Empty; var user = _userAuthenticationService.AuthenticateUser(userCredentialModel, out msg); return(AuthenticationResponse(user, msg)); } catch (Exception ex) { return(BadRequest(new { status = Constants.Error, message = Constants.ErrorMessage, user = "" })); } }
public IActionResult ManageLogin(UserCredentialModel newLoginDetails) { // Get current user from database int custID = Convert.ToInt32(User.Identity.Name); Customer custDBRecord = CustomerManager.FindById(custID); // Run a gauntlet of checks to make sure inputs are valid (this is on top of the data-annotation validation in the page) bool passesValidation = true; // keeps track of whether any validation has failed - just a little tidier for handling all the cases if (!(newLoginDetails.NewPass == newLoginDetails.ConfirmNewPass)) // if passwords don't match { TempData["PasswordsNotSame"] = "Your new passwords do not match"; passesValidation = false; } if (AccountManager.Authenticate(newLoginDetails.ExistingLogin, newLoginDetails.ExistingPass) == null) // if existing login credentials are wrong { TempData["ErrorMessage"] = "Your existing login or password is incorrect."; passesValidation = false; } if (newLoginDetails.NewLogin != custDBRecord.UserLogin && // if the login is changed from the existing one CustomerManager.Exists(newLoginDetails.NewLogin)) // and it already exists in the database { TempData["UserTaken"] = "Your existing login or password is incorrect."; passesValidation = false; } // Here's what we want to happen if validation all passes - actually update the customer if (passesValidation == true) { custDBRecord.UserLogin = newLoginDetails.NewLogin; custDBRecord.UserPass = AccountManager.HashPassword(newLoginDetails.NewPass); // Attempt to update customer in db try { CustomerManager.Update(custDBRecord); return(RedirectToAction("Index", "Home")); //TODO: maybe this should go elsewhere } // If valid inputs but update failed, something's up with the database. A special method gets displayed catch { TempData["ErrorMessage"] = "Something went wrong. Please check your inputs or contact customer service."; return(View()); } } // If not valid, returning will show the error messages return(View()); }
public Response <UserCredentialModel> AddUserCredential(UserCredentialModel userCredential) { var userRepository = unitOfWork.GetRepository <UserCredentialModel>(); SqlParameter userIDParam = new SqlParameter("UserID", userCredential.UserID); SqlParameter credentialIDParam = new SqlParameter("CredentialID", userCredential.CredentialID); SqlParameter credentialCodeParam = userCredential.LicenseNbr != null ? new SqlParameter("LicenseNbr", userCredential.LicenseNbr) : new SqlParameter("LicenseNbr", DBNull.Value); SqlParameter effectiveDateParam = userCredential.LicenseIssueDate != null ? new SqlParameter("LicenseIssueDate", userCredential.LicenseIssueDate) : new SqlParameter("LicenseIssueDate", DBNull.Value); SqlParameter expirationDateParam = userCredential.LicenseExpirationDate != null ? new SqlParameter("LicenseExpirationDate", userCredential.LicenseExpirationDate) : new SqlParameter("LicenseExpirationDate", DBNull.Value); SqlParameter modifiedOnParam = new SqlParameter("ModifiedOn", userCredential.ModifiedOn ?? DateTime.Now); List <SqlParameter> procParams = new List <SqlParameter>() { userIDParam, credentialIDParam, credentialCodeParam, effectiveDateParam, expirationDateParam, modifiedOnParam }; return(userRepository.ExecuteNQStoredProc("usp_AddUserCredential", procParams)); }
public object ValidateUserLogin(UserCredentialModel userCredentialModel) { try { ValidateUser Validuser = new ValidateUser(); var result = Validuser.IsValidUser(userCredentialModel); return(result); } catch (Exception e) { return(new Error() { IsError = true, Message = e.Message }); } }
public async Task PostAsync_ReturnsOK() { // Arrange var userCredential = new UserCredentialModel().Entity; var requestContent = base.GetSerializedContent(userCredential); string url = this._postUrl; //Act var response = await base.Client.PostAsync(url, requestContent); // Assert Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, "error in returning correct response"); string token = await base.GetDeserializedContent <string>(response); Assert.IsInstanceOf <string>(token, "error in returning the token"); }
public async Task RequestToken_InvalidUserCredential_ReturnsBadRequest() { // Arrange var userCredential = new UserCredentialModel().NullUserNameEntity; new DataAnnotationsValidator().TryValidate(userCredential, out ICollection <ValidationResult> modelState); var validationResult = modelState.First(); this._controller.ModelState.AddModelError(validationResult.MemberNames.First(), validationResult.ErrorMessage); var expectedResult = new BadRequestObjectResult(this._controller.ModelState); //Act var result = await this._controller.RequestToken(userCredential); // Assert TestHelper.AreEqualEntities(expectedResult, result, "error in returning the correct BadRequestObjectResult"); }
public async Task RequestToken_NotAuthenticatedUser_ReturnsBadRequest() { // Arrange var userCredential = new UserCredentialModel().NotAuthenticatedEntity; var transactionResult = new TransactionResult(new CustomException(Constant.Exception_AuthenticationFailed)); this._authServiceMock.Setup(q => q.GetAuthenticationToken(userCredential)).ReturnsAsync(transactionResult); var expectedResult = new BadRequestObjectResult(Constant.Exception_AuthenticationFailed); //Act var result = await this._controller.RequestToken(userCredential); // Assert this._authServiceMock.Verify(q => q.IsAuthenticated(userCredential), "error in calling the correct method"); // Verifies that authService.IsAuthenticated was called TestHelper.AreEqualEntities(expectedResult, result, "error in returning the correct BadRequestObjectResult"); }
public async Task PostAsync_InvalidAuthentication_ReturnsInvalidAuthenticationException() { // Arrange var userCredential = new UserCredentialModel().NotAuthenticatedEntity; var requestContent = base.GetSerializedContent(userCredential); var expectedContent = Constant.Exception_InvalidAuthentication; string url = this._postUrl; //Act var result = await base.Client.PostAsync(url, requestContent); // Assert string content = await base.GetDeserializedContent <string>(result); Assert.AreEqual(HttpStatusCode.BadRequest, result.StatusCode, "error in returning correct response"); Assert.AreEqual(expectedContent, content, "error in returning correct content"); }
public async Task <IActionResult> AccountUserLogin([FromBody] UserCredentialModel user) { ActionResult _result = new ObjectResult(false); BaseResponse _authenticationResponse = null; if (!ModelState.IsValid) { return(BadRequest(ModelState)); } try { MembershipContext _membershipContext = _userService.ValidateUser(user.Username, user.Password); if (_membershipContext.User != null) { // generate Json Web Token string token = GenerateToken(user.Username); _authenticationResponse = new BaseResponse() { Succeeded = true, Message = token }; } else { _authenticationResponse = new BaseResponse() { Succeeded = false, Message = "Authentication failed" }; } } catch (Exception ex) { _authenticationResponse = new BaseResponse() { Succeeded = false, Message = ex.Message }; } _result = new ObjectResult(_authenticationResponse); return(_result); }
public async Task PostAsync_NullPassword_ReturnsBadRequestValidationException() { // Arrange var userCredential = new UserCredentialModel().NullPasswordEntity; var requestContent = base.GetSerializedContent(userCredential); var modelState = new ModelStateDictionary().AddModelRequiredError("Password"); var expectedContent = base.GetModelStateContent(modelState); string url = this._postUrl; //Act var result = await base.Client.PostAsync(url, requestContent); // Assert string content = await base.GetDeserializedContent <string>(result); Assert.AreEqual(HttpStatusCode.BadRequest, result.StatusCode, "error in returning correct response"); Assert.AreEqual(expectedContent, content, "error in returning correct content"); }
public object GetUser() { var name = CryptIt.Decrypt("vPelNrzLabeGOYF6LMYvZA=="); try { UserCredentialModel userCredentialModel = new UserCredentialModel() { UserName = "******" }; return(userCredentialModel); } catch (Exception e) { return(new Error() { IsError = true, Message = e.Message }); } }
public async Task RequestToken_ReturnsOK() { // Arrange var userCredential = new UserCredentialModel().Entity; string authenticationToken = "sample_authentication_token"; var transactionResult = new TransactionResult(authenticationToken); var expectedResult = new OkObjectResult(transactionResult); this._authServiceMock.Setup(q => q.IsAuthenticated(userCredential)).ReturnsAsync(true); this._authServiceMock.Setup(q => q.GetAuthenticationToken(userCredential)).ReturnsAsync(transactionResult); //Act var result = await this._controller.RequestToken(userCredential); // Assert this._authServiceMock.Verify(q => q.IsAuthenticated(userCredential), "error in calling the correct method"); // Verifies that authService.IsAuthenticated was called this._authServiceMock.Verify(q => q.GetAuthenticationToken(userCredential), "error in calling the correct method"); // Verifies that authService.GetAuthenticationToken was called TestHelper.AreEqualEntities(expectedResult, result, "error in returning the correct authentication token"); }
/// <summary> /// Autheticate the user /// </summary> /// <param name="userCredentialModel"></param> /// <returns></returns> public TUsers AuthenticateUser(UserCredentialModel userCredentialModel, out string message) { message = string.Empty; var users = _userRepository.FindByCondition(x => x.Emailid == userCredentialModel.Email); if (users != null && users.Count() > 0) //user is found, now let's decrypt and compare the password { foreach (var userDetails in users) { if (userCredentialModel.Password == CryptoUtil.DecryptStringAES(userDetails.Password)) { var user = _userDataManager.LoadUserRoles(userDetails); ClearAttributes(user); message = "User authenticated successfully"; return(user); } } } message = "User authentication failed"; return(null); }
public object IsValidUser(UserCredentialModel userCredentialModel) { var password = CryptIt.Encrypt(userCredentialModel.Password); var user = db.tbl_user.FirstOrDefault(r => r.email == userCredentialModel.UserName && r.password == password); if (user == null) { return(new Error() { IsError = true, Message = "Incorrect User Or Password.." }); } else { //user.code = Convert.ToInt32(HttpContext.Current.Session["Code"]); return(new Result() { IsSucess = true, ResultData = user }); } }
public ResponseModel Save(UserCredentialModel model) { var errMessage = string.Empty; var pk = Guid.NewGuid().ToString(); var queryParamList = new QueryParamList { new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@Id", ParamValue = pk }, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@FullName", ParamValue = model.FullName }, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@Email", ParamValue = model.Email }, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@LoginID", ParamValue = model.LoginID }, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@ContactNo", ParamValue = model.ContactNo }, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@Password", ParamValue = model.Password }, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@UserTypeId", ParamValue = model.UserTypeId } }; const string sql = @"INSERT INTO dbo.UserCredentials(Id,FullName,Email,ContactNo,Password,UserTypeId,IsActive,CreatedAt,LoginID) VALUES(@Id,@FullName,@Email,@ContactNo,@Password,@UserTypeId,1,GETDATE(),@LoginID)"; DBExecCommandEx(sql, queryParamList, ref errMessage); return(new ResponseModel { Success = string.IsNullOrEmpty(errMessage), Message = errMessage, ReturnCode = pk }); }
public static UserCredentialViewModel ToModel(this UserCredentialModel entity) { if (entity == null) { return(null); } var model = new UserCredentialViewModel { UserCredentialID = entity.UserCredentialID, UserID = entity.UserID, CredentialID = entity.CredentialID, Name = entity.CredentialName, Description = entity.Description, LicenseRequired = entity.LicenseRequired, LicenseNbr = entity.LicenseNbr, LicenseIssueDate = entity.LicenseIssueDate, LicenseExpirationDate = entity.LicenseExpirationDate, ModifiedOn = entity.ModifiedOn }; return(model); }
public object Login(UserCredentialModel user) { try { // user pointer to check if username and password is matching var record = dbase.Users.Where(col => col.Username == user.Username && col.Password == user.Password).FirstOrDefault(); if (record == null) { // No Match return(new { status = "401", message = "Invalid Login" }); } else { return(new { status = "201", message = "Success", userid = record.Id }); // User is authenticated } } catch (Exception e) { return(new { status = "401", message = "Server Error " + e.InnerException }); } }
public IActionResult Login([FromBody] UserCredentialModel model) { var user = users. Where(x => x.EmailAddress.Equals(model.EmailAddress) && x.Password.Equals(model.Password)) .FirstOrDefault(); //check user exist if (user == null) { return(NotFound()); } //generate token var tokenHandler = new JwtSecurityTokenHandler(); var secretkey = _configuration.GetValue <string>("JWTSettings:SecretKey"); var key = Encoding.ASCII.GetBytes(secretkey); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, user.EmailAddress) }), Expires = DateTime.UtcNow.AddDays(1), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); //prepare the response var tokenResponse = new TokenModel(); tokenResponse.access_token = tokenHandler.WriteToken(token); return(Ok(tokenResponse)); }
public IActionResult LogInAuthorization([FromBody] UserCredentialModel userCredential) { return(Ok(UserService.UserAuthorizationAsync(userCredential))); }
public IHttpActionResult UpdateUserCredential(UserCredentialModel userCredential) { return(new HttpResult <Response <UserCredentialModel> >(adminRuleEngine.UpdateUserCredential(userCredential), Request)); }
public Response <UserCredentialModel> AddUserCredential(UserCredentialModel userCredential) { var apiUrl = baseRoute + "AddUserCredential"; return(communicationManager.Post <UserCredentialModel, Response <UserCredentialModel> >(userCredential, apiUrl)); }
public ActionResult Login(UserCredentialModel model) { model.IsSuccessfulLogin = _authenticationService.AreValidUserCredentials(model.Username, model.Password); return(View("Index", model)); }