NextAuth.js - Credentials authentication, adding reset password button - reactjs

I am developing login system with next/auth and have credentials logging system implemented with invitation only system. Is there a way to add Reset password link to the generated /api/auth/signin page?

Your best bet would be to create your own custom signIn page (https://next-auth.js.org/configuration/pages) where you then can add the "reset password" functionality that you desire

I saw and used the one similar with this. Perhaps this can help you.
Send a post from my backend to create a new auth0 user. At this point the auth0 user.email_verified = false.
Send a post to trigger a password reset email for the new user.
{% if user.email_verified == false %}
<h1>Invitation to our awesome app</h1>
<p>Please verify your email address and set your initial password by clicking the following link:</p>
<p>Confirm my account</p>
{% else %}
<h1>Password Change Request</h1>
<p>You have submitted a password change request. </p>
<p>If it wasn't you please disregard this email and make sure you can still login to your account. If it was you, then to <strong>confirm the password change click here</strong>.</p>
{% endif %}
<p>If you have any issues with your account, please don’t hesitate to contact us at 1-888-AWESOMECO.</p>
<br>
Thanks!
<br>
Configure a redirect on the Password Reset email template so that when the user clicks the invitation link, they will be prompted to reset their password and then they will be redirected to our app, which will then ask them to login
I added an auth0 Rule to set email_verified = true on first login/password reset ( it was one of the canned options)
}
if (user.email_verified || !user.last_password_reset) {
return callback(null, user, context);
}
// Set email verified if a user has already updated his/her password
request.patch({
url: userApiUrl + user.user_id,
headers: {
Authorization: 'Bearer ' + auth0.accessToken
},
json: { email_verified: true },
timeout: 5000
},
function(err, response, body) {
// Setting email verified isn't propagated to id_token in this
// authentication cycle so explicitly set it to true given no errors.
context.idToken.email_verified = (!err && response.statusCode === 200);
// Return with success at this point.
return callback(null, user, context);
});
}
Next time we need to send them a password reset email it will use the “existing user” flavor of the template
The invitation email pw reset link has a configurable TTL – it defaults to 5 days. So if they don’t accept the invite it will eventually timeout (and we could send them another one if needed)

Related

MS Teams permissions for creating a group

Can someone help me understand how to add a permission to a MS-Graph API call?
I'm trying to create a new team/group but I'm getting a permission error. Obviously I need add the Team.Create permission if I want to create a Team. Which I did as seen in the image below
Here's the sample code where I tried to add the permission to the MSAL client request:
// Initialize Graph client
const client = graph.Client.init({
// Implement an auth provider that gets a token
// from the app's MSAL instance
authProvider: async (done) => {
try {
// Get the user's account
const account = await msalClient
.getTokenCache()
.getAccountByHomeId(userId);
let scope = process.env.OAUTH_SCOPES.split(',');
scope.push("Team.Create");
console.log("Added a extra permission request");
console.log("scope = " + scope);
if (account) {
// Attempt to get the token silently
// This method uses the token cache and
// refreshes expired tokens as needed
const response = await msalClient.acquireTokenSilent({
scopes: scope,
redirectUri: process.env.OAUTH_REDIRECT_URI,
account: account
});
console.log("\nResponse scope = " + JSON.stringify(response) + "\n");
// First param to callback is the error,
// Set to null in success case
done(null, response.accessToken);
}
} catch (err) {
console.log(JSON.stringify(err, Object.getOwnPropertyNames(err)));
done(err, null);
}
}
});
return client;
Then I get the following error:
The user or administrator has not consented to use the application with ID 'xxxxxxx'
named 'Node.js Graph Tutorial'. Send an interactive authorization request for this user and resource
I did give permissions to Team.Create in the Azure Active Directory, so how do I consent to this app gaining access? Note this code is the tutorial for learning Graph: https://learn.microsoft.com/en-us/graph/tutorials/node
Judging by the screenshot, you can't give admin consent to the permission as it is grayed out.
You'll need to try if you can grant user consent.
acquireTokenSilent won't work in this case since consent is needed.
You need to use one of the interactive authentication methods to trigger user authentication, at which time you can consent to the permission on your user's behalf.
In that sample specifically, you probably need to modify the scopes here: https://github.com/microsoftgraph/msgraph-training-nodeexpressapp/blob/08cc363e577b41dde4f6a72ad465439af20f4c3a/demo/graph-tutorial/routes/auth.js#L11.
And then trigger the /signin route in your browser.

Firebase authentication with localId / idToken (instead of email / password)

In my app, when a user logs in, I use firebase.auth to authenticate the user based on the email/password the user typed:
firebase.auth().signInWithEmailAndPassword(userInputs.email.value, userInputs.password.value)
Then I dispatch it to the redux state and also set the received localId and idToken on the local storage:
localStorage.setItem('token', response.user.qa);
localStorage.setItem('localId', response.user.uid);
When the user closes the app window and then reopen the app later, the localId and idToken are still set in the localstorage, but to re-authenticate I need to supply email and password. Is it possible to authenticate with localId/idToken, or should I save the email/password on localStorage instead of saving the two tokens?
Upon checking if the user is authenticated:
var user = firebase.auth().currentUser;
console.log(user);
I get 'null'.
It seems that I must sign in even if I already have the localId, without signing in I don't have access to the database.
Also, obviously my database rules grant access to the db only to authenticated users:
{
"rules": {
".read": "auth != null",
".write": "auth != null"
}
}
Thanks in advance!
You don't have to store the email & password in the localstorage.
Firebase library automatically retain the auth infomation locally.
The cause of you get null is you are trying to get user info with Synchronous code.
Which means that you are trying to get user before the firebase library's initalization.
firebase.auth().currentUser; // <= synchronous
Following code runs Asynchronously and you can get user after the firebase library initalize.
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
} else {
// No user is signed in.
}
});

How to check user password in angular's strongloop SDK?

I want to check the current user's password in order to allow him to change his/her password.
According to the user model docs, the way to do this is using the user.hasPassword method, by I get a "is not a function" error.
https://docs.strongloop.com/display/LB/User#user-prototype-haspassword
There is no reference to this in the angular SDK docs, so I'm guessing this method is not avalable from angular. https://docs.strongloop.com/display/public/LB/AngularJS+JavaScript+SDK#AngularJSJavaScriptSDK-Authentication
Any clues on how to accomplish this?
Sorry if this is just semantics, but if you are using the built in User model, you don't ever "check a user's password," you check if they are authenticated with a valid authToken that is set in a header.
But if you are trying to change a user's password and requiring them to log in before changing it, you can also just call User.login() and verify that you get a success response from the API. Then use the new password and persist it by updating the User instance with an update or updateAttributes.
See https://apidocs.strongloop.com/loopback-sdk-angular/#user
Will look something like this (warning: quick writeup, not tested!):
User.login({email: $scope.email, password: $scope.oldPassword}, function(response){
// user login was valid, now update user with new password by user id
//
User.prototype$updateAttributes({id: response.user.id}, {password: $scope.newPassword},
function(response) {
// success
}, function(response) {
// fail
});
}, function(response) {
// login failed, send to login screen
});

Email verification through silverlight

I've built a Silverlight website where users can create an account and login. Right now, users just create an account through a form and can directly login. I want to incorporate a email verification feature, where the user will receive an email with a verification URL and only then can he login. I also wish to incorporate a forgot password feature that sends an email to the users registered email address to recover password.
How can I do this in silverlight. I'm using Windows SQL Azure as the back-end database. Will I have to create a separate Application for creating user accounts and recovering passwords?
Hope this helps you out on part A of your problem.
I noticed the post might throw you off a bit, so I decided to write a method that will do this for you in the quickest amount of time.
public bool Send(string fromEmail, string toEmail, string subject, string body)
{
try
{
MailMessage message = new MailMessage();
message.From = new MailAddress(fromEmail);
message.To.Add(new MailAddress(toEmail));
message.Subject = subject;
message.Body = body;
message.IsBodyHtml = false;
SmtpClient smtp = new SmtpClient();
smtp.EnableSsl = true;
smtp.Send(message);
return true;
}
catch (Exception ex)
{
return false;
}
}
Essentially, once they create their account you would want to call this filling out all variables. Make sure in your body of text you have a link that sends them to a page where they can submit "activate" their account.
This will essentially be a bit value in the database that is set to false by default and won't be set to true until they click on the "submit" or "activate" button from the link that would be in the body of text.
For password recovery you would do the same. Except instead of sending them to a page to activate their account you'd send them to a page where they could just re-create their password. Since the database doesn't care if the password is old or new you could just send them to a page where they create a new password. You wouldn't even need to create a temp password for them (Unless you wanted to for experience and for a extra caution).
Happy Coding! ;)

getting referer from auth in cakePHP

I have a link on the main page that is only accessible if they are logged in. However, if this link is clicked, I want to show a custom error message on the login page (a custom 'Message.auth').
i.e. I want (pseudo code)
if (referer == '/users/reserve'){
Message.auth = 'Please log in to reserve tickets';
}
else {
Message.auth = 'Please log in to access that page';
}
Where would I put this bit of code?
Provided you have auth flash messages being output in the login view, this should work:
// login action of users_controller.ctp
if ($this->Session->check('Auth.redirect')
&& $this->Session->read('Auth.redirect') == '/users/reserve') {
$this->Session->write('Message.auth', 'Please log in to reserve tickets');
}
to get referer you can call $this->referer() to get the referring URL then pass that value to your view.
see: referer

Resources