Forgot password Page - javascript

Good Afternoon every one,
I know this is very old question but I am very new to programming.Could any one help me
I have a forgot password page and it contains
Save button type is submit,Go to login link and one "User Name" of type input text.
Now when I click on save it should execute the following code
enter code here public VWUser ResetPassword(string userName)
{
using (var db = new AppDB())
{
var data = db.VWUsers.FirstOrDefault(m => m.UserName == userName && m.TenantId==Helper.TenantId);
if (data == null)
throw Helper.AppException(ExceptionTypes.Data, LocalText.ERR_UnAuthorizedAccess);
var password = SecurityManager.GenerateRandomPassword();
//data.Password = SecurityManager.Hash(password);
data.Password = SecurityManager.EncryptData(password);
db.SaveAndAssertChanges();
var result = db.VWUsers.First(x => x.UserName == data.UserName && x.TenantId ==Helper.TenantId);
result.xPassword = password;
return result;
}
}
And my Js will be like below
$(document).ready(function () {
debugger;
$("#frm-data").validate({
rules: {
UserName: {
required: true,
maxlength: 50,
},
},
showErrors: Helper.validateForm,
submitHandler: function (form) {
debugger;
Helper.httpPost("~/Login/ForgotPass",form, function (result) {
if (result.Status == 1) {
Helper.redirect("Login/Index");
}
else {
Helper.warning("Invalid Username or Password.");
// Helper.warning(result.Data);
}
})
}
});
})
can any one let me know how to do this.

Related

Boolean State Value Changes to Undefined on Second onSubmit

I'm working on a React project and implementing email validation and setting the state to true when it doesn't pass and false when it does. Validation part works, but getting undefined state on second onSubmit.
A bit more detail: I'm checking the state onChange and onSubmit. onChange seems to work as expected. onSubmit does work on the first click/submit but the very next click/submit, it changes the state to 'undefined' and I have no idea why.
Best to view my codepen and start filling in the email field and checking the console as I'm logging the state.
Here's a snippet of the code:
this.state = {
inputs: {
name: '',
email: '',
message: '',
},
show: true,
errors: {
name: false,
email: false,
message: false,
},
};
validateEmail(email) {
const re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
handleOnChange = e => {
const { name, value } = e.target;
const emailInput = e.target.value;
const emailValid = this.validateEmail(emailInput);
if (name === 'email') {
this.setState({
inputs: {
email: emailInput,
},
errors: {
email: !emailValid,
},
});
} else {
this.setState({
inputs: {
...this.state.inputs,
[name]: value,
},
errors: {
...this.state.errors,
[name]: false,
},
});
}
console.log('errors.email onChange = ' + this.state.errors.email);
};
So, why is this happening? and how can I solve?
You have missed the else condition when the field is not empty. that will remove the error object key from state, that is the one gives you the undefined error.
rewrite the handleSubmit function like this.
handleSubmit = (e, slackPost) => {
e.preventDefault();
console.log('errors.email onClick = ' + this.state.errors.email);
let inputFields = document.getElementsByClassName('form-input');
let invalidEmailMessage = document.querySelector('#invalid-email-message');
let failMessage = document.querySelector('#fail-message');
let failMessageBox = document.querySelector('.alert-fail');
// empty array to house empty field names
const emptyFieldNames = [];
// empty object to house input state
let errors = {};
// loop through input fields...
for (var i = 0; i < inputFields.length; i++) {
if (inputFields[i].value === '') {
let inputName = inputFields[i].name;
// add name to new array
emptyFieldNames.push(inputFields[i].getAttribute('name'));
// add input name and value of true to new object
errors[inputName] = true;
failMessageBox.style.display = 'block';
} else {
let inputName = inputFields[i].name;
errors[inputName] = false;
}
}
debugger;
this.setState({ errors });
if (emptyFieldNames.length > 0) {
failMessage.innerHTML =
'Please complete the following field(s): ' + emptyFieldNames.join(', ');
} else if (this.state.errors.email === true) {
invalidEmailMessage.innerHTML = 'Please enter a valid email';
} else {
console.log('For Submitted!');
}
};

crypto: var keyWords = key.words: TypeError: Cannot read property 'words' of undefined

having an issue using crypto. i'm pretty sure my issue is on line 75 in the saveAccounts function. I believe at this point the accounts var will consist of an empty [] as assigned in the getAccounts function (since there is nothing to 'getItemSync' from 'accounts' in 'storage'. I have a feeling the problem has something to do with the format of the data i'm trying to encrypt but i can't wrap my head around it. been trouble shooting for some time now. days. full-error report at below my code.
console.log('starting password manager');
var crypto = require("crypto-js");
var storage = require('node-persist');
storage.initSync();
var argv = require('yargs')
.command('create', 'Create a new account', function(yargs){
yargs.options({
name: {
demand: true,
alias: 'n',
description: "Account name (eg: Github, SnapChat).",
type: 'string'
},
username: {
demand: true,
alias: 'u',
description: "Please provide a username for your account.",
type: 'string'
},
password: {
demand: true,
alias: 'p',
description: "Please provide a password for your account.",
type: 'string'
},
masterPassword: {
demand: true,
alias: 'm',
description: "Please provide a MASTER password.",
type: 'string'
}
}).help('help');
})
.command('get', 'Get an existing account', function(yargs){
yargs.options({
name: {
demand: true,
alias: 'n',
description: "Account name (eg: Github, SnapChat).",
type: 'string'
},
masterPassword: {
demand: true,
alias: 'm',
description: "Please provide a MASTER password.",
type: 'string'
}
}).help('help');
})
.help('help')
.argv;
var command = argv._[0];
function getAccounts (masterPassword){
console.log("function getAccounts has been run");
var encryptedAccount = storage.getItemSync('accounts');
var accounts = [];
// decrypt
if (typeof encryptedAccount !== 'undefined') {
var bytes = crypto.AES.decrypt(encryptedAccount, masterPassword);
accounts = JSON.parse(bytes.toString(crypto.enc.Utf8));
}
// return accoutns array
return accounts;
}
function saveAccounts (accounts, masterPassword){
console.log("function saveAccounts has been run");
// encrypt accounts
var encryptedAccounts = crypto.AES.encrypt(JSON.stringify(accounts), masterPassword);
// setItemSync
storage.setItemSync('accounts', encryptedAccounts.toString());
// return accounts
return accounts;
}
function createAccount(account, masterPassword){
var accounts = getAccounts(masterPassword);
accounts.push(account);
console.log("back to function createAccount");
saveAccounts(account, masterPassword);
}
function getAccount(accountName, masterPassword){
var accounts = getAccounts(masterPassword);
var matchedAccount;
accounts.forEach(function(account){
if (account.name === accountName) {
matchedAccount = account;
}
});
return matchedAccount;
}
if (command === "create") {
var createdAccount = createAccount({
name: argv.name,
username: argv.username,
password: argv.password
}, argv.masterPassword);
console.log('Account created!');
console.log(createdAccount);
} else if (command === "get") {
if (masterPassword !== argv.m || typeof masterPassword === undefined) {
console.log("Your password was incorrect.");
} else {
var accountReturned = getAccount(argv.name, argv.masterPassword);
if(typeof(accountReturned) === undefined){
console.log("This account doesn't exist.");
} else {
console.log("Your account info:");
console.log(accountReturned);
}
}
}
the full error code looks like this
starting password manager
function getAccounts has been run
back to function createAccount
function saveAccounts has been run
/media/david/08053ee9-7733-4986-97be-f5cac7a80746/david/Projects/Node-Password-Manager/node_modules/crypto-js/aes.js:96
var keyWords = key.words;
^
TypeError: Cannot read property 'words' of undefined
at Object.C_algo.AES.BlockCipher.extend._doReset (/media/david/08053ee9-7733-4986-97be-f5cac7a80746/david/Projects/Node-Password-Manager/node_modules/crypto-js/aes.js:96:32)
at Object.CryptoJS.lib.Cipher.C_lib.Cipher.BufferedBlockAlgorithm.extend.reset (/media/david/08053ee9-7733-4986-97be-f5cac7a80746/david/Projects/Node-Password-Manager/node_modules/crypto-js/cipher-core.js:119:19)
at Object.CryptoJS.lib.Cipher.C_lib.BlockCipher.Cipher.extend.reset (/media/david/08053ee9-7733-4986-97be-f5cac7a80746/david/Projects/Node-Password-Manager/node_modules/crypto-js/cipher-core.js:457:27)
at Object.CryptoJS.lib.Cipher.C_lib.Cipher.BufferedBlockAlgorithm.extend.init (/media/david/08053ee9-7733-4986-97be-f5cac7a80746/david/Projects/Node-Password-Manager/node_modules/crypto-js/cipher-core.js:104:19)
at Object.subtype.init (/media/david/08053ee9-7733-4986-97be-f5cac7a80746/david/Projects/Node-Password-Manager/node_modules/crypto-js/core.js:68:46)
at Object.subtype.init (/media/david/08053ee9-7733-4986-97be-f5cac7a80746/david/Projects/Node-Password-Manager/node_modules/crypto-js/core.js:68:46)
at Object.subtype.init (/media/david/08053ee9-7733-4986-97be-f5cac7a80746/david/Projects/Node-Password-Manager/node_modules/crypto-js/core.js:68:46)
at Object.C_lib.Base.create (/media/david/08053ee9-7733-4986-97be-f5cac7a80746/david/Projects/Node-Password-Manager/node_modules/crypto-js/core.js:95:32)
at Object.CryptoJS.lib.Cipher.C_lib.Cipher.BufferedBlockAlgorithm.extend.createEncryptor (/media/david/08053ee9-7733-4986-97be-f5cac7a80746/david/Projects/Node-Password-Manager/node_modules/crypto-js/cipher-core.js:63:26)
at Object.CryptoJS.lib.Cipher.C_lib.SerializableCipher.Base.extend.encrypt (/media/david/08053ee9-7733-4986-97be-f5cac7a80746/david/Projects/Node-Password-Manager/node_modules/crypto-js/cipher-core.js:669:37)
You should compare typeof to the string — 'undefined'. See typeof docs
else if (command === "get") {
if (masterPassword !== argv.m || typeof masterPassword === 'undefined') {
console.log("Your password was incorrect.");
} else {
var accountReturned = getAccount(argv.name, argv.masterPassword);
if(typeof(accountReturned) === 'undefined'){
console.log("This account doesn't exist.");
} else {
console.log("Your account info:");
console.log(accountReturned);
}
}
I am working on the same Udemy course I think. Good luck!
I had the same problem, and after trying different things, I found the error was the type of object to encrypt. ---> $crypto.encrypt("string","string"). Simple as that. When you try to decrypt with an object instead of string, you get that error.
If you have long pass_sec on your .env file then change key.
Like this:
this false - > PASS_SEC=thisisverylongstring
this true - > PASS_SEC=short
in the password saving in .env support to be String ...
ecample
SECRET="yoursecret" with quotation mark.

Meteor Method.call issue in jquery-validation

I have a form to change password. I need to validate the old password. But jquery addMethod is always return false in Meteor.call. How to make it workable. Or is there any way? My bellow code will be more details about my issue.
$.validator.addMethod( 'checkPassword', ( oldpassword ) => {
var digest = Package.sha.SHA256(oldpassword);
Meteor.call('checkPassword', digest, function(err, result) {
var res = result.error != null; // even if this is "true", error message is visible.
return res;
});
});
$( "#changepassword" ).validate({
rules: {
oldpassword: {
required: true,
checkPassword: true
}
},
messages: {
oldpassword: {
required: "Please enter your Old Password",
checkPassword: "Password doesnt match!!!" //this message is visible all the time.
} }
});
Here is my method call
Meteor.methods({
checkPassword: function(digest){
if (Meteor.isServer) {
if (this.userId) {
var user = Meteor.user();
var password = {digest: digest, algorithm: 'sha-256'};
var result = Accounts._checkPassword(user, password);
return result;
}
}
}
});
here the meteor package

How to pass data from Action to Ajax success function in mvc4?

hi i am want to when login succesfully then call my success function otherwise call error function
View code here
<div class="container">
<div class="login-container">
<div class="avatar"><img src="#Url.Content("~/Content/images/download.jpeg")" style="max-width:95%;" /></div>
<div class="form-box">
#using (Html.BeginForm())
{
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
#Html.TextBoxFor(m => m.UserId, new { #class = "form-control", #id="userid", #placeholder = "Username", #required = "required", #maxlength = "20" })
</div>
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
#Html.PasswordFor(m => m.Password, new { #class = "form-control", #id = "userpass", #placeholder = "Password", #required = "required", #maxlength = "20" })
</div>
<button class="btn btn-info btn-block login" type="submit" id="login-btn"><i class="glyphicon glyphicon-log-in"></i> Login</button>
}
</div>
</div>
ajax code here:
<script>
$(document).ready(function () {
$('#login-btn').click(function () {
var dataObject = {
Id: $("#userid").val(),
Password: $("#userpass").val()
};
$.ajax({
url: '#Url.Action("Login","Account")',
type: "POST",
data: dataObject,
dataType: "json",
success: function (data) {
if (data.toString() == "login") {
toastr['success']("Login Successfully");
}
else if (data.toString() == "error") {
toastr['error']("Id or Password is incorrect");
}
},
error: function () {
toastr['error']("Hello");
}
});
});
});
Controller Code here:
[HttpPost]
public ActionResult Login(LoginMaster model)
{
string message = "";
if (ModelState.IsValid)
{
try
{
var user = from emp in db.LoginMasters
where emp.UserId == model.UserId && emp.Password == model.Password
select emp;
var rol = user.FirstOrDefault();
if (rol != null)
{
var realrol = rol.Role;
if (realrol == "admin")
{
message = "login";
return RedirectToAction("Index", "Home");
}
else if (realrol == "user")
{
Session["userid"] = rol.UserId;
message = "login";
return RedirectToAction("User", "Home");
}
}
else
{
message = "error";
}
}
catch (Exception ex)
{
ViewBag.cath = ex.Message;
}
}
else
{
message = "error";
}
if (Request.IsAjaxRequest())
{
return new JsonResult { Data = message, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
return View();
i am want to when we login succesfully that time call this
toastr['success']("Login Successfully");
and when login fail that time call
toastr['error']("Id or Password is incorrect");
please solve this problem.
thanks in advance!
Assuming your controller code hits the part that returns the json then you can access it via .Data:
success: function (data) {
if (data.Data == "login") {
toastr['success']("Login Successfully");
}
else if (data.Data == "error") {
toastr['error']("Id or Password is incorrect");
}
}
You set the .Data property within your code here:
new JsonResult { Data = message ...
and the problem with your success call is that it is testing the entire json object, not the .Data property.
data.toString() == "login"
no sir our problem is our Action where we can put hit point that is not run in a sequence our this point is firstly execute
if (Request.IsAjaxRequest())
{
return new JsonResult { Data = message, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
then after execute this part
try
{
var user = from emp in db.LoginMasters
where emp.UserId == model.UserId && emp.Password == model.Password
select emp;
var rol = user.FirstOrDefault();
if (rol != null)
{
var realrol = rol.Role;
if (realrol == "admin")
{
message = "login";
return RedirectToAction("Index", "Home");
}
else if (realrol == "user")
{
Session["userid"] = rol.UserId;
message = "login";
return RedirectToAction("User", "Home");
}
}
else
{
message = "error";
}
}
catch (Exception ex)
{
ViewBag.cath = ex.Message;
}
so problem is we can not set correct string in message variable so please first of all you can make a sample in js fiddle then provide me link
As you have used this code in your script. :
var dataObject = {
Id: $("#userid").val(),
Password: $("#userpass").val()
};
if your LoginMaster model contains Id & Password it'll display data.
If you have UserId & Password then you have to change your code in script like below.
var dataObject = {
UserId: $("#userid").val(),
Password: $("#userpass").val()
};
In short replace Id with UserId.

accounts-meld not working

Accounts-meld is not working for me, should it work out the box or do I need to do something? I am rolling my own ui and using Meteor.loginWithXX() for Facebook and Twitter. I have tried creating an account manually then logging in with a third party however it just creates a new user and doesn't merge them.
Am I doing something wrong?
I am configuring my services with
Accounts.loginServiceConfiguration.insert({
"service": "facebook",
"appId": "XXXXXXXXXXXX",
"secret": "XXXXXXXXXXXX"
});
Accounts.loginServiceConfiguration.insert({
"service": "twitter",
"consumerKey": "XXXXXXXXXXXX",
"secret": "XXXXXXXXXXXX"
});
Then I use Meteor.loginWithFacebook(); and Meteor.loginWithTwitter();
Any help would be greatly appreciated
Let me post the code I'm using and you can let me know if it's helpful. It's not my code and was gleamed from other answers but from so many I can't provide sources.
Your right to use service configuration to set up each service but you do need to install the package for that if you haven't already.
I then added an event that looks something like this for each login service I offer.
Template.login.events({
"click #loginWithFacebook": function (event) {
event.preventDefault();
Meteor.loginWithFacebook({
}, function(error) {
if (error) {
console.log(error);
}
});
}
});
I also then have an onCreateUser code block which does a check to see if it's a new user or if they are just using a new service as their login provider. This has been tweaked a little so you will need to take out the stuff that's not relevant.
Accounts.onCreateUser(function(options, user) {
var email, oldUser, service;
if (user.profile == null) {
user.profile = {};
if (options.profile != null) {
user.profile.name = options.profile.name;
user.profile.organisation = options.profile.organisation;
}
}
if (user.services != null) {
service = _.keys(user.services)[0];
email = user.services[service].email;
if (email != null) {
oldUser = Meteor.users.findOne({
"emails.address": email
});
if (oldUser != null) {
if (oldUser.services == null) {
oldUser.services = {};
}
if (service === "google" || service === "facebook") {
oldUser.services[service] = user.services[service];
Meteor.users.remove(oldUser._id);
user = oldUser;
}
} else {
if (service === "google" || service === "facebook") {
if (user.services[service].email != null) {
user.emails = [
{
address: user.services[service].email,
verified: true
}
];
} else {
throw new Meteor.Error(500, "" + service + " account has no email attached");
}
user.profile.name = user.services[service].name;
user.profile.organisation = Organisations.find({}, {'fields': {'_id':1}}).fetch()[0];
}
}
}
}
return user;
});

Categories