Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions nextjs@latest-auth-withouterrors/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"extends": "next/core-web-vitals"
}
32 changes: 32 additions & 0 deletions nextjs@latest-auth-withouterrors/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.js

# testing
/coverage

# next.js
/.next/
/out/

# production
/build

# misc
.DS_Store
*.pem

# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*

# local env files
.env*.local

# vercel
.vercel
4 changes: 4 additions & 0 deletions nextjs@latest-auth-withouterrors/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
after research and fighting with the code, there is important things to know :
middleware should be outisde pages
jsonwebtoken is not woking with nextjs middleware
we will use jose package insted of jsonwebtoken
26 changes: 26 additions & 0 deletions nextjs@latest-auth-withouterrors/middleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { NextResponse } from "next/server";
import * as jose from "jose";
export default async function middleware(request) {
const authToken = request.cookies.get("token_name"); // get our cookie
if (request.nextUrl.pathname.includes("/dashboard")) {
if (authToken === undefined) {
return NextResponse.redirect(new URL("/login", request.url));
}
try {
const { payload: DATA } = await jose.jwtVerify(
authToken,
new TextEncoder().encode(`${process.env.SECRET_KEY_JWT}`)
);
if (!DATA) {
return NextResponse.redirect(new URL("/login", request.url));
}
return NextResponse.next();
} catch (error) {
console.log(error);
}
}
return NextResponse.next();
}
export const config = {
matcher: "/dashboard/:path*",
};
7 changes: 7 additions & 0 deletions nextjs@latest-auth-withouterrors/next.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
swcMinify: true,
}

module.exports = nextConfig
25 changes: 25 additions & 0 deletions nextjs@latest-auth-withouterrors/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"name": "nextjs-auth-withouterrors",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"axios": "^0.27.2",
"cookie": "^0.5.0",
"jose": "^4.8.3",
"next": "12.2.2",
"react": "18.2.0",
"react-dom": "18.2.0",
"react-icons": "^4.4.0",
"sass": "^1.53.0"
},
"devDependencies": {
"eslint": "8.20.0",
"eslint-config-next": "12.2.2"
}
}
7 changes: 7 additions & 0 deletions nextjs@latest-auth-withouterrors/pages/_app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import '../styles/globals.scss'

function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}

export default MyApp
33 changes: 33 additions & 0 deletions nextjs@latest-auth-withouterrors/pages/api/login.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import { serialize } from "cookie";
import * as jose from "jose";
export default async function SignIn(req, res) {
const { method } = req;
switch (method) {
case "POST":
try {
const { email, password } = req.body;
if (!email || !password) {
return res.status(400).json("please fill up all fields");
}
const token = await new jose.SignJWT({
userId: `ayoubwazane`,
role: `admin`,
email: `ayoubwazane306@gmail.com`,
})
.setProtectedHeader({ alg: "HS256" })
.setIssuedAt()
.setExpirationTime("14d")
.sign(new TextEncoder().encode(`${process.env.SECRET_KEY_JWT}`));
const serialised = serialize("token_name", token, {
httpOnly: true,
secure: process.env.NODE_ENV !== "development",
sameSite: "strict",
maxAge: 60 * 60 * 24 * 2, //valid for two weaks
path: "/",
});
res.setHeader("Set-Cookie", serialised);
return res.status(202).json("user signed in successfully...");
} catch (error) {}
}
}
1 change: 1 addition & 0 deletions nextjs@latest-auth-withouterrors/pages/api/signup.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
const SignUp = async (req, res) => {};
13 changes: 13 additions & 0 deletions nextjs@latest-auth-withouterrors/pages/dashboard/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import React from "react";

function Dashboard() {
return (
<div>
<div>
<h1>DASHBOARD</h1>
</div>
</div>
);
}

export default Dashboard;
9 changes: 9 additions & 0 deletions nextjs@latest-auth-withouterrors/pages/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import styles from "../styles/Home.module.scss";

export default function Home() {
return (
<div className={styles.container}>
<h1>fixing nextjs latest version errors with middleware and jwttoken</h1>
</div>
);
}
102 changes: 102 additions & 0 deletions nextjs@latest-auth-withouterrors/pages/login.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
import React, { useState } from "react";
import { FaRegEyeSlash } from "react-icons/fa";
import { GiBleedingEye } from "react-icons/gi";
import styles from "../styles/Home.module.scss";
import axios from "axios";
function Login() {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [showPassword, setShowPassword] = useState(false);
const [success, setSuccess] = useState("");
const [error, setError] = useState("");
const handlePasswordShowing = () => {
setShowPassword(!showPassword);
};
const handleInputs = (e, arg) => {
arg(e.target.value);
};
const onSubmitForm = (e) => {
e.preventDefault();
const data = {
email: email,
password: password,
};
return axios
.post("api/login", data)
.then((response) => {
setSuccess(response.data);
console.log(response.data);
})
.catch((err) => setError(err.response.data));
};
return (
<div className={styles._login_compo}>
<div className={styles._login_compo_display_error}>
{error.length <= 0 ? null : <h4>{error}</h4>}
</div>
<div className={styles._login_compo_display_success}>
{success.length <= 0 ? null : <h4>{success}</h4>}
</div>
<div className={styles._login}>
<div className={styles._login_form_handler}>
<form onSubmit={onSubmitForm}>
<div>
<img
src="/Fingerprint.svg"
width="200"
height="200"
alt="pneumatique app login"
title="pneumatique app login"
/>
</div>
<div>
<h1>C.T.P.D</h1>
</div>
<div>
<input
type="email"
name="email"
value={email}
onChange={(e) => {
handleInputs(e, setEmail);
}}
placeholder="email"
/>
</div>
<div className={styles._login_form_handler_input_withEye}>
<input
type={showPassword ? "text" : "password"}
name="Mot de passe"
value={password}
onChange={(e) => {
handleInputs(e, setPassword);
}}
placeholder="Mot de passe"
/>
{showPassword ? (
<span onClick={handlePasswordShowing}>
<GiBleedingEye color="#fff" size={20} />
</span>
) : (
<span
className={
styles._login_form_handler_input_withEye_FaRegEyeSlash
}
onClick={handlePasswordShowing}
>
<FaRegEyeSlash color="#fff" size={20} />
</span>
)}
</div>
<div>
<button>connexion</button>
</div>
</form>
</div>
<div className={styles._login_backgroundImage}></div>
</div>
</div>
);
}

export default Login;
1 change: 1 addition & 0 deletions nextjs@latest-auth-withouterrors/public/Fingerprint.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added nextjs@latest-auth-withouterrors/public/car.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file not shown.
4 changes: 4 additions & 0 deletions nextjs@latest-auth-withouterrors/public/vercel.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
28 changes: 28 additions & 0 deletions nextjs@latest-auth-withouterrors/styles/Home.module.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
$c: center;
$f: flex;
$sp: space-around;
$sv: space-evenly;
$sb: space-between;
$cl: column;
$per: 100%;
$vh: 100vh;
$perhelf: 50%;
$b: bold;
$n: none;
$rgb: rgb(0, 0, 0);
$favColor: #3f3b53;
$light: rgb(14, 164, 190);
$BgBody: #22202e;
$re: relative;
$ab: absolute;
$po: "Poppins", sans-serif;
$ro: "Roboto", sans-serif;
$p: pointer;
$tr: transparent;
$cv: cover;
$con: contain;
$h: hidden;
$padd: 20px 0 20px 0;
$color: #2ce497;

@import "./Login.module";
Loading