diff --git a/with-golang/.env b/with-golang/.env new file mode 100644 index 0000000..df09d75 --- /dev/null +++ b/with-golang/.env @@ -0,0 +1 @@ +PORT=3001 diff --git a/with-golang/go.mod b/with-golang/go.mod new file mode 100644 index 0000000..48ccc01 --- /dev/null +++ b/with-golang/go.mod @@ -0,0 +1,36 @@ +module gin + +go 1.23.2 + +require ( + github.com/authorizerdev/authorizer-go v0.0.0-20240402105736-0eeef41a29a2 // indirect + github.com/bytedance/sonic v1.11.6 // indirect + github.com/bytedance/sonic/loader v0.1.1 // indirect + github.com/cloudwego/base64x v0.1.4 // indirect + github.com/cloudwego/iasm v0.2.0 // indirect + github.com/gabriel-vasile/mimetype v1.4.3 // indirect + github.com/gin-contrib/cors v1.7.2 // indirect + github.com/gin-contrib/sse v0.1.0 // indirect + github.com/gin-gonic/gin v1.10.0 // indirect + github.com/go-playground/locales v0.14.1 // indirect + github.com/go-playground/universal-translator v0.18.1 // indirect + github.com/go-playground/validator/v10 v10.20.0 // indirect + github.com/goccy/go-json v0.10.2 // indirect + github.com/joho/godotenv v1.5.1 // indirect + github.com/json-iterator/go v1.1.12 // indirect + github.com/klauspost/cpuid/v2 v2.2.7 // indirect + github.com/leodido/go-urn v1.4.0 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect + github.com/pelletier/go-toml/v2 v2.2.2 // indirect + github.com/twitchyliquid64/golang-asm v0.15.1 // indirect + github.com/ugorji/go/codec v1.2.12 // indirect + golang.org/x/arch v0.8.0 // indirect + golang.org/x/crypto v0.23.0 // indirect + golang.org/x/net v0.25.0 // indirect + golang.org/x/sys v0.20.0 // indirect + golang.org/x/text v0.15.0 // indirect + google.golang.org/protobuf v1.34.1 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/with-golang/go.sum b/with-golang/go.sum new file mode 100644 index 0000000..6f19df0 --- /dev/null +++ b/with-golang/go.sum @@ -0,0 +1,85 @@ +github.com/authorizerdev/authorizer-go v0.0.0-20240402105736-0eeef41a29a2 h1:Fb7QvIRVgUY4bzVheAgffz+Qa43t4ujQTMNApjyTfo8= +github.com/authorizerdev/authorizer-go v0.0.0-20240402105736-0eeef41a29a2/go.mod h1:JS47FPlPYXUoppQmyiyxk8pWwxYvw2Hf63Q7jFZzz1k= +github.com/bytedance/sonic v1.11.6 h1:oUp34TzMlL+OY1OUWxHqsdkgC/Zfc85zGqw9siXjrc0= +github.com/bytedance/sonic v1.11.6/go.mod h1:LysEHSvpvDySVdC2f87zGWf6CIKJcAvqab1ZaiQtds4= +github.com/bytedance/sonic/loader v0.1.1 h1:c+e5Pt1k/cy5wMveRDyk2X4B9hF4g7an8N3zCYjJFNM= +github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU= +github.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/0Y= +github.com/cloudwego/base64x v0.1.4/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w= +github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg= +github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0= +github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk= +github.com/gin-contrib/cors v1.7.2 h1:oLDHxdg8W/XDoN/8zamqk/Drgt4oVZDvaV0YmvVICQw= +github.com/gin-contrib/cors v1.7.2/go.mod h1:SUJVARKgQ40dmrzgXEVxj2m7Ig1v1qIboQkPDTQ9t2E= +github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= +github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= +github.com/gin-gonic/gin v1.10.0 h1:nTuyha1TYqgedzytsKYqna+DfLos46nTv2ygFy86HFU= +github.com/gin-gonic/gin v1.10.0/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y= +github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= +github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= +github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= +github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= +github.com/go-playground/validator/v10 v10.20.0 h1:K9ISHbSaI0lyB2eWMPJo+kOS/FBExVwjEviJTixqxL8= +github.com/go-playground/validator/v10 v10.20.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM= +github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU= +github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= +github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= +github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= +github.com/klauspost/cpuid/v2 v2.2.7 h1:ZWSB3igEs+d0qvnxR/ZBzXVmxkgt8DdzP6m9pfuVLDM= +github.com/klauspost/cpuid/v2 v2.2.7/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws= +github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M= +github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= +github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM= +github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= +github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= +github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE= +github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg= +golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= +golang.org/x/arch v0.8.0 h1:3wRIsP3pM4yUptoR96otTUOXI367OS0+c9eeRi9doIc= +golang.org/x/arch v0.8.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys= +golang.org/x/crypto v0.23.0 h1:dIJU/v2J8Mdglj/8rJ6UUOM3Zc9zLZxVZwwxMooUSAI= +golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8= +golang.org/x/net v0.25.0 h1:d/OCCoBEUq33pjydKrGQhw7IlUPI2Oylr+8qLx49kac= +golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM= +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y= +golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/text v0.15.0 h1:h1V/4gjBv8v9cjcR6+AR5+/cIYK5N/WAgiv4xlsEtAk= +golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= +google.golang.org/protobuf v1.34.1 h1:9ddQBjfCyZPOHPUiPxpYESBLc+T8P3E+Vo4IbKZgFWg= +google.golang.org/protobuf v1.34.1/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50= +rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4= diff --git a/with-golang/main.go b/with-golang/main.go new file mode 100644 index 0000000..98d42b0 --- /dev/null +++ b/with-golang/main.go @@ -0,0 +1,133 @@ +package main + +import ( + "log" + "net/http" + "strings" + "github.com/authorizerdev/authorizer-go" + "github.com/gin-gonic/gin" + "github.com/gin-contrib/cors" + "github.com/joho/godotenv" // For loading .env files + "os" +) + +// HealthCheckHandler handles health check requests +func HealthCheckHandler(c *gin.Context) { + c.JSON(http.StatusOK, gin.H{ + "status": "UP", + "message": "Service is running smoothly", + }) +} + +// User struct to represent user data +type User struct { + ID int `json:"id"` + Name string `json:"name"` + Email string `json:"email"` +} + +var users = []User{ + {ID: 1, Name: "Alice", Email: "alice@example.com"}, + {ID: 2, Name: "Bob", Email: "bob@example.com"}, +} + +// GetUsersHandler returns the list of users +func GetUsersHandler(c *gin.Context) { + c.JSON(http.StatusOK, users) +} + +// AddUserHandler adds a new user +func AddUserHandler(c *gin.Context) { + var newUser User + if err := c.ShouldBindJSON(&newUser); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + newUser.ID = len(users) + 1 + users = append(users, newUser) + c.JSON(http.StatusCreated, newUser) +} + +func AuthorizeMiddleware() gin.HandlerFunc { + return func(c *gin.Context) { + // Optional: add conditions here for open routes that don't require authentication + + authHeader := c.Request.Header.Get("Authorization") + tokenSplit := strings.Split(authHeader, " ") + log.Println(tokenSplit[1]) + + // Replace with your Authorizer credentials + clientID := "882720ca-81cc-4925-9d33-41035d6c758f" + authorizerURL := "http://localhost:8080" + redirectURL := "" + + defaultHeaders := map[string]string{} + authorizerClient, err := authorizer.NewAuthorizerClient(clientID, authorizerURL, redirectURL, defaultHeaders) + if err != nil { + log.Println(`authorizerClient have problem`) + // Unauthorized response if client initialization fails + c.AbortWithStatusJSON(http.StatusUnauthorized, "unauthorized") + return + } + + if len(tokenSplit) < 2 || tokenSplit[1] == "" { + log.Println(`token have problem`) + // Unauthorized response for invalid token format + c.AbortWithStatusJSON(http.StatusUnauthorized, "unauthorized") + return + } + + // Validate the token + res, err := authorizerClient.ValidateJWTToken(&authorizer.ValidateJWTTokenInput{ + TokenType: authorizer.TokenTypeAccessToken, + Token: tokenSplit[1], + }) + if err != nil || !res.IsValid { + log.Println(`validation have problem`) + // Unauthorized response for invalid token + c.AbortWithStatusJSON(http.StatusUnauthorized, "unauthorized cant aboe to find") + return + } + + // Proceed with the request if the token is valid + c.Next() + } +} + + +// Main function to set up and run the server +func main() { + // Load environment variables + if err := godotenv.Load(); err != nil { + log.Println("No .env file found") + } + + port := os.Getenv("PORT") + if port == "" { + port = "8080" // Default port if not specified + } + + r := gin.Default() + r.Use(cors.New(cors.Config{ + AllowOrigins: []string{"http://localhost:3000"}, + AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"}, + AllowHeaders: []string{"Origin", "Content-Type", "Accept", "Authorization"}, + ExposeHeaders: []string{"Content-Length"}, + AllowCredentials: true, + })) + + r.Use(cors.Default()) + r.Use(AuthorizeMiddleware()) + + + // Define routes + r.GET("/health", HealthCheckHandler) + r.GET("/users", GetUsersHandler) + r.POST("/users", AddUserHandler) + + // Start the server + log.Printf("Starting server on port %s", port) + if err := r.Run(":" + port); err != nil { + log.Fatalf("Could not start server: %v", err) + } +} diff --git a/with-nextjs15(backend integration)/.gitignore b/with-nextjs15(backend integration)/.gitignore new file mode 100644 index 0000000..5ef6a52 --- /dev/null +++ b/with-nextjs15(backend integration)/.gitignore @@ -0,0 +1,41 @@ +# 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 diff --git a/with-nextjs15(backend integration)/README.md b/with-nextjs15(backend integration)/README.md new file mode 100644 index 0000000..e215bc4 --- /dev/null +++ b/with-nextjs15(backend integration)/README.md @@ -0,0 +1,36 @@ +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.tsx`. The page auto-updates as you edit the file. + +This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel. + +## 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. diff --git a/with-nextjs15(backend integration)/bun.lockb b/with-nextjs15(backend integration)/bun.lockb new file mode 100644 index 0000000..ca0b42e Binary files /dev/null and b/with-nextjs15(backend integration)/bun.lockb differ diff --git a/with-nextjs15(backend integration)/eslint.config.mjs b/with-nextjs15(backend integration)/eslint.config.mjs new file mode 100644 index 0000000..c85fb67 --- /dev/null +++ b/with-nextjs15(backend integration)/eslint.config.mjs @@ -0,0 +1,16 @@ +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", "next/typescript"), +]; + +export default eslintConfig; diff --git a/with-nextjs15(backend integration)/next.config.ts b/with-nextjs15(backend integration)/next.config.ts new file mode 100644 index 0000000..d33429e --- /dev/null +++ b/with-nextjs15(backend integration)/next.config.ts @@ -0,0 +1,14 @@ +import type { NextConfig } from 'next'; + +const nextConfig: NextConfig = { + async rewrites() { + return [ + { + source: '/api/:path*', // Matches any path starting with /api/ + destination: 'http://localhost:3001/:path*', // Proxy to your backend + }, + ]; + }, +}; + +export default nextConfig; diff --git a/with-nextjs15(backend integration)/package.json b/with-nextjs15(backend integration)/package.json new file mode 100644 index 0000000..9864f71 --- /dev/null +++ b/with-nextjs15(backend integration)/package.json @@ -0,0 +1,28 @@ +{ + "name": "authorizer_nextjs15", + "version": "0.1.0", + "private": true, + "scripts": { + "dev": "next dev --turbopack", + "build": "next build", + "start": "next start", + "lint": "next lint" + }, + "dependencies": { + "@authorizerdev/authorizer-react": "^1.3.3", + "next": "15.1.2", + "react": "^19.0.0", + "react-dom": "^19.0.0" + }, + "devDependencies": { + "typescript": "^5", + "@types/node": "^20", + "@types/react": "^19", + "@types/react-dom": "^19", + "postcss": "^8", + "tailwindcss": "^3.4.1", + "eslint": "^9", + "eslint-config-next": "15.1.2", + "@eslint/eslintrc": "^3" + } +} diff --git a/with-nextjs15(backend integration)/postcss.config.mjs b/with-nextjs15(backend integration)/postcss.config.mjs new file mode 100644 index 0000000..1a69fd2 --- /dev/null +++ b/with-nextjs15(backend integration)/postcss.config.mjs @@ -0,0 +1,8 @@ +/** @type {import('postcss-load-config').Config} */ +const config = { + plugins: { + tailwindcss: {}, + }, +}; + +export default config; diff --git a/with-nextjs15(backend integration)/public/file.svg b/with-nextjs15(backend integration)/public/file.svg new file mode 100644 index 0000000..004145c --- /dev/null +++ b/with-nextjs15(backend integration)/public/file.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/with-nextjs15(backend integration)/public/globe.svg b/with-nextjs15(backend integration)/public/globe.svg new file mode 100644 index 0000000..567f17b --- /dev/null +++ b/with-nextjs15(backend integration)/public/globe.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/with-nextjs15(backend integration)/public/next.svg b/with-nextjs15(backend integration)/public/next.svg new file mode 100644 index 0000000..5174b28 --- /dev/null +++ b/with-nextjs15(backend integration)/public/next.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/with-nextjs15(backend integration)/public/vercel.svg b/with-nextjs15(backend integration)/public/vercel.svg new file mode 100644 index 0000000..7705396 --- /dev/null +++ b/with-nextjs15(backend integration)/public/vercel.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/with-nextjs15(backend integration)/public/window.svg b/with-nextjs15(backend integration)/public/window.svg new file mode 100644 index 0000000..b2b2a44 --- /dev/null +++ b/with-nextjs15(backend integration)/public/window.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/with-nextjs15(backend integration)/src/app/(main)/(auth)/check_api/page.tsx b/with-nextjs15(backend integration)/src/app/(main)/(auth)/check_api/page.tsx new file mode 100644 index 0000000..fb45151 --- /dev/null +++ b/with-nextjs15(backend integration)/src/app/(main)/(auth)/check_api/page.tsx @@ -0,0 +1,14 @@ +import { validateUser } from "@/lib/authorizer" + + +// const fetchUserData = async () => { +// return await validateUser(); +// }; + + +export default async function Check_api() { + const result = await validateUser(); + console.log("result", result); + return result ?
{JSON.stringify(result, null, 2)}
: null; + +} \ No newline at end of file diff --git a/with-nextjs15(backend integration)/src/app/(main)/(auth)/login/page.tsx b/with-nextjs15(backend integration)/src/app/(main)/(auth)/login/page.tsx new file mode 100644 index 0000000..d80f286 --- /dev/null +++ b/with-nextjs15(backend integration)/src/app/(main)/(auth)/login/page.tsx @@ -0,0 +1,16 @@ +'use client'; + +import { useEffect } from 'react'; +import { Authorizer, useAuthorizer } from '@authorizerdev/authorizer-react'; +import { useRouter } from 'next/navigation'; + +export default function Login() { + const { token } = useAuthorizer(); + const router = useRouter(); + useEffect(() => { + if (token) { + router.push('/'); + } + }, [token]); + return ; +} \ No newline at end of file diff --git a/with-nextjs15(backend integration)/src/app/(main)/(auth)/profile/page.tsx b/with-nextjs15(backend integration)/src/app/(main)/(auth)/profile/page.tsx new file mode 100644 index 0000000..671424a --- /dev/null +++ b/with-nextjs15(backend integration)/src/app/(main)/(auth)/profile/page.tsx @@ -0,0 +1,19 @@ +import { Authorizer } from '@authorizerdev/authorizer-js'; +import authorizerConfig from '../../../../lib/config/authorizer-config'; +import { cookies } from 'next/headers'; + +const getUserData = async () => { + const nextCookies = cookies(); + const tokenCookie = (await nextCookies).get('authorizer-client-next'); + const token = tokenCookie ? tokenCookie.value : null; + const authorizerRef = new Authorizer(authorizerConfig); + + return authorizerRef.getProfile({ + Authorization: `Bearer ${token}`, + }); +}; + +export default async function Profile() { + const user = await getUserData(); + return user ?
{JSON.stringify(user, null, 2)}
: null; +} \ No newline at end of file diff --git a/with-nextjs15(backend integration)/src/app/(main)/page.tsx b/with-nextjs15(backend integration)/src/app/(main)/page.tsx new file mode 100644 index 0000000..adbb0a9 --- /dev/null +++ b/with-nextjs15(backend integration)/src/app/(main)/page.tsx @@ -0,0 +1,27 @@ + +import Link from 'next/link'; + +const HomePage = () => { + return ( +
+
+
+

+ Authorizer Homepage!!! +

+
+

+ Authorizer is a simple, secure, and scalable authentication and + authorization service that allows you to add authentication to your + applications and APIs in just a few minutes. +

+ + {/* */} + +
+ +
+ ); +}; + +export default HomePage; \ No newline at end of file diff --git a/with-nextjs15(backend integration)/src/app/api/auth/logout/route.ts b/with-nextjs15(backend integration)/src/app/api/auth/logout/route.ts new file mode 100644 index 0000000..b83f4c7 --- /dev/null +++ b/with-nextjs15(backend integration)/src/app/api/auth/logout/route.ts @@ -0,0 +1,16 @@ +import type { AuthToken } from '@authorizerdev/authorizer-js'; +import { cookies } from 'next/headers'; +import { NextRequest, NextResponse } from 'next/server'; + +export const POST = async (req: NextRequest, res: Response) => { + (await cookies()).set('authorizer-client-next', '', { + secure: true, + expires: -1, + httpOnly: true, + path: '/', + }); + return NextResponse.json( + { message: 'Logged out successfully' }, + { status: 200 }, + ); +}; \ No newline at end of file diff --git a/with-nextjs15(backend integration)/src/app/api/auth/session/route.ts b/with-nextjs15(backend integration)/src/app/api/auth/session/route.ts new file mode 100644 index 0000000..0b15128 --- /dev/null +++ b/with-nextjs15(backend integration)/src/app/api/auth/session/route.ts @@ -0,0 +1,23 @@ +import type { AuthToken } from '@authorizerdev/authorizer-js'; +import { NextRequest, NextResponse } from 'next/server'; +import { cookies } from 'next/headers'; + +export const POST = async (req: NextRequest, res: Response) => { + const data = (await req.json()) as AuthToken | null; + const accessToken = data?.access_token; + const expiresAt = data?.expires_in; + + if (!accessToken || !expiresAt) { + return NextResponse.json({ message: 'Unauthorized' }, { status: 401 }); + } else { + (await cookies()).set('authorizer-client-next', `${accessToken}`, { + secure: true, + httpOnly: true, + path: '/', + }); + return NextResponse.json( + { message: 'Session created successfully' }, + { status: 200 }, + ); + } +}; \ No newline at end of file diff --git a/with-nextjs15(backend integration)/src/app/favicon.ico b/with-nextjs15(backend integration)/src/app/favicon.ico new file mode 100644 index 0000000..718d6fe Binary files /dev/null and b/with-nextjs15(backend integration)/src/app/favicon.ico differ diff --git a/with-nextjs15(backend integration)/src/app/globals.css b/with-nextjs15(backend integration)/src/app/globals.css new file mode 100644 index 0000000..e69de29 diff --git a/with-nextjs15(backend integration)/src/app/layout.tsx b/with-nextjs15(backend integration)/src/app/layout.tsx new file mode 100644 index 0000000..69a4975 --- /dev/null +++ b/with-nextjs15(backend integration)/src/app/layout.tsx @@ -0,0 +1,31 @@ +import type { Metadata } from 'next'; +// import { Open_Sans } from 'next/font/google'; +import './globals.css'; +import { AuthProvider } from '@/components/ClientProviders'; +import Navbar from '@/components/Dashboard/Navbar/nav'; + +// const openSans = Open_Sans({ subsets: ['latin'] }); + +export const metadata: Metadata = { + title: 'Authorizer!', + description: + 'Authorizer is a simple, secure, and scalable authentication and authorization service that allows you to add authentication to your applications and APIs in just a few minutes.', +}; + +export default async function RootLayout({ + children, +}: { + children: React.ReactNode; +}) { + + return ( + + + + {/* Pass token as a prop */} + {children} + + + + ); +} \ No newline at end of file diff --git a/with-nextjs15(backend integration)/src/components/ClientProviders.tsx b/with-nextjs15(backend integration)/src/components/ClientProviders.tsx new file mode 100644 index 0000000..0364a67 --- /dev/null +++ b/with-nextjs15(backend integration)/src/components/ClientProviders.tsx @@ -0,0 +1,44 @@ +'use client'; + +import config from '@/lib/config/authorizer-config'; +import type { AuthToken } from '@authorizerdev/authorizer-js'; +import { AuthorizerProvider } from '@authorizerdev/authorizer-react'; +import { useRouter } from 'next/navigation'; +import { ReactNode, useEffect } from 'react'; + + +const onStateChangeCallback = async ({ + token, +}: { + token: AuthToken | null; +}) => { + if (!token) return; + + await fetch('/api/auth/session', { + method: 'POST', + body: JSON.stringify(token), + cache: 'no-store', + }); +}; + +export const AuthProvider = ({ children }: { children: ReactNode }) => { + const router = useRouter(); + +// useEffect(() => { +// const hasJoinToken = sessionStorage.getItem('join'); +// if (hasJoinToken) { +// const inviteUrl = '/join?token=' + hasJoinToken; +// router.push(inviteUrl); +// } +// }, []); + + return ( + + {children} + + ); +}; + diff --git a/with-nextjs15(backend integration)/src/components/Dashboard/Navbar/nav.tsx b/with-nextjs15(backend integration)/src/components/Dashboard/Navbar/nav.tsx new file mode 100644 index 0000000..eb3f87c --- /dev/null +++ b/with-nextjs15(backend integration)/src/components/Dashboard/Navbar/nav.tsx @@ -0,0 +1,63 @@ +'use client' + +import { useAuthorizer } from '@authorizerdev/authorizer-react'; +import Link from 'next/link'; +import { useRouter } from 'next/navigation'; + + + +export default function Nav() { + const { user, setUser, setToken, authorizerRef } = useAuthorizer(); + const router = useRouter(); + const onLogout = async () => { + setUser(null); + setToken(null); + await authorizerRef.logout(); + await fetch('/api/auth/logout', { + method: 'POST', + }); + router.push('/'); + }; + + const checkApi = async () => {}; + return ( + + ); +} \ No newline at end of file diff --git a/with-nextjs15(backend integration)/src/lib/authorizer.ts b/with-nextjs15(backend integration)/src/lib/authorizer.ts new file mode 100644 index 0000000..6200ea0 --- /dev/null +++ b/with-nextjs15(backend integration)/src/lib/authorizer.ts @@ -0,0 +1,22 @@ +import { cookies } from 'next/headers'; + +export const generateAuthHeaders = async () => { + const nextCookies = await cookies(); + const token = nextCookies.get('authorizer-client-next')?.value; + const headers = new Headers(); + headers.append('Content-Type', 'application/json'); + headers.append('Authorization', `Bearer ${token}`); + return headers; +}; + +export const validateUser = async () => { + const headers = await generateAuthHeaders(); + console.log(headers); + const response = await fetch('http://localhost:3001/health', { + headers, + }); + + if (response.ok) return response.json(); + return false; +}; + diff --git a/with-nextjs15(backend integration)/src/lib/config/authorizer-config.ts b/with-nextjs15(backend integration)/src/lib/config/authorizer-config.ts new file mode 100644 index 0000000..2809d18 --- /dev/null +++ b/with-nextjs15(backend integration)/src/lib/config/authorizer-config.ts @@ -0,0 +1,7 @@ +const config = { + authorizerURL: 'http://localhost:8080', + redirectURL: 'http://localhost:3000', + clientID: '882720ca-81cc-4925-9d33-41035d6c758f', + }; + + export default config; \ No newline at end of file diff --git a/with-nextjs15(backend integration)/src/middleware.ts b/with-nextjs15(backend integration)/src/middleware.ts new file mode 100644 index 0000000..25cf51c --- /dev/null +++ b/with-nextjs15(backend integration)/src/middleware.ts @@ -0,0 +1,36 @@ +// src/middleware.ts +import { NextResponse } from 'next/server'; +import type { NextRequest } from 'next/server'; + +export function middleware(request: NextRequest) { + const token = request.cookies.get('authorizer-client-next'); + console.log('Token:', token); + + // Define protected routes + const protectedRoutes = ['/profile']; + const isProtectedRoute = protectedRoutes.some(route => + request.nextUrl.pathname.startsWith(route) + ); + + // If no token exists for protected routes, redirect to login + if (isProtectedRoute && !token) { + return NextResponse.redirect(new URL('/login', request.url)); + } + + // If logged in and trying to access login, redirect to home + if (request.nextUrl.pathname === '/login' && token) { + return NextResponse.redirect(new URL('/', request.url)); + } + + return NextResponse.next(); +} + +export const config = { + matcher: [ + // Skip Next.js internals and all static files, unless found in search params + '/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)', + // Always run for API routes + '/(api|trpc)(.*)', + ], + } + \ No newline at end of file diff --git a/with-nextjs15(backend integration)/tailwind.config.ts b/with-nextjs15(backend integration)/tailwind.config.ts new file mode 100644 index 0000000..109807b --- /dev/null +++ b/with-nextjs15(backend integration)/tailwind.config.ts @@ -0,0 +1,18 @@ +import type { Config } from "tailwindcss"; + +export default { + content: [ + "./src/pages/**/*.{js,ts,jsx,tsx,mdx}", + "./src/components/**/*.{js,ts,jsx,tsx,mdx}", + "./src/app/**/*.{js,ts,jsx,tsx,mdx}", + ], + theme: { + extend: { + colors: { + background: "var(--background)", + foreground: "var(--foreground)", + }, + }, + }, + plugins: [], +} satisfies Config; diff --git a/with-nextjs15(backend integration)/tsconfig.json b/with-nextjs15(backend integration)/tsconfig.json new file mode 100644 index 0000000..c133409 --- /dev/null +++ b/with-nextjs15(backend integration)/tsconfig.json @@ -0,0 +1,27 @@ +{ + "compilerOptions": { + "target": "ES2017", + "lib": ["dom", "dom.iterable", "esnext"], + "allowJs": true, + "skipLibCheck": true, + "strict": true, + "noEmit": true, + "esModuleInterop": true, + "module": "esnext", + "moduleResolution": "bundler", + "resolveJsonModule": true, + "isolatedModules": true, + "jsx": "preserve", + "incremental": true, + "plugins": [ + { + "name": "next" + } + ], + "paths": { + "@/*": ["./src/*"] + } + }, + "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"], + "exclude": ["node_modules"] +}