integrated auth plugin

This commit is contained in:
anthdm 2024-06-16 11:18:34 +02:00
parent 52b39899dc
commit f28da98d27
19 changed files with 277 additions and 26 deletions

View file

@ -20,4 +20,9 @@ MIGRATION_DIR = app/db/migrations
# least 32 bytes long. # least 32 bytes long.
# NOTE: You might want to change this secret when using # NOTE: You might want to change this secret when using
# your app in production. # your app in production.
APP_SECRET = {{app_secret}} SUPERKIT_SECRET = {{app_secret}}
# Authentication Plugin
SUPERKIT_AUTH_REDIRECT_AFTER_LOGIN = /profile
SUPERKIT_AUTH_SESSION_EXPIRY_IN_HOURS = 48
SUPERKIT_AUTH_SKIP_VERIFY = true

View file

@ -4,3 +4,4 @@ bin
node_modules node_modules
tmp tmp
.env .env
app_db

View file

@ -1,4 +1,4 @@
package app package db
import ( import (
"log" "log"
@ -8,12 +8,16 @@ import (
"github.com/anthdm/gothkit/kit" "github.com/anthdm/gothkit/kit"
_ "github.com/mattn/go-sqlite3" _ "github.com/mattn/go-sqlite3"
"github.com/uptrace/bun" "github.com/uptrace/bun"
"github.com/uptrace/bun/dialect/sqlitedialect" "github.com/uptrace/bun/dialect/sqlitedialect"
"github.com/uptrace/bun/extra/bundebug" "github.com/uptrace/bun/extra/bundebug"
) )
var DB *bun.DB // I could not came up with a better naming for this.
// Ideally, app should export a global variable called "DB"
// but this will cause imports cycles for plugins.
var Query *bun.DB
func init() { func init() {
config := db.Config{ config := db.Config{
@ -27,8 +31,8 @@ func init() {
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
DB = bun.NewDB(db, sqlitedialect.New()) Query = bun.NewDB(db, sqlitedialect.New())
if kit.IsDevelopment() { if kit.IsDevelopment() {
DB.AddQueryHook(bundebug.NewQueryHook(bundebug.WithVerbose(true))) Query.AddQueryHook(bundebug.NewQueryHook(bundebug.WithVerbose(true)))
} }
} }

View file

@ -0,0 +1,14 @@
-- +goose Up
create table if not exists users(
id integer primary key,
email text unique not null,
password_hash text not null,
first_name text not null,
last_name text not null,
email_verified_at timestamp with time zone,
created_at timestamp with time zone not null,
updated_at timestamp with time zone not null
);
-- +goose Down
drop table if exists users;

View file

@ -0,0 +1,14 @@
-- +goose Up
create table if not exists sessions(
id integer primary key,
token string not null,
user_id integer not null references users,
ip_address text,
user_agent text,
expires_at timestamp with time zone not null,
last_login_at timestamp with time zone,
created_at timestamp with time zone not null
);
-- +goose Down
drop table if exists sessions;

View file

@ -1,13 +1,11 @@
package handlers package handlers
import ( import (
"net/http"
"AABBCCDD/app/types" "AABBCCDD/app/types"
"github.com/anthdm/gothkit/kit" "github.com/anthdm/gothkit/kit"
) )
func HandleAuthentication(w http.ResponseWriter, r *http.Request) (kit.Auth, error) { func HandleAuthentication(kit *kit.Kit) (kit.Auth, error) {
return types.AuthUser{}, nil return types.AuthUser{}, nil
} }

View file

@ -3,6 +3,7 @@ package app
import ( import (
"AABBCCDD/app/handlers" "AABBCCDD/app/handlers"
"AABBCCDD/app/views/errors" "AABBCCDD/app/views/errors"
"AABBCCDD/plugins/auth"
"log/slog" "log/slog"
"github.com/anthdm/gothkit/kit" "github.com/anthdm/gothkit/kit"
@ -21,9 +22,11 @@ func InitializeMiddleware(router *chi.Mux) {
// Define your routes in here // Define your routes in here
func InitializeRoutes(router *chi.Mux) { func InitializeRoutes(router *chi.Mux) {
// Comment out to configure your authentication // Authentication plugin:
auth.InitializeRoutes(router)
authConfig := kit.AuthenticationConfig{ authConfig := kit.AuthenticationConfig{
AuthFunc: handlers.HandleAuthentication, AuthFunc: auth.AuthenticateUser,
RedirectURL: "/login", RedirectURL: "/login",
} }

View file

@ -6,9 +6,9 @@ import (
templ Index() { templ Index() {
@layouts.App() { @layouts.App() {
<div class="h-screen text-center flex flex-col justify-center items-center"> <div class="text-center flex flex-col justify-center items-center mt-10 lg:mt-32">
<div class="flex flex-col gap-12"> <div class="flex flex-col gap-12">
<h1 class="inline-block text-transparent bg-clip-text max-w-2xl mx-auto text-4xl lg:text-7xl font-bold uppercase bg-gradient-to-r from-indigo-500 via-purple-500 to-pink-500">superkit</h1> <h1 class="inline-block text-transparent bg-clip-text max-w-2xl mx-auto text-5xl lg:text-7xl font-bold uppercase bg-gradient-to-r from-indigo-500 via-purple-500 to-pink-500">superkit</h1>
<div class="flex flex-col gap-3"> <div class="flex flex-col gap-3">
<h1 class="max-w-2xl mx-auto text-2xl lg:text-4xl font-bold lg:leading-tight"> <h1 class="max-w-2xl mx-auto text-2xl lg:text-4xl font-bold lg:leading-tight">
Build high-performance apps swiftly with minimal team resources. Build high-performance apps swiftly with minimal team resources.

View file

@ -22,7 +22,7 @@ templ BaseLayout() {
<!-- HTMX --> <!-- HTMX -->
<script src="https://unpkg.com/htmx.org@1.9.9" defer></script> <script src="https://unpkg.com/htmx.org@1.9.9" defer></script>
</head> </head>
<body x-data="{theme: 'light'}" :class="theme" lang="en"> <body x-data="{theme: 'dark'}" :class="theme" lang="en">
{ children... } { children... }
</body> </body>
</html> </html>

View file

@ -6,11 +6,13 @@ require (
github.com/a-h/templ v0.2.707 github.com/a-h/templ v0.2.707
github.com/anthdm/gothkit v0.0.0-20240615140127-d74e729d7c71 github.com/anthdm/gothkit v0.0.0-20240615140127-d74e729d7c71
github.com/go-chi/chi/v5 v5.0.12 github.com/go-chi/chi/v5 v5.0.12
github.com/google/uuid v1.6.0
github.com/joho/godotenv v1.5.1 github.com/joho/godotenv v1.5.1
github.com/mattn/go-sqlite3 v1.14.22 github.com/mattn/go-sqlite3 v1.14.22
github.com/uptrace/bun v1.2.1 github.com/uptrace/bun v1.2.1
github.com/uptrace/bun/dialect/sqlitedialect v1.2.1 github.com/uptrace/bun/dialect/sqlitedialect v1.2.1
github.com/uptrace/bun/extra/bundebug v1.2.1 github.com/uptrace/bun/extra/bundebug v1.2.1
golang.org/x/crypto v0.24.0
) )
require ( require (
@ -25,3 +27,6 @@ require (
github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect
golang.org/x/sys v0.21.0 // indirect golang.org/x/sys v0.21.0 // indirect
) )
// uncomment for local development on the superkit core.
// replace github.com/anthdm/gothkit => ../

View file

@ -14,6 +14,8 @@ github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0= github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0=
github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/securecookie v1.1.2 h1:YCIWL56dvtr73r6715mJs5ZvhtnY73hBvEF8kXD8ePA= github.com/gorilla/securecookie v1.1.2 h1:YCIWL56dvtr73r6715mJs5ZvhtnY73hBvEF8kXD8ePA=
github.com/gorilla/securecookie v1.1.2/go.mod h1:NfCASbcHqRSY+3a8tlWJwsQap2VX5pwzwo4h3eOamfo= github.com/gorilla/securecookie v1.1.2/go.mod h1:NfCASbcHqRSY+3a8tlWJwsQap2VX5pwzwo4h3eOamfo=
github.com/gorilla/sessions v1.2.2 h1:lqzMYz6bOfvn2WriPUjNByzeXIlVzURcPmgMczkmTjY= github.com/gorilla/sessions v1.2.2 h1:lqzMYz6bOfvn2WriPUjNByzeXIlVzURcPmgMczkmTjY=
@ -47,6 +49,8 @@ github.com/vmihailenco/msgpack/v5 v5.4.1 h1:cQriyiUvjTwOHg8QZaPihLWeRAAVoCpE00IU
github.com/vmihailenco/msgpack/v5 v5.4.1/go.mod h1:GaZTsDaehaPpQVyxrf5mtQlH+pc21PIudVV/E3rRQok= github.com/vmihailenco/msgpack/v5 v5.4.1/go.mod h1:GaZTsDaehaPpQVyxrf5mtQlH+pc21PIudVV/E3rRQok=
github.com/vmihailenco/tagparser/v2 v2.0.0 h1:y09buUbR+b5aycVFQs/g70pqKVZNBmxwAhO7/IwNM9g= github.com/vmihailenco/tagparser/v2 v2.0.0 h1:y09buUbR+b5aycVFQs/g70pqKVZNBmxwAhO7/IwNM9g=
github.com/vmihailenco/tagparser/v2 v2.0.0/go.mod h1:Wri+At7QHww0WTrCBeu4J6bNtoV6mEfg5OIWRZA9qds= github.com/vmihailenco/tagparser/v2 v2.0.0/go.mod h1:Wri+At7QHww0WTrCBeu4J6bNtoV6mEfg5OIWRZA9qds=
golang.org/x/crypto v0.24.0 h1:mnl8DM0o513X8fdIkmyFE/5hTYxbwYOjDS/+rK6qpRI=
golang.org/x/crypto v0.24.0/go.mod h1:Z1PMYSOR5nyMcyAVAIQSKCDwalqy85Aqn1x3Ws4L5DM=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.19.0 h1:q5f1RH2jigJ1MoAWp2KTp3gm5zAGFUTarQZ5U386+4o= golang.org/x/sys v0.19.0 h1:q5f1RH2jigJ1MoAWp2KTp3gm5zAGFUTarQZ5U386+4o=

View file

@ -1,9 +1,10 @@
package auth package auth
import ( import (
"auth/app/views/layouts"
v "github.com/anthdm/gothkit/validate" v "github.com/anthdm/gothkit/validate"
"auth/app/views/components"
"AABBCCDD/app/views/layouts"
"AABBCCDD/app/views/components"
) )
type AuthIndexPageData struct { type AuthIndexPageData struct {

View file

@ -1,9 +1,10 @@
package auth package auth
import ( import (
"auth/app/db" "AABBCCDD/app/db"
"cmp" "cmp"
"database/sql" "database/sql"
"fmt"
"net/http" "net/http"
"os" "os"
"strconv" "strconv"
@ -69,8 +70,8 @@ func HandleAuthCreate(kit *kit.Kit) error {
return kit.Render(LoginForm(values, errors)) return kit.Render(LoginForm(values, errors))
} }
// todo: use the kit.Getenv instead of the comp thingy skipVerify := kit.Getenv("SUPERKIT_AUTH_SKIP_VERIFY", "false")
skipVerify := cmp.Or(os.Getenv("SUPERKIT_AUTH_SKIP_VERIFY"), "false") fmt.Println(skipVerify)
if skipVerify != "true" { if skipVerify != "true" {
if user.EmailVerifiedAt.Equal(time.Time{}) { if user.EmailVerifiedAt.Equal(time.Time{}) {
errors.Add("verified", "please verify your email") errors.Add("verified", "please verify your email")
@ -78,7 +79,7 @@ func HandleAuthCreate(kit *kit.Kit) error {
} }
} }
sessionExpiryStr := os.Getenv("SUPERKIT_AUTH_SESSION_EXPIRY_IN_HOURS") sessionExpiryStr := kit.Getenv("SUPERKIT_AUTH_SESSION_EXPIRY_IN_HOURS", "48")
sessionExpiry, err := strconv.Atoi(sessionExpiryStr) sessionExpiry, err := strconv.Atoi(sessionExpiryStr)
if err != nil { if err != nil {
sessionExpiry = 48 sessionExpiry = 48
@ -102,7 +103,7 @@ func HandleAuthCreate(kit *kit.Kit) error {
sess.Values["sessionToken"] = session.Token sess.Values["sessionToken"] = session.Token
sess.Save(kit.Request, kit.Response) sess.Save(kit.Request, kit.Response)
redirectURL := cmp.Or(os.Getenv("SUPERKIT_AUTH_REDIRECT_AFTER_LOGIN"), "/profile") redirectURL := kit.Getenv("SUPERKIT_AUTH_REDIRECT_AFTER_LOGIN", "/profile")
return kit.Redirect(http.StatusSeeOther, redirectURL) return kit.Redirect(http.StatusSeeOther, redirectURL)
} }

View file

@ -1,7 +1,7 @@
package auth package auth
import ( import (
"auth/app/db" "AABBCCDD/app/db"
"fmt" "fmt"
"github.com/anthdm/gothkit/kit" "github.com/anthdm/gothkit/kit"

View file

@ -1,9 +1,11 @@
package auth package auth
import ( import (
"auth/app/views/layouts"
v "github.com/anthdm/gothkit/validate"
"fmt" "fmt"
v "github.com/anthdm/gothkit/validate"
"AABBCCDD/app/views/layouts"
) )
templ ProfileShow(formValues ProfileFormValues) { templ ProfileShow(formValues ProfileFormValues) {

View file

@ -2,8 +2,8 @@ package auth
import ( import (
v "github.com/anthdm/gothkit/validate" v "github.com/anthdm/gothkit/validate"
"auth/app/views/layouts" "AABBCCDD/app/views/layouts"
"auth/app/views/components" "AABBCCDD/app/views/components"
) )
type SignupIndexPageData struct { type SignupIndexPageData struct {

View file

@ -1,7 +1,7 @@
package auth package auth
import ( import (
"auth/app/db" "AABBCCDD/app/db"
"context" "context"
"time" "time"

View file

@ -625,11 +625,35 @@ body {
} }
} }
.fixed {
position: fixed;
}
.right-6 {
right: 1.5rem;
}
.top-6 {
top: 1.5rem;
}
.mx-auto { .mx-auto {
margin-left: auto; margin-left: auto;
margin-right: auto; margin-right: auto;
} }
.ml-4 {
margin-left: 1rem;
}
.mt-10 {
margin-top: 2.5rem;
}
.mt-32 {
margin-top: 8rem;
}
.inline-block { .inline-block {
display: inline-block; display: inline-block;
} }
@ -638,6 +662,14 @@ body {
display: flex; display: flex;
} }
.inline-flex {
display: inline-flex;
}
.hidden {
display: none;
}
.h-screen { .h-screen {
height: 100vh; height: 100vh;
} }
@ -659,10 +691,22 @@ body {
max-width: 80rem; max-width: 80rem;
} }
.max-w-md {
max-width: 28rem;
}
.max-w-sm {
max-width: 24rem;
}
.cursor-pointer { .cursor-pointer {
cursor: pointer; cursor: pointer;
} }
.list-disc {
list-style-type: disc;
}
.flex-col { .flex-col {
flex-direction: column; flex-direction: column;
} }
@ -679,10 +723,22 @@ body {
justify-content: space-between; justify-content: space-between;
} }
.gap-1 {
gap: 0.25rem;
}
.gap-10 {
gap: 2.5rem;
}
.gap-12 { .gap-12 {
gap: 3rem; gap: 3rem;
} }
.gap-2 {
gap: 0.5rem;
}
.gap-3 { .gap-3 {
gap: 0.75rem; gap: 0.75rem;
} }
@ -691,19 +747,45 @@ body {
gap: 1rem; gap: 1rem;
} }
.gap-6 {
gap: 1.5rem;
}
.gap-8 {
gap: 2rem;
}
.rounded-md { .rounded-md {
border-radius: calc(var(--radius) - 2px); border-radius: calc(var(--radius) - 2px);
} }
.border {
border-width: 1px;
}
.border-b { .border-b {
border-bottom-width: 1px; border-bottom-width: 1px;
} }
.border-input {
--tw-border-opacity: 1;
border-color: hsl(var(--input) / var(--tw-border-opacity));
}
.border-red-500 {
--tw-border-opacity: 1;
border-color: rgb(239 68 68 / var(--tw-border-opacity));
}
.bg-primary { .bg-primary {
--tw-bg-opacity: 1; --tw-bg-opacity: 1;
background-color: hsl(var(--primary) / var(--tw-bg-opacity)); background-color: hsl(var(--primary) / var(--tw-bg-opacity));
} }
.bg-transparent {
background-color: transparent;
}
.bg-gradient-to-r { .bg-gradient-to-r {
background-image: linear-gradient(to right, var(--tw-gradient-stops)); background-image: linear-gradient(to right, var(--tw-gradient-stops));
} }
@ -728,11 +810,31 @@ body {
background-clip: text; background-clip: text;
} }
.px-3 {
padding-left: 0.75rem;
padding-right: 0.75rem;
}
.px-4 { .px-4 {
padding-left: 1rem; padding-left: 1rem;
padding-right: 1rem; padding-right: 1rem;
} }
.px-6 {
padding-left: 1.5rem;
padding-right: 1.5rem;
}
.px-8 {
padding-left: 2rem;
padding-right: 2rem;
}
.py-12 {
padding-top: 3rem;
padding-bottom: 3rem;
}
.py-2 { .py-2 {
padding-top: 0.5rem; padding-top: 0.5rem;
padding-bottom: 0.5rem; padding-bottom: 0.5rem;
@ -776,6 +878,11 @@ body {
line-height: 1.25rem; line-height: 1.25rem;
} }
.text-xs {
font-size: 0.75rem;
line-height: 1rem;
}
.font-bold { .font-bold {
font-weight: 700; font-weight: 700;
} }
@ -792,6 +899,10 @@ body {
text-transform: uppercase; text-transform: uppercase;
} }
.tracking-wide {
letter-spacing: 0.025em;
}
.text-foreground { .text-foreground {
--tw-text-opacity: 1; --tw-text-opacity: 1;
color: hsl(var(--foreground) / var(--tw-text-opacity)); color: hsl(var(--foreground) / var(--tw-text-opacity));
@ -807,17 +918,101 @@ body {
color: hsl(var(--primary-foreground) / var(--tw-text-opacity)); color: hsl(var(--primary-foreground) / var(--tw-text-opacity));
} }
.text-red-500 {
--tw-text-opacity: 1;
color: rgb(239 68 68 / var(--tw-text-opacity));
}
.text-transparent { .text-transparent {
color: transparent; color: transparent;
} }
.underline {
text-decoration-line: underline;
}
.shadow-sm {
--tw-shadow: 0 1px 2px 0 rgb(0 0 0 / 0.05);
--tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color);
box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow);
}
.ring-offset-background {
--tw-ring-offset-color: hsl(var(--background) / 1);
}
.transition-colors {
transition-property: color, background-color, border-color, text-decoration-color, fill, stroke;
transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
transition-duration: 150ms;
}
.duration-200 {
transition-duration: 200ms;
}
/* fix for Alpine users. */ /* fix for Alpine users. */
[x-cloak] { [x-cloak] {
display: none !important; display: none !important;
} }
.placeholder\:text-neutral-500::-moz-placeholder {
--tw-text-opacity: 1;
color: rgb(115 115 115 / var(--tw-text-opacity));
}
.placeholder\:text-neutral-500::placeholder {
--tw-text-opacity: 1;
color: rgb(115 115 115 / var(--tw-text-opacity));
}
.hover\:bg-primary\/90:hover {
background-color: hsl(var(--primary) / 0.9);
}
.focus\:border-neutral-300:focus {
--tw-border-opacity: 1;
border-color: rgb(212 212 212 / var(--tw-border-opacity));
}
.focus\:outline-none:focus {
outline: 2px solid transparent;
outline-offset: 2px;
}
.focus\:ring:focus {
--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);
--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(3px + var(--tw-ring-offset-width)) var(--tw-ring-color);
box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000);
}
.focus\:ring-primary:focus {
--tw-ring-opacity: 1;
--tw-ring-color: hsl(var(--primary) / var(--tw-ring-opacity));
}
.disabled\:cursor-not-allowed:disabled {
cursor: not-allowed;
}
.disabled\:opacity-50:disabled {
opacity: 0.5;
}
@media (min-width: 1024px) { @media (min-width: 1024px) {
.lg\:mt-20 {
margin-top: 5rem;
}
.lg\:mt-40 {
margin-top: 10rem;
}
.lg\:mt-32 {
margin-top: 8rem;
}
.lg\:text-4xl { .lg\:text-4xl {
font-size: 2.25rem; font-size: 2.25rem;
line-height: 2.5rem; line-height: 2.5rem;

View file

@ -92,6 +92,10 @@ func (kit *Kit) Render(c templ.Component) error {
return c.Render(kit.Request.Context(), kit.Response) return c.Render(kit.Request.Context(), kit.Response)
} }
func (kit *Kit) Getenv(name string, def string) string {
return Getenv(name, def)
}
func Handler(h HandlerFunc) http.HandlerFunc { func Handler(h HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
kit := &Kit{ kit := &Kit{