How to reset password in passport-local strategy in Sails.js - sails.js

Passport.js provides authentication framework in Node.js. It only deals with Authentication.
Now I would like to enable password reset. Since there is no password field in User model, only passports, how can I reset password in passport-local strategy? I assume that user needs to generate a new password and call something to override the existing hash of the old password. What methods are those and where can I find them?

When the user selects to reset his/her password, what you can do is send an email to the user with a link containing a token associated with the user. Once the user clicks on the link, you validate the user based on the token & email and then show the reset password HTML. Once user enters the new password, in the backend code, you set the password on the User object after hashing and then save it. You can set the token as null too.
A sample code with base64 will be as shown below
user.salt = new Buffer(crypto.randomBytes(16).toString('base64'), 'base64');
user.password = user.hashPassword('newPassword');
user.token = undefined;
user.save(...)
The hashPassword method is as given.
UserSchema.methods.hashPassword = function(password) {
if (this.salt && password) {
return crypto.pbkdf2Sync(password, this.salt, 10000, 64).toString('base64');
} else {
return password;
}
};
The above code is auto-generated with Yeoman

Related

Validate user inputted password against user password saved on parse server before changing password

I am working on an application using Parse.com as backend support.I have implemented change Password using this code
if (pwdController!.text == newpwdController!.text) {
user.password = pwdController!.text;
await user.save();
I want the user to enter the current password before allowing them change it to a new one but when I try to get the current password from the parseuser object it returns null, all the other similar questions I've seen such as this Change Password and Forgot Password with ParseUser in Parse.com aren't validating that the user has the correct current password. How can I validate that the password entered by user is their current password before letting them change it?
You can verify that the user has entered the correct current password by calling the ParseUser.login method with the username and entered password. Then check if it returns a successful response.
ParseUser user = await ParseUser.currentUser();// this gets the current user object
var nuser = (user.username, oldpwdController!.text, user.username);
var resp = await nuser.login();
if (resp.success) {
user.password = pwdController!.text;
await user.save();
The snippet of code above assumes that you have two textcontrollers(oldpwdController for current password, and pwdController for new password to change to).

Mongodb Realm custom JWT auth causes empty custom user data

I'm working on an app that currently uses email/password auth provided by MongoDB Realm. I'm thinking of switching to using the custom JWT auth for various reasons. I'm quite extensively using the custom user data to store all sorts of things. When I switch from email/password to custom JWT the login works, but the custom user data is empty...
This works fine:
const jwt = await axios.post("https://MYAPI.COM/login", {
user: email.value,
password: password.value,
});
console.log(`jwt: ${JSON.stringify(jwt.data)}`);
const credentials = Realm.Credentials.emailPassword(
email.value,
password.value
);
// const credentials = Realm.Credentials.jwt(jwt.data);
console.log("logging in");
const user = await realm.logIn(credentials);
await user.refreshCustomData();
const customUserData = await user.refreshCustomData()
console.log(`Logged in as ${JSON.stringify(user)}`);
console.log(`customUserData: ${JSON.stringify(customUserData)}`);
When I uncomment the line changing the credentials the custom user data is empty
I was running into a similar problem using Custom Function for authentication.
I was mapping the userId incorrectly -
custom user data is based on the ID of the authenticated user, please make sure that the user ID is mapped correctly in the corresponding collection.
https://www.mongodb.com/docs/realm/users/enable-custom-user-data/

NestJS & Passport: Change JWT token on user password change?

I'm trying to reset/change the token (JWT) for users who changed their passwords on NestJS API with PassportJS. Here is a clean example of how this authorization works: https://docs.nestjs.com/security/authentication.
I want to generate a new token on password change to make sure, that on every device on which the user was logged in, after password change they will get unauthorized and so logged out.
This is how I handle the password change in users service:
async changePassword(uId: string, password: any) {
return await this.userRepository.createQueryBuilder()
.update(User)
.set({ password: await bcrypt.hash(password.value, 10) })
.where("userId = :userId", { userId: uId })
.execute();
}
There are no prebuild methods to do this I think. JwtService got only 5 methods: decode, sign (this one is used to generate a token), signAsync, verify and verifyAsync.
So how can I do this properly?
You'd need some sort of way to invalidate the JWT that was already given to the user. As you can't just do that to a token, generally (it's stateless, it holds its own validity) you'd need to create a JWT restrictlist in a database that you check the incoming JWT against. If the JWT is in the restrictlist, reject the request. Otherwise, let it through (if it's valid of course)

Authenticatee FrontendUser via PHP API call from Extbase

First of all im Using TYPO3 Version 8.7.
The current problem i'm facing regards authentication of FrontendUser (fe_user) stored on a given page (in this case pid 168).
Apparently i'm trying to authenticate user with given credentials sent by a mobile application. I'm able to parse the user data and perform an authentication:
// plain-text password
$password = 'XXX';
// salted user password hash
$saltedPassword = 'YYY';
// keeps status if plain-text password matches given salted user password hash
$success = FALSE;
if (\TYPO3\CMS\Saltedpasswords\Utility\SaltedPasswordsUtility::isUsageEnabled('FE')) {
$objSalt = \TYPO3\CMS\Saltedpasswords\Salt\SaltFactory::getSaltingInstance($saltedPassword);
if (is_object($objSalt)) {
$success = $objSalt->checkPassword($password, $saltedPassword);
}
}
While debugging this code snippet, i recognized the password sent by the user via Request, which gets encrypted with the given Salt algorithm change every time i retry this request. I'm not sure how to get a correct authentication, if the password changes constantly.
The $objSalt object contains the right Hashing Method($pbkdf2-sha256$25000), the password stored in the Database starts with the same prefix, but the actual payload is different.
So What is the exact problem or whats the thing i'm missing in the above code to complete the authentication?
Thanks for your help
BR,
Martin
the password sent by the user via Request, which gets encrypted with the given Salt algorithm change every time i retry this request
Yes, that because the salt is changed every time.
You should retrieve the salting instance with:
$instance = \TYPO3\CMS\Saltedpasswords\Salt\SaltFactory::getSaltingInstance($user['password']);

How to implement user login in Jersey API

I am implementing RESTful API using javax.ws.rs. The response of the calls that I need to implement requires knowing which user is logged in currently. I tried making a separate call for the user login:
api.myapi.co.uk/authenticate?username=xxxx&password=xxxx
where I basically save the user information is a global variable
and then tried to make another call to retrieve information from the database based on the user that has been saved earlier but I find the value as null during the second call. What am I missing? Is my approach wrong? do you have any suggestions please?
Your code probably looks like this, right?
#Path("/")
public class MyResource{
private String username;
private String password;
#Path("authenticate")
public String authenticate(#QueryParam("username") username, #QueryParam("password") password) {
if(!username.equals("zainab") || !password.equals("letmein"))
return "Incorrect username or password";
this.username=username;
this.password=password;
return "Sucessfully authenticated";
}
#Path("secret")
public String secret() {
if(username == null || password == null)
return "Sorry, not authorized";
return "You are authorized: "+username;
}
}
If so, the problem is that JAX-RS creates a new Resource object for each request. A request to "/secret" then uses a new instance of MyResource, which has username and password as null.
Then, you might think, I'll just make it static! Then, your resource can't handle concurrent requests. What if Person A calls "/authenticate", then "/secret". Then Person B calls "/secret" without authenticating. He can then access "/secret" without authenticating!
Anyways, this violates the idea of RESTful services. The S in RESTful stands for "Stateless". This means that the server should store no state per client, and possibly give the user a token to pass with concurrent requests.
One possibility is to accept the username and password for every request to secret ("/secret?username=zainab&password=letmein"). Or you could implement token-based authentication, where the user calls "/authenticate" to get a token, and they pass that token on all later requests. Here is a link to help with that.
Also, note that username and password is usually not send in the URL as a query param, but instead in the Authorization HTTP header as such Authorization: base64encode("USERNAME:PASSWORD")