After how many days should I reset my JWT cookie for Android local database? - netezza

I'm currently doing forgot password functionality for the first time and here's the code so far.
sends the email for the user that has the URL with the JWT token
router.post('/change-password', verifyAuth, resetPassword);
receives and confirms JWT then changes password
router.post('/change-password/:token/:password', confirmResetPassword);
the process I'm currently thinking about is in the email I send the user to
http://localhost:3000/change-passowrd?token=TOKEN_VALUE
but I'm not sure if this is a smart idea or not? I can also use cookies if it's better, any idea?

It's okay to store the JWT token store in the URL for reset password functionality. You have to send this link using Email or any other secure communication service.
I implemented this feature
https://yourapp.com/home/reset/${token}
const data = {
from: "yourcompanymail#outlook.com",
to: user.email,
subject: "Please reset your password",
text: `Hello ${user.name},\n\nI heard that you lost your Teeny password. You can use the following link to reset your password: https://yourapp.com/home/reset/${token}
};
transporter.sendMail(data, function (error, info) {
if (error) {
console.log(error);
} else {
console.log("Email sent: " + info.response);
}
});
Now if the user hits this URL, validate the token and redirect or render the change password page. But don't send the password through the URL.

Related

Linking Twitter account to user account (twitter-passport)

Currently, a user is able to login in and sign up for my application no problem. I've then added a "Link your twitter user to account" button which when clicked takes the user to '/auth/twitter'. This then kicks off passport-twitter and the oAuth process begins.
Right now, I'm using passport-twitter as the package for twitter oAuth. This process works. I'm able to get the user successfully authenticated. Here is the code.
However two problems: I don't see a way to 1) keep the user signed into Twitter so they don't have to keep doing this flow of reconnecting their twitter every time they want to push content to it from my app. and 2) associate the Twitter user and the signed in user to my application. Long term, I plan to add other social media accounts, so the user will have multiple social media linked. Twitter will be just one.
Problem #2: I wasn't able to do an axios.get call from my redux store or from the front end to '/auth/twitter/' otherwise I could then just get the information back from the call and then post it to the user's table (right?). So, instead I'm accessing '/auth/twitter' from an tag in the front end to kick off the flow.
passport.use(
new TwitterStrategy(
{
consumerKey: "XXX",
consumerSecret: "XXX",
callbackURL: "http://localhost:8080/auth/twitter/callback",
// callbackURL: "http://www.localhost:8080/home",
includeEmail: true,
},
async(accessToken, refreshToken, profile, cb) => {
console.log('got the prodile')
const twitterIDforOAuth = profile.id
const { id, username } = profile;
let theuser = await User.findOne({
where: {
twitterID: id
}
})
if(theuser){
console.log('FOUND USER', '\n', theuser)
} else {
try {
console.log('NO USER FOUND')
var passwordUser = (Math.random() + 1).toString(36).substring(7);
console.log('CREATING USER')
theuser = await Promise.all([
User.create({
twitterID: id,
username : username,
password: passwordUser
})
])
console.log('USER CREATED');
} catch (error) {
console.log(error);
}
}
//this callback calls the auth/callback url to kick off the redirect process
// need to send username and password to /auth/signup
return cb(null, {username: username, password: passwordUser})
//Line below sends too much data that is irrelevant for the user... lets review it?
// return cb(null, {username: twitterIDforOAuth})
}
)
);
app.get('/auth/twitter', passport.authenticate("twitter"));
app.get(
"/auth/twitter/callback",
passport.authenticate("twitter", {
failureRedirect: "/login",
failureMessage: true,
session: false
}),
async (req, res) => {
var user = req.user;
console.log(user.username, user.password);
//GET USERNAME AND PASSWORD
var username = user.username;
var password = user.password;
///they need to login the app
//auth/login
res.redirect('/AccountSettings')
}
);
The user is being redirected to /AccountSettings while they go through this flow, so I know that the user is 100% authenticated and signed in with Twitter (otherwise they'd be pushed to /login, which isn't happen).
Most people in this flow create a user in their database using the information returned from Twitter.
However, I'm trying to link this information to the signed in user, and keep them signed into Twitter so the user doesn't need to keep reconnecting their Twitter account (at least not often). (With access to their Twitter account, my plan is to allow them to push content to it)
Currently I'm hitting the '/auth/twitter' route with an tag which's href takes it to '/auth/twitter'. Is this the right way about it or is this approach causing my linkage issue?
What are people's recommendation for this issue? Whats the right way to approach linking social media accounts to a signed in user's account?
I'm using Express, Redux, React, Postgres, and passport-twitter
SOLUTION: How to passing data in TwitterStrategy, PassportJS?
had to create a state object outside the /auth/twitter route and then added a id param to the /auth/twitter route so the full route was /auth/twitter/:id
once I got the id I saved it to a state route outside the route in the server file that was accessible to the callback function later in the proces.

How do I avoid React Native GoogleSignIn by sending to google a password violation

I used #react-native-google-signin/google-signin": "^8.0.0" to create a google sign in button into my app.
When I used it, google recognised it as not trusted app, so send my an email to advice of a violation, and now every time I use a password saved on my google account to login on any site or application, he gives me a message telling me to change all of my passwords. I solved to remove the message, by ignoring for every passwords, almost 200 :/. But it's just temporary solution, cause if I do login again to my app it will happen again. How can I say to google that it is an app in developing, is there any mode to activate? Here's my code:
GoogleSignin.configure({
scopes: ['https://www.googleapis.com/auth/drive.readonly'], // what API you want to access on behalf of the user, default is email and profile
webClientId: '15299853035-njb79hdij6h1svo22drigurca1qb4djb.apps.googleusercontent.com', // client ID of type WEB for your server (needed to verify user ID and offline access)
offlineAccess: true, // if you want to access Google API on behalf of the user FROM YOUR SERVER
// hostedDomain: '', // specifies a hosted domain restriction
// forceCodeForRefreshToken: true, // [Android] related to `serverAuthCode`, read the docs link below *.
// accountName: '', // [Android] specifies an account name on the device that should be used
iosClientId: '15299853035-siujgcjtol0lfja83n7p6fk55cq6jinn.apps.googleusercontent.com', // [iOS] if you want to specify the client ID of type iOS (otherwise, it is taken from GoogleService-Info.plist)
// googleServicePlistPath: '', // [iOS] if you renamed your GoogleService-Info file, new name here, e.g. GoogleService-Info-Staging
// openIdRealm: '', // [iOS] The OpenID2 realm of the home web server. This allows Google to include the user's OpenID Identifier in the OpenID Connect ID token.
// profileImageSize: 120, // [iOS] The desired height (and width) of the profile image. Defaults to 120px
});
try {
await GoogleSignin.hasPlayServices();
const { idToken } = await (await GoogleSignin.signIn());
const googleCredential = await GoogleAuthProvider.credential(idToken);
await signInWithCredential(authApp, googleCredential)
.then(async(userCredential) => {
if(!authApp.currentUser.emailVerified)
{
sendEmailVerification(authApp.currentUser)
.then(() => {
// Email verification sent!
// ...
})
.catch((error)=>{
setLoading(false)
console.log(error)
})
}
......

How to update the password of a Supabase user on a NextJs project?

I'm facing an issue updating a password for a supabase user on a BlitzJs (NextJs) project.
Basically, I have a reset password method that works perfectly. First I send an email with a reset link, that opens a page where the user can update his password like so:
const { error, data } = await supabase.auth.api.updateUser(token, { password: password.trim() })
the token being the one in the url, provided in the email link.
So far, so good, but when I try to update the password for a logged in user, using the exact same method supabase.auth.api.updateUser, it fails to find the user;
The difference is the token is the session.access_token
So I've tried to use the supabase.auth.api.updateUserById method, but it gives me another error: { message: 'User not allowed', status: 401 }
Any ideas? I feel the supabase docs about this is not very clear, and probably outdated as it doesn't show all the available methods :/
Update password for authenticated user.
const { user, error } = await supabase.auth.update({password: 'new password'})
For more informations check: Supabase references

How do I manage an access token, when storing in local storage is not an option?

I have a ReactJS app running in browser, which needs access to my backend laravel-passport API server. So, I am in control of all code on both client and server side, and can change it as I please.
In my react app, the user logs in with their username and password, and if this is successful, the app recieves a personal access token which grants access to the users data. If I store this token in local storage, the app can now access this users data by appending the token to outgoing requests.
But I do not want to save the access token in local storage, since this is not secure. How do I do this?
Here is what I have tried:
In the laravel passport documentation, there is a guide on how to automatically store the access token in a cookie. I believe this requires the app to be on the same origin, but I cannot get this to work. When testing locally, I run the app on localhost:4000, but the API is run on my-app.localhost. Could this be a reason why laravel passport does not make a cookie with the token, although they technically both have origin localhost?
OAuth has a page on where to store tokens. I tried the three options for "If backend is present", but they seem to focus on how the authorization flow rather than how to specifically store the token.
Here's the relevant parts of my code (of course, feel free to ask for more if needed):
From my react app:
const tokenData = await axios.post(this.props.backendUrl + '/api/loginToken', { email: 'myEmail', password: 'myPassword' })
console.log('token data: ', tokenData)
const personalAccessToken = tokenData.data.success.token;
var config = {
headers: {
'Authorization': "Bearer " + personalAccessToken
};
const user = await axios.get(this.props.backendUrl + '/api/user', config);
From the controller class ApiController:
public function loginToken()
{
if (Auth::attempt(['email' => request('email'), 'password' => request('password')])) {
$user = Auth::user();
$success['token'] = $user->createToken('MyApp')->accessToken;
return response()->json(['success' => $success], 200);
} else {
return response()->json(['error' => 'Unauthorised'], 401);
}
}
and the loginToken function is called from the /api/loginToken route.
Expected and actual results:
Ideally, I would love to have the token saved in a cookie like in the passport documentation, so I don't even have to attach the token to outgoing requests from the react app, but I'm not sure that this is even possible. Perhaps with third party cookies?
Else, I'd just like to find some way to store the token securely (for example in a cookie?), and then append it to outgoing calls from the react app.

Firebase handle reset password emails for not verified users

When a new user registers the web application a verification email is sent to him. I prevent new users to log in before verification.
Meanwhile if the verification link expires and the user forgets the password he will click the reset password link and will receive an email.
So I think that I should handle reset password action together with verification at once. Otherwise user will not be able to login even after changing the password.
function handleResetPassword(auth, actionCode) {
auth.verifyPasswordResetCode(actionCode)
.then(function (email) {
// Showing the reset screen and ask the user for
// the new password.
}).catch(function (error) {
//
});
};
When user saves the new password:
function saveNewPassword() {
auth.confirmPasswordReset(actionCode, vm.form.password).then(function (resp) {
// Password reset has been confirmed and new password updated.
// Now auto sign in user
auth.signInWithEmailAndPassword(vm.email, vm.form.password).catch(function (error) {
// Handle Errors here.
});
firebase.auth().onAuthStateChanged(function (user) {
if (user) {
// user signed in.
// check whether the user is verified
// if not set true
user.updateProfile({ emailVerified: true })
}
});
}).catch(function (error) {
//
});
}
But the code below doesn't work as I expected as it has no affect. I can change other user data (e.g. displayName) but not (emailVerified). It only works with firebase email verification.
user.updateProfile({ emailVerified: true })
What is the recommended approach for this type of user scenario ?
You can't update emailVerified from the client, otherwise any unverified user would be able to do that without enforcing actual ownership of the email.
You would need to do it with the Admin SDK using an HTTP endpoint (you can use Firebase Functions for that too). However, you need to ensure that the password reset code succeeded. So in this case you need to run your code on the server. Here is how it would work:
var firebase = require('firebase');
var admin = require('firebase-admin');
// Initialize the client and admin instances.
// firebase.initializeApp(clientConfig);
// admin.initializeApp(adminConfig);
// Send the reset code and the new password to your backend.
var email = null;
// Get email corresponding to code.
firebase.auth().checkActionCode(actionCode)
.then(function(info) {
email = info.email;
// Confirm password reset.
firebase.auth().confirmPasswordReset(actionCode, password)
});
.then(function() {
// Get uid of user with corresponding email.
return admin.auth().getUserByEmail(email);
}).then(function(userRecord) {
// Password reset succeeded. Email can be verified as the user
// must have received the code via their email confirming
// ownership.
return admin.auth().updateUser(userRecord.uid, {emailVerified: true});
});

Resources