Commit 83b45ccb authored by Marco Andrade's avatar Marco Andrade

Initial commit

parents
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions
# 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*
# env files (can opt-in for committing if needed)
.env*
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts
This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app).
## Getting Started
First, run the development server:
```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
You can start editing the page by modifying `app/page.js`. The page auto-updates as you edit the file.
## Learn More
To learn more about Next.js, take a look at the following resources:
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!
## Deploy on Vercel
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.
import { createCookie } from "@/actions/handleCookie"
import NextAuth from "next-auth"
import Credentials from "next-auth/providers/credentials"
export const { handlers, signIn, signOut, auth } = NextAuth({
providers: [
Credentials({
credentials: {
credencial: {},
senha: {}
},
authorize: async (credentials) => {
let response = await fetch("https://frotas-api.app.fslab.dev/login", {
method: 'POST',
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
credencial: credentials.credencial,
senha: credentials.senha
})
})
let data = await response.json()
if (!data.error) {
// TODO: criar o arquivo handleCookie => cookie http only
await createCookie("access_token", data.data.token, data.data.payload.exp);
return {
...data.data.payload
}
}
return null
}
})
],
})
\ No newline at end of file
import { dirname } from "path";
import { fileURLToPath } from "url";
import { FlatCompat } from "@eslint/eslintrc";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const compat = new FlatCompat({
baseDirectory: __dirname,
});
const eslintConfig = [...compat.extends("next/core-web-vitals")];
export default eslintConfig;
{
"compilerOptions": {
"paths": {
"@/*": ["./src/*"]
}
}
}
/** @type {import('next').NextConfig} */
const nextConfig = {};
export default nextConfig;
This diff is collapsed.
{
"name": "intro-auth",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"next": "15.1.6",
"next-auth": "^5.0.0-beta.25",
"react": "^19.0.0",
"react-dom": "^19.0.0"
},
"devDependencies": {
"@eslint/eslintrc": "^3",
"eslint": "^9",
"eslint-config-next": "15.1.6",
"postcss": "^8",
"tailwindcss": "^3.4.1"
}
}
/** @type {import('postcss-load-config').Config} */
const config = {
plugins: {
tailwindcss: {},
},
};
export default config;
"use server";
import { cookies } from "next/headers";
// export function getCookie() { ... }
export const getCookie = async (name) => {
const cookieStore = await cookies()
const data = cookieStore.get(name)
return data?.value
}
export const createCookie = async (name, data, expires) => {
const cookieStore = await cookies()
cookieStore.set(name, data, {
httpOnly: true,
secure: true,
expires: new Date(expires * 1000),
sameSite: "strict",
path: "/"
})
}
export const deleteCookie = async (name) => {
const cookieStore = await cookies()
const deletedCookie = cookieStore.delete(name)
return deletedCookie
}
\ No newline at end of file
"use client"
import { ApplicationContext } from "@/context/ApplicationContext"
import { signOut } from "next-auth/react"
import { useContext } from "react"
export default function InicioPage(){
// capturar o token que está armazenado no cookie http only
const { token } = useContext(ApplicationContext)
return(
<>
<h1>Página logada</h1>
<div className="border border-red-500 p-2 m-2">
{ token }
</div>
<button onClick={async () => {
await signOut({
redirectTo: "/login"
})
}}>Logout</button>
</>
)
}
\ No newline at end of file
import { redirect } from "next/navigation";
import { auth } from "../../../auth";
import { ApplicationProvider } from "@/context/ApplicationContext";
import { getCookie } from "@/actions/handleCookie";
export default async function AuthLayout({ children }) {
const session = await auth()
// Capturar o token
const token = await getCookie("access_token")
if (!session) {
redirect("/login")
}
return (
<ApplicationProvider token={token}>
<>{children}</>
</ApplicationProvider>
)
}
\ No newline at end of file
import { redirect } from "next/navigation";
import { auth } from "../../../auth";
export default async function NoAuthLayout({ children }) {
const session = await auth()
if (session) {
redirect("/inicio")
}
return <>{children}</>
}
\ No newline at end of file
"use client"
import { useState } from "react"
import { signIn } from "next-auth/react"
import { useRouter } from "next/navigation"
export default function LoginPage(){
const router = useRouter()
const [credencial, setCredencial] = useState("")
const [senha, setSenha] = useState("")
async function login(e) {
e.preventDefault()
const response = await signIn("credentials", {
credencial: credencial,
senha: senha,
redirect: false
})
if (response.ok && !response.error) {
router.replace("/inicio")
console.log(response)
} else {
alert("Login ou senha inválidos")
console.log(response)
}
}
return(
<>
<h1>Login</h1>
<form onSubmit={login}>
<div>
<label htmlFor="credencial">Credencial</label>
<input
className="border border-black"
type="text"
id="credencial"
value={credencial}
onChange={e => setCredencial(e.target.value)} />
</div>
<div>
<label htmlFor="senha">Senha</label>
<input
className="border border-black"
type="text"
id="senha"
value={senha}
onChange={e => setSenha(e.target.value)} />
</div>
<div>
<input
className="border border-black bg-blue-600 text-white"
type="submit"
value="Login" />
</div>
</form>
</>
)
}
\ No newline at end of file
import { handlers } from "../../../../../auth" // Referring to the auth.ts we just created
export const { GET, POST } = handlers
\ No newline at end of file
@tailwind base;
@tailwind components;
@tailwind utilities;
import "./globals.css";
import SessionAuthProvider from "@/providers/sessionProvider";
export const metadata = {
title: "Create Next App",
description: "Generated by create next app",
};
export default function RootLayout({ children }) {
return (
<html lang="pt-br">
<SessionAuthProvider>
<body>
{children}
</body>
</SessionAuthProvider>
</html>
);
}
export default function Home() {
return (
<main>
<div>Hello world!</div>
</main>
);
}
"use client"
import { createContext, useState } from "react"
export const ApplicationContext = createContext({})
export function ApplicationProvider({ token, children }){
const [tokenState, setTokenState] = useState(token)
return(
<ApplicationContext
value={{
token: tokenState
}}
>
{ children }
</ApplicationContext>
)
}
\ No newline at end of file
import { SessionProvider } from "next-auth/react"
export default function SessionAuthProvider({ children }) {
return(
<SessionProvider>
{ children }
</SessionProvider>
)
}
\ No newline at end of file
/** @type {import('tailwindcss').Config} */
export default {
content: ["./src/app/**/*.{js,ts,jsx,tsx,mdx}"],
theme: {},
plugins: [],
};
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment