Looking for a backend dev that can simply help me implement MONGODB with nextJS and the current model I have now. I have bought https://www.devias.io admin dashboard, and just want to implement auth and database reading with it.
Just want the basic auth setup. It's already setup in the FILES just wanting to know how to configure it properly based on the devias guides
Has anyone done this before I can't find any documentation on it
It's setup with mock data at the moment
SRC/API/AUTH/index.js
import { createResourceId } from '../../utils/create-resource-id';
import { decode, JWT_EXPIRES_IN, JWT_SECRET, sign } from '../../utils/jwt';
import { wait } from '../../utils/wait';
import { users } from './data';
class AuthApi {
async signIn(request) {
const { email, password } = request;
await wait(500);
return new Promise((resolve, reject) => {
try {
// Find the user
const user = users.find((user) => user.email === email);
if (!user || (user.password !== password)) {
reject(new Error('Please check your email and password'));
return;
}
// Create the access token
const accessToken = sign({ userId: user.id }, JWT_SECRET, { expiresIn: JWT_EXPIRES_IN });
resolve({ accessToken });
} catch (err) {
console.error('[Auth Api]: ', err);
reject(new Error('Internal server error'));
}
});
}
async signUp(request) {
const { email, name, password } = request;
await wait(1000);
return new Promise((resolve, reject) => {
try {
// Check if a user already exists
let user = users.find((user) => user.email === email);
if (user) {
reject(new Error('User already exists'));
return;
}
user = {
id: createResourceId(),
avatar: undefined,
email,
name,
password,
plan: 'Standard'
};
users.push(user);
const accessToken = sign({ userId: user.id }, JWT_SECRET, { expiresIn: JWT_EXPIRES_IN });
resolve({ accessToken });
} catch (err) {
console.error('[Auth Api]: ', err);
reject(new Error('Internal server error'));
}
});
}
me(request) {
const { accessToken } = request;
return new Promise((resolve, reject) => {
try {
// Decode access token
const { userId } = decode(accessToken);
// Find the user
const user = users.find((user) => user.id === userId);
if (!user) {
reject(new Error('Invalid authorization token'));
return;
}
resolve({
id: user.id,
avatar: user.avatar,
email: user.email,
name: user.name,
plan: user.plan
});
} catch (err) {
console.error('[Auth Api]: ', err);
reject(new Error('Internal server error'));
}
});
}
}
export const authApi = new AuthApi();
then /SRC/API/AUTH/data.js
export const users = [
{
id: '5e86809283e28b96d2d38537',
avatar: '/assets/avatars/avatar-anika-visser.png',
email: 'demo#devias.io',
name: 'Anika Visser',
password: 'Password123!',
plan: 'Premium'
}
];
This is the documentation on it
JSON Web Token (JWT)
Most auth providers use this strategy under the hood to provide access tokens. Currently, the app doesn't cover the backend service, and this service is mocked (faked) using http client interceptors. The implementation is basic, but enough to give you a starting point.
How it was implemented
Since tokens are meant to be created on the backend server, they are built with encrypt, encode and decode utility methods because they are not meant to be used on the client. These utilities can be found in src/utils/jwt. These are for development purposes only, and you must remove (or avoid using) them.
How to use JWT Provider
The app is delivered with JWT Provider as default auth strategy. If you changed or removed it, and you want it back, simply follow these steps:
Step 1: Import the provider
Open src/pages/_app.js file, import the provider and wrap the App component with it.
// src/pages/_app.js
import { AuthConsumer, AuthProvider } from '../contexts/auth/jwt-context';
const App = (props) => {
const { Component, pageProps } = props;
return (
<AuthProvider>
<Component {...pageProps} />
</AuthProvider>
);
};
Step 2: Set the hook context
Open src/hooks/use-auth.js file and replace the current context the following line:
import { AuthContext } from '../contexts/auth/jwt-context';
How to use auth
Retrieve user profile
In the example below, you can find how it can be used in any component not just the App. Should you want to use it in any other component, you'll have to import the useAuth hook and use it as needed.
// src/pages/index.js
import { useAuth } from '../hooks/use-auth';
const Page = () => {
const { user } = useAuth();
return (
<div>
Email: {user.email}
</div>
);
};
Auth methods / actions
For simplicity and space limitations, the code below is used only to exemplify, actual code can be found in the components.
// src/pages/index.js
import { useAuth } from '../hooks/use-auth';
const Page = () => {
const { login } = useAuth();
const handleLogin = () => {
// Email/username and password
login('demo#devias.io', 'Password123!');
};
s
return (
<div>
<button onClick={handleLogin}>
Login
</button>
</div>
);
};
Implemented flows
Currently, the app only covers the main flows:
Register
Login
Logout
const mongoose = require('mongoose');
const jwt = require("jsonwebtoken");
// Connect to MongoDB
mongoose.connect('mongodb://localhost/yourdbname', {
useNewUrlParser: true,
useUnifiedTopology: true
});
const userSchema = new mongoose.Schema({
id: {
type: String,
required: true,
unique: true
},
email: {
type: String,
required: true
},
name: {
type: String,
required: true
},
password: {
type: String,
required: true
},
plan: {
type: String,
default:
'Standard'
},
avatar: {
type: String,
default:
null
},
});
const User = mongoose.model('User', userSchema);
const JWT_SECRET = process.env.JWT_SECRET;
const JWT_EXPIRES_IN = '7d';
class AuthApi {
async signIn(request) {
const {
email,
password
} = request;
const user = await User.findOne({
email
});
if (!user || (user.password !== password)) {
throw new Error('Please check your email and password');
}
const accessToken = jwt.sign({
userId: user.id
}, JWT_SECRET, {
expiresIn: JWT_EXPIRES_IN
});
return {
accessToken
};
}
async signUp(request) {
const {
email,
name,
password
} = request;
const existingUser = await User.findOne({
email
});
if (existingUser) {
throw new Error('User already exists');
}
const newUser = new User({
id: mongoose.Types.ObjectId(),
email,
name,
password,
plan: 'Standard',
avatar: null,
});
await newUser.save();
const accessToken = jwt.sign({
userId: newUser.id
}, JWT_SECRET, {
expiresIn: JWT_EXPIRES_IN
});
return {
accessToken
};
}
async me(request) {
const {
accessToken
} = request;
const decoded = jwt.verify(accessToken, JWT_SECRET);
const {
userId
} = decoded;
const user = await User.findById(userId);
if (!user) {
throw new Error('Invalid authorization token');
}
return {
id: user.id,
avatar: user.avatar,
email: user.email,
name: user.name,
plan: user.plan
};
}
}
export const authApi = new AuthApi();
Related
I am using NextAuth.js for authentication and MongoDB to save the user information.
When the user registers with email & password, it saves to MongoDB.
If this user login with a Google account that has the same email address, it returns Error: Action login with HTTP GET is not supported by NextAuth.js
If the Google email address does not exist in the DB, then it works okay.
How do I check if the email address exists in the DB before login into the website by using GoogleProvider?
import { MongoDBAdapter } from '#next-auth/mongodb-adapter';
import clientPromise from '../../../lib/mongodb';
import CredentialsProvider from 'next-auth/providers/credentials';
import GoogleProvider from 'next-auth/providers/google';
import { verifyPassword } from '../../../lib/auth';
import { connectToDatabase } from '../../../lib/db';
const { parseCookies } = require('nookies');
export default async function auth(req, res) {
const cookies = parseCookies({ req });
const maxAge =
cookies.remember === 'true' ? 30 * 24 * 60 * 60 : 1 * 24 * 60 * 60; // 30 days, 1 day
return await NextAuth(req, res, {
providers: [
CredentialsProvider({
async authorize(credentials) {
const client = await connectToDatabase();
const usersCollection = await client.db().collection('users');
const result = await usersCollection.findOne({
email: credentials.email,
});
if (!result) {
client.close();
throw new Error('No user found!');
}
const isValid = await verifyPassword(
credentials.password,
result.password
);
if (!isValid) {
client.close();
throw new Error('Could not log you in!');
}
client.close();
const user = {
id: result._id,
email: result.email,
name: result.name,
role: result.role,
remember: credentials.remember,
};
return user;
},
}),
GoogleProvider({
clientId: process.env.GOOGLE_ID,
clientSecret: process.env.GOOGLE_SECRET,
}),
],
adapter: MongoDBAdapter(clientPromise),
callbacks: {
// called after sucessful signin
jwt: async ({ token, user }) => {
user && (token.user = user);
return token;
}, // called whenever session is checked
session: async (data) => {
const { session, token } = data;
session.user = token.user;
return session;
},
},
secret: process.env.SECRET_KEY,
session: {
strategy: 'jwt',
maxAge: maxAge,
},
jwt: {
secret: process.env.SECRET_KEY,
encryption: true,
},
pages: {
signIn: './login',
},
});
}
You can use the SignIn callback to control if a user is allowed to sign in https://next-auth.js.org/configuration/callbacks#sign-in-callback
callbacks: {
async signIn({ user, account, profile, email, credentials }) {
if(account.provider === 'google') {
//check the user on your database and return true if is allowed to signIn
const isAllowedToSignIn = true
if (isAllowedToSignIn) {
return true
} else {
// Return false to display a default error message
return false
// Or you can return a URL to redirect to:
// return '/unauthorized'
}
}
}
}
I need to get the data from the custom signIn page in order to write a user to the sanity database. But these signIn data is only obtained in [...nextauth].js file.
Code:
[...nextauth].js
import NextAuth from 'next-auth'
import GoogleProvider from 'next-auth/providers/google'
export default NextAuth({
// Configure one or more authentication providers
providers: [
GoogleProvider({
clientId: "xxxxxx",
clientSecret: "xxxxx",
}),
// ...add more providers here
],
secret: "something",
pages: {
signIn: '/auth/signin',
},
callbacks: {
async session({ session, token, user }) {
session.user.username = session.user.name
.split(' ')
.join('')
.toLocaleLowerCase()
session.user.uid = token.sub
return session
},
},
})
And these session data can be used inside components using useSession from next-auth.
But while trying to get the data to my custom signIn page, session is undefined.
import { getProviders, signIn as signIntoProvider } from "next-auth/react";
import { sanityClient } from "../../sanity";
import { useSession } from 'next-auth/react';
function signIn({users}) {
const { data: session } = useSession()
const onSubmit = (data) => {
fetch("/api/createUser", {
method: "POST",
body: JSON.stringify(data),
})
.then((resp) => {
console.log(resp);
})
.catch((err) => {
console.log(err);
});
};
const checkIfUserThere = async () => {
let newUser = session.user.email;
for (const data of users) {
if (data.email === newUser) {
return true;
}
}
return false;
};
useEffect(() => {
(async () => {
const userExists = await checkIfUserThere();
if(userExists === false ){
onSubmit(session.user); //write to sanity database
}
})();
}, []);
return (
<>
<button
className="rounded-lg bg-blue-500 p-3 text-white"
onClick={() =>
signIntoProvider("google", { callbackUrl: "/" })
}
>
Sign in with Google
</button>
</>
);
}
The above code is for a custom signIn page.
What is expected :
Once the user clicks the sign-in with the Google button, the session data must be added to the sanity database. But in my case, session here is undefined.
A simple way to do this is to write the logic inside the [...nextAuth].js file.
To solve the task of popularizing a document in Sanity from a Google authentication, you must first establish a connection to your Sanity project. Note that this import comes from the 'npm i #sanity/client' package or 'yarn add #sanity/client' and is not a reference to the configuration located in the sanity.js file. To do this, you can import the #sanity/client library and set up a configuration to connect to your project:
import sanityClient from "#sanity/client";
const config = {
dataset: "DATASET_NAME",
projectId: "PROJECT_ID",
useCdn: 'CDN'
token: "YOUR_TOKEN_SANITY",
};
export const client = sanityClient(config);
After setting up authentication with Google, you must set up a callback to run every time a user authenticates. This callback should look in Sanity to see if the user already exists, and if not, create a new user document in Sanity with the authenticated user's information:
const populateSanityUser = async (user) => {
const sanityUser = await client.fetch(
`*[_type == "users" && email == "${user.email}"]{ //check if the email exists
email
}`
);
if (sanityUser.length > 0) { //if exists
return sanityUser;
} else { //if not, create a new user with Google user session data
try {
await client.create({
_type: "user",
name: user.name,
email: user.email,
urlImage: user.image,
... // another field in your document
});
return user;
} catch (error) {
return error;
}
}
};
export default NextAuth({
...authOptions,
callbacks: {
async signIn(user) {
const isAllowedToSignIn = true; //optional
if (isAllowedToSignIn) {
const sanityUser = await populateSanityUser(user.user);
return sanityUser;
} else {
return false;
}
},
},
});
Important: Make sure that when you pass the user coming from NextAuth callback function you use user.user, as it comes nested with more data.
More information about callbacks in NextAuth here: https://next-auth.js.org/configuration/callbacks
I have created an app that connects to a mongodb cluster and stores user info. The user is then able to log in with Next-Auth functionality. The app was working just fine before deploying to Vercel. On the live site I ran into some Server Config Errors. I refractored my code yet I am still running into a few errors.
I am successfully able to connect to the database for a new user sign up.
import {
connectToDatabase,
hashedPassword,
} from "../../helper/HelperFunctions";
const isEmpty = (value) => value.trim() === "";
const isTenChars = (value) => value.trim().length >= 10;
const emailValidation = (value) => {
const pattern = /^[^ ]+#[^ ]+\.[a-z]{2,3}$/;
if (value.match(pattern)) {
return true;
} else {
return false;
}
};
export default async function handler(req, res) {
if (req.method == "POST") {
let data = req.body;
const { firstName, lastName, email, password, userName } = data;
const firstNameIsValid = !isEmpty(firstName);
const lastNameisValid = !isEmpty(lastName);
const emailIsValid = emailValidation(email);
const passwordisValid = isTenChars(password);
const userNameIsValid = !isEmpty(userName);
let userDataIsValid =
firstNameIsValid &&
lastNameisValid &&
emailIsValid &&
passwordisValid &&
userNameIsValid;
if (!userDataIsValid) {
return;
}
const client = await connectToDatabase();
const db = client.db();
const existingUser = await db.collection("users").findOne({ email: email });
if (existingUser) {
res.status(422).json({ message: "User already exists, please log in!" });
console.log("User already exists, please log in!");
client.close();
return;
}
const protectedPassword = await hashedPassword(password);
await db.collection("users").insertOne({
firstName: firstName,
lastName: lastName,
email: email,
password: protectedPassword,
userName: userName,
});
client.close();
res.status(201).json({ message: "Signed up!" });
} else {
res.status(200).json({ data: req.body });
}
}
Here is my nextauth api route
import NextAuth from "next-auth/next";
import CredentialsProvider from "next-auth/providers/credentials";
// Helper Functions
import {
connectToDatabase,
comparePasswords,
} from "../../../helper/HelperFunctions";
export default NextAuth({
session: { strategy: "jwt" },
providers: [
CredentialsProvider({
async authorize(credentials) {
const client = await connectToDatabase();
const userCollection = client.db().collection("users");
const user = await userCollection.findOne({
email: credentials.email,
});
if (!user) {
client.close();
throw new Error("No user found!");
}
const isValid = await comparePasswords(
credentials.password,
user.password
);
if (!isValid) {
client.close();
throw new Error("Invalid password");
}
client.close();
if (user) {
return {
email: user.email,
};
} else {
return null;
}
},
}),
],
});
Before I deployed my site on Vercel, this was working just fine on localhost. The user should then proceed to a new page if the result of logging in has no errors.
const result = await signIn("credentials", {
redirect: false,
email: form.email,
password: form.password,
});
if (!result.error) {
console.log(true);
router.replace("/suggestions");
} else {
console.log(result.error);
setLoginResult(result.error);
}
If you see CLIENT_FETCH_ERROR make sure you have configured the NEXTAUTH_URL environment variable.
when developing you set it to localhost:3000, now you need to set that to your deployed url.
I have the following code.
I want to implement authentication using MongoDB, mongoose, express using typescript.
I am having a typescript issue. I tried declaring type (maybe incorrectly) for findUser and did not resolve. Any tips?
model.ts
import mongoose, { Schema, Document } from 'mongoose';
import bcrypt from 'bcrypt';
export interface IUser extends Document {
username: string;
password: string;
}
const userSchema: Schema = new Schema({
username: {
type: String,
unique: true,
required: true,
},
password: {
type: String,
required: true,
},
});
// tslint:disable-next-line: only-arrow-functions
userSchema.statics.findUser = async function (username, password) {
const user = await User.findOne({ username });
if (!user) {
return;
}
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) {
return;
}
return user;
};
userSchema.pre<IUser>('save', async function (next) {
const user = this;
if (user.isModified('password')) {
user.password = await bcrypt.hash(user.password, 8);
}
next();
});
const User = mongoose.model<IUser & Document>('User', userSchema);
export default User;
auth.ts (route)
ERROR:Property 'findUser' does not exist on type 'Model<IUser & Document>'.ts(2339)
import express from 'express';
import User from '../models/user-model';
const router = express.Router();
declare module 'express-session' {
// tslint:disable-next-line: interface-name
export interface SessionData {
user: { [key: string]: any };
}
}
router.post('/signin', async (req, res) => {
const { email, password } = req.body;
const user = await User.findUser(email, password);
if (user) {
req.session.user = user._id;
res.json({
message: 'You are successfully login',
auth: true,
});
} else {
res.json({
message: 'Unable to login',
auth: false,
});
}
});
export = router;
You can set a second generic on the mongoose.model() method which describes the model itself.
Here we include all of the properties of Model<IUser> and also add your custom function.
type UserModel = Model<IUser> & {
findUser: (username: string, password: string) => Promise<IUser | undefined>;
}
IUser determines the type for the documents in this model, while UserModel determines the type for the model.
const User = mongoose.model<IUser, UserModel>('User', userSchema);
Now the type for the method is known. user here gets type IUser | undefined;
const user = await User.findUser('joe', 'abcd');
Typescript Playground Link
I am trying to test my API and I am not sure what I am doing wrong. The only error I am getting is cannot post. After some research, I am suspecting something wrong with my controller class.
This is my first real large project and I have created an API similar to this just with mongo but this is my first time using seqealize, and MySQL (with node).
The api/student/register router just won't post, but when I remove the controller and but a function that returns just plain JSON it works, that is why I really do believe it has something to do with my controller class.
contoller/student.controller.js
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
require('dotenv').config();
const secret = process.env.SERCRET_KEY;
const db = require('../models/index.js');
const Student = db.Student;
class StudentContoller {
static registerStudent(req, res) {
try {
let {
first_name,
last_name,
email,
password,
phone,
shirt_size,
grade,
teacher,
} = req.body;
Student.findAll({
where: {
email : email,
is_Archived: false,
}
})
.then(result => {
if (result.length > 0){
res.status(400).json({ message: 'Email is already registerd'});
} else {
let hashPassword = bcrypt.hashSync(password, 10);
let newStudent = {
first_name,
last_name,
email,
password: hashPassword,
phone,
shirt_size,
grade,
teacher,
school_id,
}
Student.Create(newStudent)
.then(data => {
if(data){
res.status(201).json({message: 'Student Created', student: data })
}
})
.catch(err => res.json({error : err.message}));
}
})
} catch (e) {
res.status(500).json({error: 'error caused in regiserted controller'})
}
}
static async login(req, res) {
let { email, password, } = req.body;
await Student.findAll({
where: {
email: email,
is_Archived: false,
}
})
.then(student => {
if(student.length === 0){
res.status(400).json({ message: 'Sorry, account does not exsist'})
} else {
let passwordIsValid = bcrypt.compareSync(req.body.password, student[0].password.trim());
if (passwordIsValid) {
let studentDetails = {
id: student[0].dataValues.id,
first_name: student[0].first_name,
last_name: student[0].last_name,
}
let token = jwt.sign({
student: studentDetails,
}, secret, {
expiresIn: '1d'
});
res.status(200).json({
success: true,
student: studentDetails,
message: 'Login successfull',
token: token,
});
} else {
res.status(401).json({
success: false,
message: 'Login failed',
});
}
}
})
.catch(err => res.status(500).json({error: err.message}));
}
static async updateStudent(req, res) {
try {
const {
first_name,
last_name,
email,
password,
phone,
shirt_size,
grade,
teacher,
} = req.body;
let hashpassword = bcrypt.hashSync(password, 10);
let updateStudent = {
first_name,
last_name,
email,
password : hashpassword,
phone,
shirt_size,
grade,
teacher,
}
Student.update(updateStudent, {
where: {
id: req.params.id
}
})
.then(response => {
res.status(200).json({success: true, message: "Student updated successfully"})
})
.then(err => res.json({err: err.message}));
} catch (e) {
res.status(500).json({ error: e});
}
}
static async archiveStudent(req, res) {
try{
let id = req.params.id
await Student.findAll({
where: {id: id}
})
.then(result => {
if (result.length == 1){
Student.update(
{is_Archived: true},
{ where: {id: id}}
)
}
})
} catch (e) {
res.status(500).json({ error: e});
}
}
}
module.exports = StudentContoller;
student.routs.js
const express = require('express');
const router = express.Router();
const jwt = require('jsonwebtoken');
const checkJWT = require('../middlewares/check-token');
const StudentController = require('../controllers/student.controller');
//
//
router.get('student/login', StudentController.login);
router.post('student/register', checkJWT,StudentController.registerStudent);
module.exports = router;
Sever js
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const morgan = require('morgan');
const helmet = require('helmet');
const app = express();
// Middlewars
app.use(cors()); // Enable Cors
app.use(morgan('dev')); // Enable Logging
app.use(helmet()); // Enables Security Headers
app.use(bodyParser.json()); // Parses requrests of type application/json
app.use(bodyParser.urlencoded({ extended: true})); // Parses request of application/x-www-form-urlencode
//Add database connection
const db = require('./models');
//db.sequelize.sync().then(()=> initial())
// Routing
app.get('/', (req, res)=> res.json({message: "Base API URL"}));
const studnetRoute = require('./routes/student.routes');
app.use('/', studnetRoute);
const PORT = process.env.PORT || 3300;
app.listen(PORT, () => console.log(`Server Running on port ${PORT}`));
you can do like this in your router file .
router.route('student/login')
.get(StudentController.login);
router.route('student/register')
.post(checkJWT, StudentController.registerStudent);