How to add custom "check your email" page in next-auth? (verifyRequest) - reactjs

I am trying to have my own text and style there. In the documentation (https://next-auth.js.org/configuration/options#pages) it says we can add a custom page by adding verifyRequest: '/auth/verify-request' but no example
I tried to create a custom verify-request.js file with this code https://github.com/nextauthjs/next-auth/blob/1838e43b275fa36b1eb7bd046eead6795cfd0f2d/src/server/pages/verify-request.js but it do not working for me...
Is there an example ot tutorial how to do it? I searched everything all I could and nothing.

Update the pages options in [...nextauth].js (located in /pages/api/auth)
pages: {
signIn: "/auth/signin",
signOut: "/auth/signout",
error: "/auth/error", // Error code passed in query string as ?error=
verifyRequest: "/auth/verify", // (used for check email message)
// newUser: null, // If set, new users will be directed here on first sign in
},
Then create your custom page (in the above case name it "verify.js") in the location /pages/auth/ as defined above. This will override the default verify request page, and you can custom whatever you want on your verify page

When you try to add it a route like /pages/api/auth/verify it makes a problem. you should add your page directly into pages route something like /pages/verify and it should all be fine. You can use every page you'd like.

Related

Is there a way to rename automatically generated routes JSON file in Next.js?

I have a problem, when I click to go to the /analytics page on my site, adblockers block the analytics.json file that's being requested by Next.js as they think it's an analytics tracker (it's not, it's a page listing analytics products).
Is there a way to rename the route files Next.js uses when navigating to server-side rendered pages on the client-side?
I want to either obfuscate the names so they're not machine readable, or have a way to rename them all.
Any help appreciated.
With thanks to #gaston-flores I've managed to get something working.
In my instance /analytics is a dynamic page for a category, so I moved my pages/[category]/index.tsx file to pages/[category]/category.tsx and added the following rewrite:
// next.config.js
module.exports = {
async rewrites() {
return [
{
source: "/:category",
destination: "/:category/category",
},
];
},
};
This now gets the category.json file rather than analytics.json, which passes the adblockers checks and renders as expected.
Note that due to having a dynamic file name in the pages/[category] directory (pages/[category]/[product].tsx), I had to move that to pages/[category]/product/[product].tsx as I was seeing the /analytics page redirected to /analytics/category for some reason without this tweak.

How to Navigate to separate URL in react router Dom v6?

i am making a validation form , with a function that checks for password and email , if true it should navigate to a separate website (not to a path within the web). But it is not working
This is my code below:
function validate() {
if (email==='123#123.com' && password==="123456"){
console.log(email);
history('http://www.dummy.com/webmail')
}
}
return{
.
.
.
<Button className={stylesAuth.submitButton} variant="warning" onClick={validate}>
}
How should I do so?
Since you're redirecting to an external website, you can simply use plain old JavaScript and do a:
window.location.href = "https://www.dummy.com/webmail";
For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Location/href.
A little bit more information: using history doesn't make sense in this case, it is only meant for internal navigation within your web application. In fact, you cannot even push an external URL onto the history stack:
The new URL must be of the same origin as the current URL; otherwise, pushState() will throw an exception.
https://developer.mozilla.org/en-US/docs/Web/API/History/pushState

symfony 5 web debug toolbar showing anonymous and cannot redirect after onAuthenticationSuccess

I have been following along with the following Symfony tutorials, but I believe they are using version 4 and I am using version 5. They reach a point in the tutorial which shows that the web debug toolbar shows the user's email logged and they even pointed out that if you see logged as anonymous, then just refresh. I did refresh, but it still shows as anon.
As you can see by the following screen shot, login was successful and it shows the correct username as well:
I started to watch the first part of the tutorial - listed below - when I reached a point in the second part that pointed out that I should watch the first part, which made sense, that I might have missed something, but that was an even older version of Symfony and things have changed in version 5.
First part of the tutorial
Second part of the tutorial
After going through the tutorials, I still have the web debug tool showing anon. Now, I am using React as a form to POST the email and password - see next screen shot - would that effect how the web debug toolbar, but I do not see how, because the console shows that the system knows the user.
Does anyone know a config that needs to be changed?
I have tried changing the following within src\Security\TokenAuthenticator - getUser from:
return $this->em->getRepository(User::class)
->findOneBy(['apiToken' => $credentials])
;
To:
return $this->em->getRepository(User::class)->findOneBy(['email' => $credentials['email']]);
But no change, still shows anon
Also, as the subject states, I cannot redirect via onAuthenticationSuccess
public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
// on success, let the request continue
return new RedirectResponse($this->urlGenerator->generate('app_homepage'));
}
I do not see why this does not work. Again, is it because I am posting via a React app?
Turns that it is because I am running an older version of the browser Firefox and the log in is working. You can see by the screen shot of both Firefox and Chrome, that it is working Chrome
As far as the redirect goes, PHPStorm was saying that I did not have urlGenerator available in the TokenAuthenticator class. As a result, I should have noticed before and this is what I did to correct it:
In my src\Security\TokenAuthenticator I have the following:
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
In my constructor:
private $em;
private $urlGenerator;
public function __construct(EntityManagerInterface $em, UrlGeneratorInterface $urlGenerator)
{
$this->em = $em;
$this->urlGenerator = $urlGenerator;
}
My onAuthenticationSuccess:
public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
// on success, let the request continue
// redirect to some "app_homepage" route - of wherever you want
return new RedirectResponse($this->urlGenerator->generate('app_homepage'));
}
But it is still not working
I have tried
use Symfony\Component\HttpFoundation\RedirectResponse;
private $redirectResponse;
public function __construct(EntityManagerInterface $em, RedirectResponse $redirectResponse)
{
$this->em = $em;
$this->redirectResponse = $redirectResponse;
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
// on success, let the request continue
// redirect to some "app_homepage" route - of wherever you want
return $this->redirectResponse->redirectToRoute('app_homepage');
}
But PHPStorm tells me that it cannot find method redirectToRoute within class RedirectResponse
The only thing that I have found to work with redirecting users to the home page after successful is login, is within my React login app. I have an async to my handleClick method, after the fetch POST, I have a setTimeout of 3000 that uses a plain javascript:
window.location.href = '/';
I would love to know the answer to why I cannot redirect via the Authenticator class that I have created, but at least someone who is using Firefox will not have to wonder why their web debug tool is not showing that the user has successfully logged in while still showing anon

Given a moz-extension:// URL opened by bookmark, how can I switch to tab using extension code?

This is related to some other questions I am working on.
Say, for whatever reason, a user has bookmarked a page (call it pageURL of the pattern moz-extensions://MY-OWN-WEBEXT-ID/*) intended to be opened from a browser action context menu, and opened it in a tab, then opened many other tabs and possibly other windows. User knows the extension tab exists somewhere and doesn't want to keep opening new bookmarks, and so wants to use the add-on's browser action context menu to find the extension page's tab. Likewise, I don't want my add-on to open a duplicate tab.
The problem, since the add-on did not create the tab (a bookmark did), I have no tab ID to pass to browser.tabs.update( WebExtTab.id, { active: true } ) or window ID to pass to browser.windows.update( WebExtWindow.id, { focused: true } ). (WebExtWindow referring to a WebExtensions browser.windows.Window object, not a browser window object.
I can use browser.extension.getViews( ) to generate a list of browser window objects (aka tabs), and checking each window.location.href find that indeed the URL (and thus tab) does exist (somewhere), but I can't use that window object to focus on the tab nor to get a tab ID for browser.tabs.update().
In the case of multiple browser windows, I can't even get the right browser window to raise up given that window object, because the window objects returned by getViews have no id property with which to call browser.windows.update(). Similar to the tabs problem.
Finally, I can't use browser.tabs.query( { 'url': pageURL } ) to find the tab ID, because the url option must conform to match patterns, which FORBID using the moz-extension:// scheme.
What would be exceptionally useful was if the WebExtensions API allowed an extension to find the tabs and windows of all pages that belong to itself, regardless if those pages were opened by the add-on, manually entered, a bookmark or clicking a link.
For example, given a pageURL conforming to moz-extension://MY-OWN-WEBEXT-ID/*, one could do a browser.tabs.query and/or a browser.windows.query on a url matching the above pattern, and return a WebExt tab/window object, respectively. If such a tab/window was not opened by the WebExt API (i.e. bookmark), then generate a new object (i.e. a pseudo-create), to populate with existing data (i.e. location.href, status flags, etc) and generate new data as needed (i.e. the ID numbers), such that the returned object is usable within the context of the API.
This would fill a gap in API coverage where certain methods (i.e. getViews) return dead-end browser objects which have no hooks and no connection with the WebExt API and are thus mostly useless.
The simple answer: ++RTFM. browser.windows.getAll() will allow you to populate the windows objects with tab info. You need the permissions: [ "tabs" ] in manifest.json to get the tab.url property. But other than that, all the windows and tab objects will have an ID so that you can trivially focus window and switch active tab!
Note: This requires Firefox 52.0+ to make use of the async/await feature. Otherwise, you just have to use function generators and promises. Also, I've omitted any error checking, for demonstration purposes, but it might be a good idea to put them back in later.
async function tabCreate ( opts ) {
var pageURL = browser.runtime.getURL( opts.page + '.html' );
var extWins = await browser.windows.getAll( { populate: true, windowTypes: [ 'normal' ] } );
// Look for tab by comparing url, if url matches (i.e. tab exists), then focus window and make tab active.
for ( var extWin of extWins ) {
for ( var extTab of extWin.tabs ) {
if ( pageURL === extTab.url ) {
console.log( `My Extension->tabCreate(): Window ${extWin.id}, Tab ${extTab.id}:\n\t${extTab.url}` );
browser.windows.update( extWin.id, { focused: true } );
browser.tabs.update( extTab.id, { active: true } );
return;
}
}
}
// Otherwise, create tab.
browser.tabs.create( { url: pageURL } );
}
Opinion: I wish I didn't have to give away the tabs permission just for this feature. It would be nice if we always got our own moz-extension://MY-OWN-WEBEXT-ID/* urls, and null URLs for other tabs, without permissions given to access all tabs, but oh well.
Example Usage:
function myWebExt_Options ( ) {
tabCreate( {
'page': 'options',
'panel': 1
} );
}
browser.contextMenus.create( {
title: 'Options',
contexts: [ 'browser_action' ],
onclick: myWebExt_Options
} );
Note: I've implemented this to expect options in an opts object that has a page property, which I use as a shorthand to generate the full page URL. This is because of another question which requires passing a message to the page, which I store in opts.panel. But none of that is necessary. It could be changed to a flat string, or use the full 'getURL' generated elsewhere as a parameter. Change to suit your need and style.

CakePHP reverse routing issues

I've been using routing with "slug" as a named parameter, for example:
Router::connect('/category/:slug', array('controller'=>'categories', 'action'=>'view'), array('pass'=>array('slug'), 'slug'=>'[a-z0-9\-]+'));
I've now stumbled across a problem because I want to restrict the above route to logged in users only, so I've put this in the beforeFilter() function of my CategoriesController:
if(!$this->Auth->loggedIn()) {
$this->Auth->deny('view');
}
Now if I go to /category/my-category (while logged out) I'll be redirected to my application's login page, unfortunately after I log in I'm redirected to /categories/view/my-category/slug:my-category
This is due to line 317 of AuthComponent.php, where we have:
$this->Session->write('Auth.redirect', Router::reverse($request));
So it seems when I do Router::reverse($request) on the above route it doesn't work properly (because it thinks "my-category" should be both a passed and a named parameter).
Is this a problem with the way I've set up this route, or is it a bug with CakePHP? Surely Router::reverse($request) should always return the URL we're currently at?
Any advice appreciated...
I'm not 100% sure if it is a bug or not, but until we find out a work-around could be to manually set the new loginRedirect in your category controller like so:
if(!$this->Auth->loggedIn()) {
$this->Auth->deny('view');
$this->Auth->loginRedirect = '/categories/' . $this->request->params['slug'];
}
Note, check that $this->request->params['slug'] is the right var to use, not 100% off the top of my head.

Resources