public async Task <CustomerModel> ValidateCustomer(string username, string password) { var customer = await GetCustomerByUsername(username); if (customer == null) { return(null); } if (customer.Deleted) { return(null); } if (!customer.Active) { return(null); } if (!customer.Password.Equals(EncryptionLibrary.EncryptText(password))) { customer.FailedLoginAttempts++; if (customer.FailedLoginAttempts > 0 && customer.FailedLoginAttempts >= 5) { //todo: lock account for 24 hours } await UpdateCustomer(customer); return(null); } return(_mapper.Map <CustomerModel>(customer)); }
public IHttpActionResult Login(LoginViewModel loginViewModel) { if (!string.IsNullOrWhiteSpace(loginViewModel.Username) && !string.IsNullOrWhiteSpace(loginViewModel.Password)) { var Username = loginViewModel.Username; var password = EncryptionLibrary.EncryptText(loginViewModel.Password); var result = LoginRepository.ValidateUser(Username, password); if (result != null) { var RoleID = result.RoleID; var roleCode = RoleRepository.GetRoleCode(RoleID); loginViewModel.RoleCode = roleCode; loginViewModel.UserId = result.RegistrationID; if (!AssignRolesRepository.CheckIsUserAssignedRole(result.RegistrationID)) { loginViewModel.IsAssigned = false; } else { loginViewModel.IsAssigned = true; } } } return(Ok(loginViewModel)); }
public bool Post([FromBody] ChangePasswordModel ChangePasswordModel) { try { var UserID = (from user in _DatabaseContext.UserMasterTB where user.Username == ChangePasswordModel.Username select user.U_Id).SingleOrDefault(); if (Comparepassword(ChangePasswordModel)) { string newEncrypttpassword = EncryptionLibrary.EncryptText(ChangePasswordModel.NewPassword); var UserModel = new UserMasterTB { U_Id = UserID, Password = newEncrypttpassword }; var db = _DatabaseContext; db.UserMasterTB.Attach(UserModel); db.Entry(UserModel).Property(x => x.Password).IsModified = true; db.SaveChanges(); return(true); } else { return(false); } } catch (Exception) { throw; } }
public HttpResponseMessage easebuzzPayment(HttpRequestMessage request, paymentdetails pd) { if (!ModelState.IsValid || pd == null) { return(new HttpResponseMessage(HttpStatusCode.BadRequest)); } clsKeyValue ckv = EncryptionLibrary.GetKeys(); string amount = pd.amount; string firstname = pd.firstname; string email = pd.email; string phone = pd.phone; string productinfo = pd.productinfo; string surl = "https://payment.tollpay.in/success.aspx"; //Request.Form["surl"].Trim(); string furl = "https://payment.tollpay.in/success.aspx"; //Request.Form["furl"].Trim(); string Txnid = ckv.SessionID; //call the object of class and start payment Easebuzz t = new Easebuzz(ckv.easebuzzsalt, ckv.easebuzzkey, ckv.easebuzzenv); string strForm = t.initiatePaymentAPI(amount, firstname, email, phone, productinfo, surl, furl, Txnid); return(request.CreateResponse(HttpStatusCode.OK, strForm)); }
public bool Post([FromBody] UserMasterTB usermastertb) { try { var output = (from usermaster in _DatabaseContext.UserMasterTB where usermastertb.Username == usermaster.Username select usermaster.Username).Count(); if (output > 0) { return(false); } else { var userTypeID = (from user in _DatabaseContext.UserType where user.UserTypeName == "User" select user.UserTypeID).SingleOrDefault(); usermastertb.U_Id = 0; usermastertb.UserTypeID = userTypeID; usermastertb.Password = EncryptionLibrary.EncryptText(usermastertb.Password); usermastertb.CreatedOn = DateTime.Now; _DatabaseContext.Add(usermastertb); _DatabaseContext.SaveChanges(); return(true); } } catch (Exception) { throw; } }
/// <summary> /// Saves the specified reference identifier. /// </summary> /// <param name="referenceId">The reference identifier.</param> /// <param name="imageModel">The image model.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">imageModel</exception> public async Task <string> SaveImage(Guid referenceId, ImageModel imageModel) { // check write permissions if (imageModel == null) { throw new ArgumentNullException("imageModel"); } await((IAsyncInitialization)_configManager).Initialization; var directoryInfo = Directory.CreateDirectory(Path.Combine(_configManager.CacheLocation, referenceId.ToString())); // this is for Images directoryInfo.CreateSubdirectory(ImagesFolder); var imageFilePath = Path.Combine(directoryInfo.FullName, $"Source{imageModel.Extension}"); using (var file = File.OpenWrite(imageFilePath)) { var encryptedData = EncryptionLibrary.EncryptData(imageModel.ImageFileModel.Buffer, EncryptionConfig.AesKey, EncryptionConfig.HmacKey); await file.WriteAsync(encryptedData, 0, encryptedData.Length); } return(imageFilePath); }
public override void OnException(ExceptionContext context) { StringValues authorizationToken; if (context.Exception != null) { var encodedString = context.HttpContext.Request.Headers.TryGetValue("Token", out authorizationToken); if (!string.IsNullOrEmpty(authorizationToken.First())) { var key = EncryptionLibrary.DecryptText(authorizationToken.First()); string[] parts = key.Split(new char[] { ':' }); var customerId = Convert.ToInt32(parts[0]); var exception = context.Exception; var model = new LogModel { ShortMessage = exception.Message, FullMessage = exception?.ToString() ?? string.Empty, CustomerId = customerId, IpAddress = context.HttpContext.Connection.RemoteIpAddress?.ToString(), PageUrl = $"{context.HttpContext.Request.PathBase}{context.HttpContext.Request.Path}{context.HttpContext.Request.QueryString}", CreatedOn = DateTime.UtcNow, PageReferrer = $"{context.HttpContext.Request.Headers[HeaderNames.Referer]}", }; _logService.InsertLog(model); } } }
public ActionResult Register(RegisteredUser user) { try { if (!ModelState.IsValid) { return(View("Register", user)); } if (_registeruserRepo.ValidateRegisteredUser(user)) { ModelState.AddModelError("", @"User is already registered"); return(View("Register", user)); } user.CreatedOn = DateTime.Now; user.Password = EncryptionLibrary.EncryptText(user.Password); user.ActiveStatus = true; user.UserType = 1; _registeruserRepo.Add(user); TempData["UserManager"] = "User registered successfully"; ModelState.Clear(); return(RedirectToAction("Login")); } catch (Exception e) { //Console.WriteLine(e); //throw; return(View()); } }
public ActionResult Create(RegisterUser RegisterUser) { try { if (!ModelState.IsValid) { return(View("Create", RegisterUser)); } // Validating Username if (_repository.ValidateUsername(RegisterUser)) { ModelState.AddModelError("", "User is Already Registered"); return(View("Create", RegisterUser)); } RegisterUser.CreateDate = DateTime.Now; // Encrypting Password with AES 256 Algorithm RegisterUser.Password = EncryptionLibrary.EncryptText(RegisterUser.Password); // Saving User Details in Database _repository.Add(RegisterUser); TempData["UserMessage"] = "User Registered Successfully"; ModelState.Clear(); return(View("Create", new RegisterUser())); } catch { return(View()); } }
public int RegistrarUsuario(User request) { request.Password = EncryptionLibrary.EncryptText(request.Password); int id = _UsersRepository.Insertar(request); return(id); }
public IActionResult ChangePassword(ChangePasswordModel ChangePasswordModel) { if (!ModelState.IsValid) { return(View(ChangePasswordModel)); } var password = EncryptionLibrary.EncryptText(ChangePasswordModel.Password); var registrationModel = _IUsers.Userinformation(Convert.ToInt32(HttpContext.Session.GetString("UserID"))); if (registrationModel.Password == password) { var registration = new Users(); registration.Password = EncryptionLibrary.EncryptText(ChangePasswordModel.NewPassword); registration.ID = Convert.ToInt32(HttpContext.Session.GetString("UserID")); var result = _ILogin.UpdatePassword(registration); if (result) { TempData["MessageUpdate"] = "Password Updated Successfully"; ModelState.Clear(); return(View(new ChangePasswordModel())); } else { return(View(ChangePasswordModel)); } } else { TempData["MessageUpdate"] = "Invalid Password"; return(View(ChangePasswordModel)); } }
public ActionResult Register(Registration registration) { try { UserManager userManager = new UserManager(); registration.CreatedBy = Session["Username"].ToString(); registration.Password = EncryptionLibrary.EncryptText(registration.Password); int value = userManager.CreateUser(registration); if (value == 1) { TempData["MessageRegistration"] = "User Created Successfully"; return(RedirectToAction("/Index")); } else if (value == 2) { TempData["MessageRegistration"] = " EmailID already exist"; } else if (value == 3) { TempData["MessageRegistration"] = " Username already exist"; } else if (value == 0) { TempData["MessageRegistration"] = "Error Occured"; } // ViewBag.Roles = new SelectList(userManager.GetRoleList(), "RoleID", "RoleName"); return(RedirectToAction("/Index")); } catch { return(View()); } }
public IActionResult Registration(Registration Registration) { try { var isUsernameExists = _IRepository.CheckUserNameExists(Registration.Username); if (isUsernameExists) { ModelState.AddModelError("", errorMessage: "Username Already Used try unique one!"); } else { Registration.CreatedOn = DateTime.Now; Registration.RoleID = _IRoles.getRolesofUserbyRolename("Users"); Registration.Password = EncryptionLibrary.EncryptText(Registration.Password); Registration.ConfirmPassword = EncryptionLibrary.EncryptText(Registration.ConfirmPassword); if (_IRepository.AddUser(Registration) > 0) { TempData["MessageRegistration"] = "You have successfully registered!"; ModelState.Clear(); return(View(new Registration())); } else { return(View(Registration)); } } return(View(Registration)); } catch (System.Exception) { throw; } }
public ActionResult ChangePassword(ChangePasswordModel changepasswordmodel) { try { var password = EncryptionLibrary.EncryptText(changepasswordmodel.OldPassword); var storedPassword = _ILogin.GetPasswordbyUserID(Convert.ToInt32(Session["UserID"])); if (storedPassword == password) { var result = _ILogin.UpdatePassword(EncryptionLibrary.EncryptText(changepasswordmodel.NewPassword), Convert.ToInt32(Session["UserID"])); if (result) { ModelState.Clear(); ViewBag.message = "Password Changed Successfully"; return(View(changepasswordmodel)); } else { ModelState.AddModelError("", "Something Went Wrong Please try Again after some time"); return(View(changepasswordmodel)); } } else { ModelState.AddModelError("", "Entered Wrong Old Password"); return(View(changepasswordmodel)); } } catch (Exception) { throw; } }
public JsonResult ResetUserPasswordProcess(string RegistrationID) { try { if (string.IsNullOrEmpty(Convert.ToString(RegistrationID))) { return(Json("Error", JsonRequestBehavior.AllowGet)); } var Password = EncryptionLibrary.EncryptText("default@123"); var isPasswordUpdated = _IRegistration.UpdatePassword(RegistrationID, Password); if (isPasswordUpdated) { return(Json(data: true, behavior: JsonRequestBehavior.AllowGet)); } else { return(Json(data: false, behavior: JsonRequestBehavior.AllowGet)); } } catch (Exception) { throw; } }
private bool Authorize(HttpActionContext actionContext) { try { var encodedString = actionContext.Request.Headers.GetValues("WeSchoolAuthorization").First(); bool validFlag = false; if (!string.IsNullOrEmpty(encodedString)) { var key = EncryptionLibrary.DecryptText(encodedString); string[] parts = key.Split(new char[] { ':' }); var UserID = Convert.ToInt32(parts[0]); // Studentcode var RandomKey = parts[1]; // Random Key var CompanyID = parts[2]; // Admission No long ticks = long.Parse(parts[3]); // Ticks DateTime IssuedOn = new DateTime(ticks); // Issued On var ClientID = parts[4]; // Admission No // By passing this parameter var registerModel = (from register in db.Applicationsdlps where register.AdmissionNo == CompanyID && register.Code == UserID && register.AdmissionNo == ClientID select register).FirstOrDefault(); if (registerModel != null) { // Validating Time var ExpiresOn = (from token in db.TokensManagers where token.StudentCode == UserID select token.ExpiresOn).FirstOrDefault(); // Validating Token var TokenKey = (from token in db.TokensManagers where token.StudentCode == UserID select token.TokenKey).FirstOrDefault(); if ((encodedString != TokenKey)) { validFlag = false; } else { if ((DateTime.Now > ExpiresOn)) { validFlag = false; } else { validFlag = true; } } } else { validFlag = false; } } return(validFlag); } catch (Exception) { return(false); } }
public int Post([FromBody] UserDetails userDetails) { try { var output = (from userDetail in _DatabaseContext.UserDetails where userDetail.Username == userDetails.Username select userDetail.Username).Count(); if (output > 0) { return(0); } else { var userTypeID = (from user in _DatabaseContext.UserType where user.UserTypeName == "User" select user.UserTypeID).SingleOrDefault(); userDetails.UserId = 0; userDetails.UserTypeID = userTypeID; userDetails.Password = EncryptionLibrary.EncryptText(userDetails.Password); userDetails.CreatedOn = DateTime.Now; _DatabaseContext.Add(userDetails); _DatabaseContext.SaveChanges(); return(userDetails.UserId); } } catch (Exception) { throw; } }
public ActionResult CreateAdmin(Registration registration) { try { var isUsernameExists = _IRegistration.CheckUserNameExists(registration.Username); if (isUsernameExists) { ModelState.AddModelError("", errorMessage: "Username Already Used try unique one!"); } else { registration.CreatedOn = DateTime.Now; registration.RoleID = _IRoles.getRolesofUserbyRolename("Admin"); registration.Password = EncryptionLibrary.EncryptText(registration.Password); registration.ConfirmPassword = EncryptionLibrary.EncryptText(registration.ConfirmPassword); if (_IRegistration.AddUser(registration) > 0) { TempData["MessageRegistration"] = "Data Saved Successfully!"; return(RedirectToAction("CreateAdmin")); } else { return(View("CreateAdmin", registration)); } } return(RedirectToAction("Dashboard")); } catch { return(View()); } }
public IActionResult Registration(Registration Registration) { try { var isUsernameExists = CheckUserNameExists(Registration.Username); if (isUsernameExists) { ModelState.AddModelError("", errorMessage: "Username Already Used try unique one!"); } else { Registration.CreatedOn = DateTime.Now; Registration.RoleID = 1; Registration.Password = EncryptionLibrary.EncryptText(Registration.Password); Registration.ConfirmPassword = EncryptionLibrary.EncryptText(Registration.ConfirmPassword); if (AddUser(Registration) > 0) { TempData["MessageRegistration"] = "Data Saved Successfully!"; return(View(Registration)); } else { return(View(Registration)); } } return(View(Registration)); } catch (System.Exception) { throw; } }
public clsWalletrequest() { string key = "8E41AEF6156CF2221EF6A2EA6950A934"; string vguid = Guid.NewGuid().ToString(); //DateTime.Now.ToString("yyyyMMddHHmmssfffffff"); Walletrequest wr = new Walletrequest(); Subheader sub = new Subheader() { serviceRequestVersion = "1.0", serviceRequestId = "WALLET", requestUUID = vguid, channelId = "DIGI" }; wr.SubHeader = sub; Walletrequestbody wrb = new Walletrequestbody(); var jsonString = JsonConvert.SerializeObject(wrb); Console.WriteLine("Walletrequestbody plan -" + jsonString.ToString()); wr.WalletRequestBodyEncrypted = EncryptionLibrary.encrypt(jsonString, key); this.WalletRequest = wr; db.AxisSetuAPILoggers.Add(new AxisSetuAPILogger() { RequestGuid = vguid , request = jsonString }); db.SaveChanges(); }
public IActionResult Create(UsersViewModel entity) { try { var isUsernameExists = _IRepository.CheckUserNameExists(entity.dbModel.Username); if (isUsernameExists) { ModelState.AddModelError("", errorMessage: "Username already exists. Please enter a unique username."); } else { entity.dbModel.CreatedOn = DateTime.Now; entity.dbModel.RoleID = entity.dbModel.RoleID; entity.dbModel.Password = EncryptionLibrary.EncryptText(entity.dbModel.Password); entity.dbModel.ConfirmPassword = EncryptionLibrary.EncryptText(entity.dbModel.Password); if (_IRepository.AddUser(entity.dbModel) > 0) { TempData["MessageRegistration"] = "User created successfully!"; // return View(entity.dbModel); return(RedirectToAction("Index")); } else { return(RedirectToAction("Index")); } } return(RedirectToAction("Index")); } catch (System.Exception) { throw; } }
public static string GetUserId() { HttpContextAccessor dd = new HttpContextAccessor(); var Headers = dd.HttpContext.Request.Headers; string Token = string.Empty; foreach (var key in Headers.Keys) { if (key.ToLower() == "token") { Token = Headers[key]; } } if (string.IsNullOrEmpty(Token)) { Token = "Can't Get Account Token"; } else { var Key = EncryptionLibrary.DecryptText(Token); string[] Parts = Key.Split(new string[] { ":~!@#" }, StringSplitOptions.None); Token = Parts[0]; } return(Token); }
public IActionResult Post([FromBody] LoginRequestViewModel value) { try { if (ModelState.IsValid) { var loginstatus = _users.AuthenticateUsers(value.UserName, EncryptionLibrary.EncryptText(value.Password)); if (loginstatus) { var userdetails = _users.GetUserDetailsbyCredentials(value.UserName, EncryptionLibrary.EncryptText(value.Password)); if (userdetails != null) { // Jason Web Token (Jwt) security token handler var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(_appSettings.Secret); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, userdetails.UserId.ToString()) }), Expires = DateTime.UtcNow.AddDays(1), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); value.Token = tokenHandler.WriteToken(token); // Remove password before returning value.Password = null; value.Usertype = userdetails.RoleId; return(Ok(value)); } else { value.Password = null; value.Usertype = 0; return(Ok(value)); } } value.Password = null; value.Usertype = 0; return(Ok(value)); } value.Password = null; value.Usertype = 0; return(Ok(value)); } catch (Exception) { throw; } }
public async Task <UsersProfileViewModel> GetAllTransactions() { var userId = Convert.ToInt32(this.User.FindFirstValue(ClaimTypes.Name)); var userProfile = await _userProfile.GetUserByIdAsync(userId); var tempUserProfile = mapper.Map <UsersProfileViewModel>(userProfile); tempUserProfile.Password = EncryptionLibrary.DecryptText(tempUserProfile.Password); return(tempUserProfile); }
public Task <Users> Handle(NewUser request, CancellationToken cancellationToken) { var tempUsers = AutoMapper.Mapper.Map <Users>(request); tempUsers.CreatedDate = DateTime.Now; tempUsers.Createdby = 1; tempUsers.Password = EncryptionLibrary.EncryptText(request.Password); _users.InsertUsers(tempUsers); return(Task.FromResult(tempUsers)); }
public ActionResult Login(User loginUser) { try { if (string.IsNullOrEmpty(loginUser.Username) && (string.IsNullOrEmpty(loginUser.Password))) { ModelState.AddModelError("", "Enter Username and Password"); } else if (string.IsNullOrEmpty(loginUser.Username)) { ModelState.AddModelError("", "Enter Username"); } else if (string.IsNullOrEmpty(loginUser.Password)) { ModelState.AddModelError("", "Enter Password"); } else { loginUser.Password = EncryptionLibrary.EncryptText(loginUser.Password); UserManager usermgr = new UserManager(); if (usermgr.ValidateRegisteredUser(loginUser)) { var UserID = usermgr.GetLoggedUserID(loginUser); var UserFullName = usermgr.GetUserFullName(UserID); var UserImage = usermgr.GetUserImage(UserID); var UserStatus = usermgr.GetUserStatus(UserID); if (UserStatus) { Session["UserID"] = UserID; HttpContext.Session["UserFullName"] = UserFullName; Session["UserImg"] = UserImage; return(RedirectToAction("Index", "Home")); } else { ModelState.AddModelError("", "Inactive User Access. Please contact Administrator."); return(View("Login", loginUser)); } } else { ModelState.AddModelError("", "Invalid Username or Password."); loginUser.Password = ""; loginUser.ConfirmPassword = ""; return(View("Login", loginUser)); } } return(View("Login", loginUser)); } catch { return(View()); } }
public Admin Post([FromBody] Login objLogin) { Admin objReturn = null; objLogin.Password = EncryptionLibrary.EncryptText(objLogin.Password); using (Admin_BAL objBAL = new Admin_BAL()) { objReturn = objBAL.Validate(objLogin.EmailId, objLogin.Password); } return(objReturn); }
private bool Authorize(HttpActionContext actionContext) { try { var encodedString = actionContext.Request.Headers.GetValues("Token").First(); bool validFlag = false; if (!string.IsNullOrEmpty(encodedString)) { var key = EncryptionLibrary.DecryptText(encodedString); string[] parts = key.Split(new char[] { ':' }); var RandomKey = parts[0]; // Random Key var UserID = Convert.ToInt32(parts[1]); // UserID var RoleID = Convert.ToInt32(parts[2]); // RoleID var SchoolID = Convert.ToInt32(parts[3]); // SchoolID var AcademicYearID = Convert.ToInt32(parts[4]); // AcademicYearID long ticks = long.Parse(parts[5]); // Ticks DateTime IssuedOn = new DateTime(ticks); var tokenModel = (from token in db.Tokens where token.TokenKey == RandomKey select token).FirstOrDefault(); if (tokenModel != null) { var ExpiresOn = (from token in db.Tokens where token.TokenID == tokenModel.TokenID select token.ExpiresOn ).FirstOrDefault(); if ((DateTime.Now > ExpiresOn)) { validFlag = false; } else { validFlag = true; } } else { validFlag = false; } } return(validFlag); } catch (Exception) { return(false); } }
public ActionResult Login(LoginViewModel loginViewModel) { try { if (!string.IsNullOrEmpty(loginViewModel.Username) && !string.IsNullOrEmpty(loginViewModel.Password)) { var Username = loginViewModel.Username; var password = EncryptionLibrary.EncryptText(loginViewModel.Password); var result = _ILogin.ValidateUser(Username, password); if (result != null) { if (result.ID == 0 || result.ID < 0) { ViewBag.errormessage = "Entered Invalid Username and Password"; } else { var RoleID = result.RoleID; remove_Anonymous_Cookies(); //Remove Anonymous_Cookies HttpContext.Session.SetString("UserID", Convert.ToString(result.ID)); HttpContext.Session.SetString("RoleID", Convert.ToString(result.RoleID)); HttpContext.Session.SetString("Username", Convert.ToString(result.Username)); if (RoleID == 1) { return(RedirectToAction("Dashboard", "Admin")); } else if (RoleID == 2) { return(RedirectToAction("Dashboard", "Customer")); } else if (RoleID == 3) { return(RedirectToAction("Dashboard", "SuperAdmin")); } } } else { ViewBag.errormessage = "Entered Invalid Username and Password"; return(View()); } } return(View()); } catch (Exception) { throw; } }
public static apiheaderdata GetAuthorize(string encodedString) { apiheaderdata apidata = new apiheaderdata(); if (!string.IsNullOrEmpty(encodedString)) { var key = EncryptionLibrary.DecryptText(encodedString); string[] parts = key.Split(new char[] { ':' }); apidata.UserID = Convert.ToInt32(parts[1]); // UserID apidata.RoleID = Convert.ToInt32(parts[2]); // RoleID apidata.SchoolID = Convert.ToInt32(parts[3]); // SchoolID apidata.AcademicYearID = Convert.ToInt32(parts[4]); // AcademicYearID } return(apidata); }