Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Setup email and password based authentication #18

Merged
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
46 changes: 46 additions & 0 deletions .air.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
root = "."
testdata_dir = "testdata"
tmp_dir = "tmp"

[build]
args_bin = []
bin = "./server"
cmd = "make build"
delay = 1000
exclude_dir = ["assets", "tmp", "vendor", "testdata", "node_modules"]
exclude_file = []
exclude_regex = ["_test.go"]
exclude_unchanged = false
follow_symlink = false
full_bin = ""
include_dir = []
include_ext = ["go", "tpl", "tmpl", "html"]
include_file = []
kill_delay = "0s"
log = "build-errors.log"
poll = false
poll_interval = 0
post_cmd = []
pre_cmd = []
rerun = false
rerun_delay = 500
send_interrupt = false
stop_on_error = false

[color]
app = ""
build = "yellow"
main = "magenta"
runner = "green"
watcher = "cyan"

[log]
main_only = false
time = false

[misc]
clean_on_exit = false

[screen]
clear_on_rebuild = false
keep_scroll = true
3 changes: 3 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
PG_URL="postgres://postgres:pwd@postgres:5432/visio?sslmode=disable"
REDIS_URL="redis://redis:6479"
PORT="8080"
7 changes: 7 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,10 @@
*.out
go.work
server
vendor
main
.env
tmp/
htmx.min.js
public/output.css
node_modules
3 changes: 3 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -32,5 +32,8 @@ push-image:
@docker tag visio-dev:latest thewisepigeon/visio-dev:latest
@docker push thewisepigeon/visio-dev:latest

tailwind-compilation:
@npx tailwindcss -i ./assets/app.css -o ./public/output.css --watch

test:
@go test -v ./...
3 changes: 3 additions & 0 deletions assets/app.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
2 changes: 1 addition & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ services:
image: golang
container_name: server
volumes:
- ~/code/visio/server:/go/src/app
- ~/code/visio/:/go/src/app
depends_on:
- postgres
ports:
Expand Down
3 changes: 3 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ require (
github.com/go-chi/jwtauth/v5 v5.3.0 // indirect
github.com/goccy/go-json v0.10.2 // indirect
github.com/gofiber/fiber/v2 v2.51.0 // indirect
github.com/gofiber/template v1.8.2 // indirect
github.com/gofiber/template/html/v2 v2.0.5 // indirect
github.com/gofiber/utils v1.1.0 // indirect
github.com/google/uuid v1.5.0 // indirect
github.com/jmoiron/sqlx v1.3.5 // indirect
github.com/joho/godotenv v1.5.1 // indirect
Expand Down
6 changes: 6 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,12 @@ 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/gofiber/fiber/v2 v2.51.0 h1:JNACcZy5e2tGApWB2QrRpenTWn0fq0hkFm6k0C86gKQ=
github.com/gofiber/fiber/v2 v2.51.0/go.mod h1:xaQRZQJGqnKOQnbQw+ltvku3/h8QxvNi8o6JiJ7Ll0U=
github.com/gofiber/template v1.8.2 h1:PIv9s/7Uq6m+Fm2MDNd20pAFFKt5wWs7ZBd8iV9pWwk=
github.com/gofiber/template v1.8.2/go.mod h1:bs/2n0pSNPOkRa5VJ8zTIvedcI/lEYxzV3+YPXdBvq8=
github.com/gofiber/template/html/v2 v2.0.5 h1:BKLJ6Qr940NjntbGmpO3zVa4nFNGDCi/IfUiDB9OC20=
github.com/gofiber/template/html/v2 v2.0.5/go.mod h1:RCF14eLeQDCSUPp0IGc2wbSSDv6yt+V54XB/+Unz+LM=
github.com/gofiber/utils v1.1.0 h1:vdEBpn7AzIUJRhe+CiTOJdUcTg4Q9RK+pEa0KPbLdrM=
github.com/gofiber/utils v1.1.0/go.mod h1:poZpsnhBykfnY1Mc0KeEa6mSHrS3dV0+oBWyeQmb2e0=
github.com/google/uuid v1.5.0 h1:1p67kYwdtXjb0gL0BPiP1Av9wiZPo5A8z2cWkTZ+eyU=
github.com/google/uuid v1.5.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/jmoiron/sqlx v1.3.5 h1:vFFPA71p1o5gAeqtEAwLU4dnX2napprKtHr7PYIcN3g=
Expand Down
21 changes: 21 additions & 0 deletions internal/database/redis.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package database

import (
"fmt"
"os"
"github.com/redis/go-redis/v9"
)

func GetRedisClient() *redis.Client {
redisURL := os.Getenv("REDIS_URL")
if redisURL == "" {
fmt.Println("Failed to read REDIS_URL environment variable")
os.Exit(1)
}
opts, err := redis.ParseURL(redisURL)
if err != nil {
fmt.Printf("Error while parsing redis URL: %v", err)
os.Exit(1)
}
return redis.NewClient(opts)
}
18 changes: 18 additions & 0 deletions internal/handlers/app.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package handlers

import "github.com/gofiber/fiber/v2"

type AppHandler struct {
}

func NewAppHandler() *AppHandler {
return &AppHandler{}
}

func (h *AppHandler) GetLandingPage(c *fiber.Ctx) error {
return c.Render("index", fiber.Map{})
}

func (h *AppHandler) GetAuthPage(c *fiber.Ctx) error {
return c.Render("auth", fiber.Map{})
}
75 changes: 17 additions & 58 deletions internal/handlers/auth.go
Original file line number Diff line number Diff line change
@@ -1,17 +1,11 @@
package handlers

import (
"errors"
"fmt"
"github.com/gofiber/fiber/v2"
"github.com/oklog/ulid/v2"
"log/slog"
"net/http"
"os"
"time"
"visio/internal/store"
"visio/internal/types"
"visio/pkg"

"github.com/gofiber/fiber/v2"
)

type AuthHandler struct {
Expand All @@ -26,57 +20,22 @@ func NewAuthHandler(usersStore *store.Users, logger *slog.Logger) *AuthHandler {
}
}

func (h *AuthHandler) GetAuthURL(c *fiber.Ctx) error {
url := fmt.Sprintf(
"https://github.com/login/oauth/authorize?client_id=%s&redirect_uri=%s",
os.Getenv("GH_CLIENT_ID"),
os.Getenv("GH_REDIRECT_URI"),
)
response := struct {
URL string `json:"url"`
}{
URL: url,
}
if err := c.Status(fiber.StatusOK).JSON(response); err != nil {
h.logger.Error(err.Error())
return c.SendStatus(fiber.ErrInternalServerError.Code)
}
return nil
}

func (h *AuthHandler) GithubAuthCallback(c *fiber.Ctx) error {
code := c.Query("code")
error := c.Query("error")
webAppURL := os.Getenv("WEB_APP_URL")
errorURL := "%s/error?context=%s"
internalErrRedirect := fmt.Sprintf(errorURL, webAppURL, "internal")
if error != "" {
var redirectURL string
switch error {
case "access_denied":
redirectURL = fmt.Sprintf(errorURL, webAppURL, error)
default:
h.logger.Debug(fmt.Sprintf("Error while handling github redirect: %s", error))
redirectURL = fmt.Sprint(errorURL, webAppURL, "unknown")
}
if err := c.Redirect(redirectURL, fiber.StatusTemporaryRedirect); err != nil {
h.logger.Error(err.Error())
return c.SendStatus(fiber.ErrInternalServerError.Code)
}
return nil
}
accessToken, err := pkg.GetToken(code)
return nil
}

func (h *AuthHandler) GetUserInfo(c *fiber.Ctx) error {
currentUser, ok := c.Context().Value("currentUser").(map[string]string)
if !ok {
return c.SendStatus(fiber.ErrUnauthorized.Code)
}
if err := c.Status(fiber.StatusOK).JSON(currentUser); err != nil {
h.logger.Error(err.Error())
func (h *AuthHandler) Signup(c *fiber.Ctx) error {
reqPayload := new(struct {
Email string `json:"email"`
Password string `json:"password"`
})
if err := c.BodyParser(reqPayload); err != nil {
h.logger.Error(fmt.Sprintf("Error while parsing body: %v", err))
return c.SendStatus(fiber.ErrInternalServerError.Code)
}
// count, err := h.users.CountByEmail(reqPayload.Email)
// if err != nil {
// h.logger.Error(err.Error())
// return c.SendStatus(fiber.ErrInternalServerError.Code)
// }
// if count != 0 {
// return c.SendStatus(fiber.ErrConflict.Code)
// }
return nil
}
31 changes: 8 additions & 23 deletions internal/store/users.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,8 @@ package store
import (
"database/sql"
"fmt"
"visio/internal/types"

"github.com/jmoiron/sqlx"
"visio/internal/types"
)

type Users struct {
Expand All @@ -21,8 +20,8 @@ func NewUsersStore(db *sqlx.DB) *Users {
func (s *Users) Insert(user *types.User) error {
_, err := s.db.NamedExec(
`
insert into users(id, github_id, email, username, avatar, signup_date)
values (:id, :github_id, :email, :username, :avatar, :signup_date)
insert into users(id, email, password, signup_date)
values (:id, :email, :password, :signup_date)
`,
user,
)
Expand All @@ -44,25 +43,11 @@ func (s *Users) GetById(id string) (*types.User, error) {
return dbUser, nil
}

func (s *Users) GetByGithubId(id string) (*types.User, error) {
dbUser := new(types.User)
err := s.db.Get(dbUser, "select * from users where github_id=$1", id)
if err != nil {
if err == sql.ErrNoRows {
return nil, types.ErrUserNotFound
}
return nil, fmt.Errorf("Error while querying user from database: %w", err)
}
return dbUser, nil
}

func (s *Users) UpdateUserData(id, email, username, avatar string) error {
_, err := s.db.Exec(
"update users set username=$1, email=$2, avatar=$3 where id=$4",
username, email, avatar, id,
)
func (s *Users) CountByEmail(email string) (int, error) {
count := 0
err := s.db.QueryRowx("select count(*) from users where email=$1", email).Scan(&count)
if err != nil {
return fmt.Errorf("Error while updating user data: %w", err)
return 0, fmt.Errorf("Error while counting users by email: %w", err)
}
return nil
return count, nil
}
5 changes: 2 additions & 3 deletions internal/types/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package types
import "errors"

var (
ErrNoPrimaryEmailFound = errors.New("No primary email found")
ErrUserNotFound = errors.New("No user found")
ErrSessionNotFound = errors.New("Session not found")
ErrUserNotFound = errors.New("No user found")
ErrSessionNotFound = errors.New("Session not found")
)
4 changes: 1 addition & 3 deletions internal/types/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,7 @@ import "time"

type User struct {
Id string `json:"id" db:"id"`
GithubId string `json:"github_id" db:"github_id"`
Email string `json:"email" db:"email"`
Username string `json:"username" db:"username"`
Avatar string `json:"avatar" db:"avatar"`
Password string `json:"password" db:"password"`
SignupDate time.Time `json:"signup_date" db:"signup_date"`
}
59 changes: 23 additions & 36 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,13 @@ import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/logger"
"github.com/gofiber/fiber/v2/middleware/recover"
"github.com/gofiber/template/html/v2"
"github.com/joho/godotenv"
"log/slog"
"os"
)

type (
Host struct {
Fiber *fiber.App
}
"visio/internal/database"
"visio/internal/handlers"
"visio/internal/store"
)

func main() {
Expand All @@ -23,45 +22,33 @@ func main() {
panic(err)
}
}
hosts := map[string]*Host{}

api := fiber.New()
api.Use(logger.New())
api.Use(recover.New())

hosts["api.localhost:8080"] = &Host{api}

api.Get("/", func(c *fiber.Ctx) error {
return c.SendStatus(fiber.StatusOK)
appHandler := handlers.NewAppHandler()
postgresPool := database.NewPostgresPool()
usersStore := store.NewUsersStore(postgresPool)
textHandler := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{})
appLogger := slog.New(textHandler)
authHandler := handlers.NewAuthHandler(usersStore, appLogger)

engine := html.New("./views", ".html")
engine.Reload(appEnv != "PROD")
app := fiber.New(fiber.Config{
Views: engine,
ViewsLayout: "layouts/main",
})

app := fiber.New()
app.Static("/public", "./public")
app.Use(logger.New())
app.Use(recover.New())

hosts["localhost:8080"] = &Host{app}

app.Get("/home", func(c *fiber.Ctx) error {
return c.SendStatus(fiber.StatusOK)
})

server := fiber.New()
server.Use(func(c *fiber.Ctx) error {
host := hosts[c.Hostname()]
if host == nil {
return c.SendStatus(fiber.ErrNotFound.Code)
} else {
host.Fiber.Handler()(c.Context())
return nil
}
})
app.Get("/", appHandler.GetLandingPage)
app.Get("/auth", appHandler.GetAuthPage)
api := app.Group("/api")
api.Post("/auth", authHandler.Signup)

port := os.Getenv("PORT")
if port == "" {
panic("Unable to read PORT environment variable")
}
fmt.Printf("Server listening on port %s", port)
err := server.Listen(fmt.Sprintf(":%s", port))
err := app.Listen(fmt.Sprintf(":%s", port))
if err != nil {
panic(err)
}
Expand Down
Loading
Loading