When I put my password Environment Variables it won't work - next.js

My code works as below in my localhost. What I'm trying to do is put my password in my .envlocal but it won't work.
working code
export default function (req, res) {
let nodemailer = require('nodemailer')
const transporter = nodemailer.createTransport({
port: 465,
host: "smtp.gmail.com",
auth: {
user: 'myEmail#gmail.com',
pass: 'password123',
},
secure: true,
});
const mailData = {
from: 'keshibatmail#gmail.com',
to: 'kensukeshibata#gmail.com',
subject: `Message From ${req.body.name}`,
text: req.body.message + " | Sent from: " + req.body.email,
html: `<div>${req.body.message}</div><p>Sent from: ${req.body.email}</p>`
}
transporter.sendMail(mailData, function (err, info) {
if(err)
console.log(err)
else
console.log(info);
})
console.log(req.body)
res.send('success')
}
What I tried.
My next.js is
"next": "10.x"
,
So I should be able to use this since my next.js is higher than 9.4 https://nextjs.org/docs/api-reference/next.config.js/environment-variables
I made .env.local file
NEXT_PUBLIC_PASSWORD=password123
then process.env.NEXT_PUBLIC_PASSWORD
I tried without NEXT_PUBLIC_ as well.
I get this error.
response: '535-5.7.8 Username and Password not accepted.
const transporter = nodemailer.createTransport({
port: 465,
host: "smtp.gmail.com",
auth: {
user: myEmail#gmail.com,
pass: process.env.NEXT_PUBLIC_PASSWORD,
},
secure: true,
});

Related

Failed to fetch. Possible Reasons: Cors Network failure URL Scheme

I trying to do a swagger documentation for an Express API and Firebase database, when I make request to my database in local with postman it work, but with the swagger interface I get this error:
Failed to fetch.
Possible Reasons:
CORS
Network Failure
URL scheme must be "http" or "https" for CORS request.
For my documentation I use swagger-autogen and swagger-ui-express
there is a example for the login endpoint:
const app = express();
const port = process.env.PORT || 8080;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(
cors({
origin: `http://localhost:${port}`,
methods: ["GET", "POST", "DELETE", "PUT", "PATCH"],
credentials: true,
})
);
app.use(helmet());
app.use(morgan("combined"));
app.get("/", (req, res) => {
res.status(200).json({ message: "Welcome" });
});
app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(swaggerFile, options));
swagger.js
const outputFile = "schemas/swagger.json";
const endpoints = \["routes/auth.js", "routes/menus.js"\];
const doc = {
info: {
version: "1.0.0",
title: "Menus API documentation",
description: "Documentation of MenusAPI",
termsOfService: "http://swagger.io/terms/",
contact: {
email: "contact#toto.com",
},
license: {
name: "Apache 2.0",
url: "http://www.apache.org/licenses/LICENSE-2.0.html",
},
},
servers: \[
{
url: "https://localhost:8081/menusapi/api/v1/",
},
\],
host: "/",
consumes: \["application/json"\],
produces: \["application/json"\],
securityDefinitions: {
OAuth2: {
type: "oauth2",
flows: {
authorizationCode: {
authorizationUrl: process.env.AUTH_UTI,
tokenUrl: process.env.TOKEN_URI,
scopes: {
read: "Grants read access",
write: "Grants write access",
},
},
},
},
bearerAuth: {
type: "http",
scheme: "bearer",
bearerFormat: "JWT",
},
},
"#definitions": {
AddUser: userSchema.registration,
Login: userSchema.login,
Menus: menusSchema,
},
};
swaggerAutogen(outputFile, endpoints, doc).then(() =\> {
require("../app");
});
routes/auth.js
router.post("/login", auth.login);
controllers/auth_controller.js
exports.login = async (req, res) =\> {
/\* #swagger.tags = \['Auth'\]
\#swagger.description = 'Service to login';
\#swagger.summary = "Service to login a user to the app";
\#swagger.security = \[{
"OAuth2": \[
'read',
'write'
\]
}\]
\#swagger.responses\[200\] = {
description: 'Login sucess',
schema: {
"message": "Successfully connected!",
"jwt": "A very long token",
"refresh_jwt": "An other long token"
}
}
console error:
throw new Error(`${(0, validate_1.invalidArgumentMessage)(arg, desc)} Cannot use "undefined" as a Firestore value${fieldPathMessage}. ` +
^
Error: Value for argument "value" is not a valid query constraint. Cannot use "undefined" as a Firestore value
I looked everywhere but I really don't know what to do

Strapi athentication returns AxiosError: Request failed with status code 400

using Strapi with Next js. Trying to authenticate with following code
const authenticate = () => {
const paylaod = {data: {
identifier: email,
password: password
}}
console.log(paylaod)
axios.post(`http://localhost:1337/api/auth/local`, paylaod).then((res, err) => {
console.log(res, err)
console.log(res,err)
const { jwt, user } = res.data
window.localStorage.setItem('jwt', jwt)
window.localStorage.setItem('userData', JSON.stringify(user))
router.push({
pathname: '/calendar',
});
}).catch(err => {
console.log(err)
})
}
Response I'm getting is:
AxiosError {message: 'Request failed with status code 400', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}
Dug every possible answer in forums and Stackoverflow, but nothing helped.
User I'm using is not super admin, registered fresh one in Strapi admin.
this is how my middleware list looks like
export default [
'strapi::errors',
'strapi::security',
'strapi::cors',
'strapi::poweredBy',
'strapi::logger',
'strapi::query',
'strapi::body',
'strapi::session',
'strapi::favicon',
'strapi::public',
];
and here's my (scrappy) env
HOST='127.0.0.1'
PORT=1337
APP_KEYS="gfhgfhgfhg,hfghghgf"
API_TOKEN_SALT="adfasdfads"
ADMIN_JWT_SECRET="adfasdfasdf"
JWT_SECRET="sdasdadfasdf"

NextAuth.js signIn() method not working using serverless-http in AWS Lambda

I am trying to deploy NextJs and NextAuth.js to AWS using CDK (Cloud Development Kit). I have cloned the NextAuth.js example project (https://github.com/nextauthjs/next-auth-example) and
installed "serverless-http" for handling the binding from Lambda to NextJs. I attempted to follow this guide https://remaster.com/blog/nextjs-lambda-serverless-framework but using AWS CDK instead of the serverless.yml file as I am integrating it with existing infrastructure.
next.config.js:
/** #type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
swcMinify: true,
images: {
unoptimized: true
},
output: 'standalone'
}
module.exports = nextConfig
[...nextauth].ts (From the example but using a simple credentials provider that always resolves):
import NextAuth, { NextAuthOptions } from "next-auth"
import CredentialsProvider from "next-auth/providers/credentials";
export const authOptions: NextAuthOptions = {
providers: [
CredentialsProvider({
name: "Credentials",
credentials: {
username: { label: "Username", type: "text", placeholder: "jsmith" },
password: { label: "Password", type: "password" }
},
async authorize(credentials, req) {
return { id: "1", name: "J Smith", email: "jsmith#example.com" }
}
})
],
theme: {
colorScheme: "light",
},
callbacks: {
async jwt({ token }) {
token.userRole = "admin"
return token
},
},
}
export default NextAuth(authOptions)
server.ts:
import { NextConfig } from "next";
import NextServer from "next/dist/server/next-server";
import serverless from "serverless-http";
// #ts-ignore
import { config } from "./.next/required-server-files.json";
const nextServer = new NextServer({
hostname: "localhost",
port: 3000,
dir: __dirname,
dev: false,
conf: {
...(config as NextConfig),
},
});
export const handler = serverless(nextServer.getRequestHandler());
It is being built using the following script:
#!/bin/bash
BUILD_FOLDER=.dist
yarn build
rm -rf $BUILD_FOLDER
mv .next/standalone/ $BUILD_FOLDER/
cp -r .next/static $BUILD_FOLDER/.next
rm $BUILD_FOLDER/server.js
cp -r next.config.js $BUILD_FOLDER/
cp -r node_modules/serverless-http $BUILD_FOLDER/node_modules/serverless-http
tsc server.ts --outDir .dist --esModuleInterop true
cp -r public $BUILD_FOLDER/
This is deployed using AWS written in CDK C#. Primarily using a HttpApi and a single Lambda. Each configured as shown below:
Lambda:
var function = new Function(this, "nextjs-function", new FunctionProps
{
Code = Code.FromAsset(...".dist"),
Handler = "server.handler",
Runtime = Runtime.NODEJS_16_X,
...
Environment = new Dictionary<string, string>
{
{ "NEXTAUTH_URL", "https://myDomainName.com" },
{ "NEXTAUTH_SECRET", portalSecret },
}
});
HttpApi:
var httpApi = new HttpApi(this, "http-api", new HttpApiProps
{
DisableExecuteApiEndpoint = true,
DefaultIntegration = new HttpLambdaIntegration("nextjs-route", function),
DefaultDomainMapping = new DomainMappingOptions
{
DomainName = "myDomainName.com"
}
});
Opening the deployed webpage and clicking the "Sign In" button at the top, I get taken to /api/auth/signin?callbackUrl=%2F with a form. Without touching the credentials I click "Sign in with credentials". This results in the page reloading and nothing happening. Expected behaviour should be a session and a redirect back to the home page (/) as is happening when running it locally using either yarn dev or yarn build && yarn start.
I get no errors client/server-side thus leaving me in the dark.
I suspect that it has to do with domain configuration but I am unable to find the problem. I tested with another NextJs/NextAuth project using a AWS Cognito provider. This also had problems as when I clicked the sign in button I got an "Unexpected token" error due to the underlying signIn(...) function (from the NextAuth library) trying to parse the fetched page as JSON, which turned out to be the sign-in-page. Thus my suspicion of something domain-related.

Mariasql with nodejs not working

I did:
var MariaSQLClient = require('mariasql');
var maria_connection = new MariaSQLClient({ host: '127.0.0.1', user: 'root', password: 'root', db: 'db1' })
But when i check whether it is connected or not using:
maria_connection.connected
false
It returns false always

Meteor slingshot file upload to Google Cloud Storage internal server error

I am trying to upload files using edgee:slingshot, but I have several errors. I have did everything as described in github page. This is my settings on server:
Slingshot.GoogleCloud.directiveDefault.GoogleSecretKey = Assets.getText('google-cloud-service-key.pem');
Slingshot.createDirective("myFileUploads", Slingshot.GoogleCloud, {
bucket: 'dossum-app',
GoogleAccessId: "GOOGXXXX",
GoogleSecretKey: "qZEsLZ/NiXXXXXXXXXXXXUW8NVjSvRb8SgdxXXXXX2",
acl: 'bucket-owner-full-control',
authorize: function() {
if (!this.userId) {
var message = 'Please login before posting file';
throw new Meteor.Error('Login Required', message);
}
return true;
},
key: function(file) {
var user = Meteor.users.findOne(this.userId);
return user.username + '/' + file.name;
}
});
And this is cors.json:
[{"origin": ["http://localhost:3000", "http://qnekt.zehinz.com"], "responseHeader": ["Origin", "Accept", "X-Requested-With", "Authorization", "Content-Type", "Content-Length", "Accept-Encoding", "X-CSRF-Token"], "method": ["GET", "HEAD", "DELETE", "PUT", "POST", "HEAD"], "maxAgeSeconds": 3600}]
If I run with above configuration I get this error without any details: {error: 500, reason: "Internal server error"....
I have tried to comment this line: //GoogleSecretKey:"qZEsLZ/NiEkXo641XHIUW8NVjSvRb8SgdxIyYcV2"
This time I receive this error:
{error: "Forbidden - 403", reason: "Failed to upload file to cloud storage", details: undefined ...
Can anyone please guide me?
Where should I get GoogleAccessId if I am using .pem file instead of GoogleSecretKey?
What should be the cors.json file for file uploading and public reading?
I had troubles with edgee:slingshot and Google Cloud Storage. But this settings now work for me:
//server
Slingshot.GoogleCloud.directiveDefault.GoogleSecretKey = Assets.getText('google-cloud-service-key.pem');
Slingshot.createDirective('avatarUploader', Slingshot.GoogleCloud, {
bucket: 'my_bucket',
GoogleAccessId: 'xxxxxxxxxxxxxx#developer.gserviceaccount.com',
acl: 'public-read',
authorize: function() {
if (!this.userId) {
var message = 'Please login before posting file';
throw new Meteor.Error('Login Required', message);
}
return true;
},
key: function(file) {
var user = Meteor.users.findOne(this.userId);
var ext = file.type.split('/')[1];
return user.username + '/' + randomString(20) + '.' + ext;
}
});
//CORS settings
[
{
"origin": ["*"],
"responseHeader": ["*"],
"method": ["GET", "POST", "PUT", "HEAD"],
"maxAgeSeconds": 3000
}
]
For details look here.

Resources