restructuring, config and readme
This commit is contained in:
53
backend/internal/auth/controller.go
Normal file
53
backend/internal/auth/controller.go
Normal file
@@ -0,0 +1,53 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"git.schreifuchs.ch/schreifuchs/ng-blog/backend/internal/model"
|
||||
)
|
||||
|
||||
func (s *Service) Login(w http.ResponseWriter, r *http.Request) {
|
||||
login := model.Login{}
|
||||
if err := json.NewDecoder(r.Body).Decode(&login); err != nil {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
if login.Name == s.cfg.AdminName && login.Password == s.cfg.AdminPassword {
|
||||
token, err := createJWT([]byte(s.cfg.Secret))
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
err = json.NewEncoder(w).Encode(&model.LoginResponse{
|
||||
Token: token,
|
||||
})
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) Authenticated(next http.HandlerFunc) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// Our middleware logic goes here...
|
||||
token, err := extractToken(r)
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
err = validateJWT(token, []byte(s.cfg.Secret))
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
next(w, r)
|
||||
})
|
||||
}
|
51
backend/internal/auth/jwt.go
Normal file
51
backend/internal/auth/jwt.go
Normal file
@@ -0,0 +1,51 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
func createJWT(secret []byte) (token string, err error) {
|
||||
return jwt.NewWithClaims(jwt.SigningMethodHS512, jwt.MapClaims{
|
||||
"exp": time.Now().Add(time.Hour * 24).Unix(),
|
||||
}).SignedString(secret)
|
||||
}
|
||||
|
||||
func validateJWT(tokenString string, secret []byte) (err error) {
|
||||
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (any, error) {
|
||||
// Don't forget to validate the alg is what you expect:
|
||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
|
||||
}
|
||||
|
||||
return secret, nil
|
||||
})
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if date, err := token.Claims.GetExpirationTime(); err == nil && date.After(time.Now()) {
|
||||
return nil
|
||||
}
|
||||
return errors.New("JWT not valid")
|
||||
}
|
||||
|
||||
func extractToken(r *http.Request) (token string, err error) {
|
||||
tokenHeader := r.Header.Get("Authorization") // Grab the token from the header
|
||||
|
||||
if tokenHeader == "" {
|
||||
err = errors.New("missing token")
|
||||
return
|
||||
}
|
||||
|
||||
token = strings.TrimPrefix(tokenHeader, "Bearer ")
|
||||
|
||||
if token == "" {
|
||||
err = errors.New("malformed token")
|
||||
}
|
||||
return
|
||||
}
|
26
backend/internal/auth/resource.go
Normal file
26
backend/internal/auth/resource.go
Normal file
@@ -0,0 +1,26 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Secret string `env:"SECRET"`
|
||||
ValidDuration time.Duration `env:"VALID_DURATION"`
|
||||
AdminName string `env:"ADMIN_NAME"`
|
||||
AdminPassword string `env:"ADMIN_PASSWORD"`
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
cfg *Config
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func New(cfg *Config, db *gorm.DB) *Service {
|
||||
return &Service{
|
||||
cfg,
|
||||
db,
|
||||
}
|
||||
}
|
61
backend/internal/blog/controller.go
Normal file
61
backend/internal/blog/controller.go
Normal file
@@ -0,0 +1,61 @@
|
||||
package blog
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"git.schreifuchs.ch/schreifuchs/ng-blog/backend/internal/model"
|
||||
"github.com/gorilla/mux"
|
||||
)
|
||||
|
||||
func (s Service) SavePost(w http.ResponseWriter, r *http.Request) {
|
||||
var post model.Post
|
||||
if err := json.NewDecoder(r.Body).Decode(&post); err != nil {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
fmt.Fprint(w, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
if err := s.db.Save(&post).Error; err != nil {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
fmt.Fprint(w, err.Error())
|
||||
}
|
||||
|
||||
json.NewEncoder(w).Encode(&post)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}
|
||||
|
||||
func (s Service) GetAllPosts(w http.ResponseWriter, r *http.Request) {
|
||||
var posts []model.Post
|
||||
|
||||
if err := s.db.Preload("Comments").Order("created_at DESC").Find(&posts).Error; err != nil {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
fmt.Fprint(w, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
json.NewEncoder(w).Encode(&posts)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}
|
||||
|
||||
func (s Service) DeletePost(w http.ResponseWriter, r *http.Request) {
|
||||
idStr, ok := mux.Vars(r)["postID"]
|
||||
if !ok {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
id, err := strconv.Atoi(idStr)
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
err = s.db.Delete(&model.Post{}, id).Error
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
fmt.Fprint(w, err.Error())
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
11
backend/internal/blog/resource.go
Normal file
11
backend/internal/blog/resource.go
Normal file
@@ -0,0 +1,11 @@
|
||||
package blog
|
||||
|
||||
import "gorm.io/gorm"
|
||||
|
||||
type Service struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func New(db *gorm.DB) *Service {
|
||||
return &Service{db: db}
|
||||
}
|
28
backend/internal/config/resource.go
Normal file
28
backend/internal/config/resource.go
Normal file
@@ -0,0 +1,28 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"git.schreifuchs.ch/schreifuchs/ng-blog/backend/internal/auth"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Port int `env:"PORT"`
|
||||
Host string `env:"HOST"`
|
||||
DBPath string `env:"DB_PATH"`
|
||||
Auth auth.Config `env:"AUTH"`
|
||||
}
|
||||
|
||||
func Default() *Config {
|
||||
return &Config{
|
||||
Port: 8080,
|
||||
Host: "localhost",
|
||||
DBPath: "./blog.db",
|
||||
Auth: auth.Config{
|
||||
Secret: "secret",
|
||||
ValidDuration: time.Hour * 1,
|
||||
AdminName: "admin",
|
||||
AdminPassword: "admin",
|
||||
},
|
||||
}
|
||||
}
|
32
backend/internal/initialize/inject.go
Normal file
32
backend/internal/initialize/inject.go
Normal file
@@ -0,0 +1,32 @@
|
||||
package initialize
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"git.schreifuchs.ch/schreifuchs/ng-blog/backend/internal/auth"
|
||||
"git.schreifuchs.ch/schreifuchs/ng-blog/backend/internal/blog"
|
||||
"git.schreifuchs.ch/schreifuchs/ng-blog/backend/internal/config"
|
||||
"git.schreifuchs.ch/schreifuchs/ng-blog/backend/internal/model"
|
||||
"git.schreifuchs.ch/schreifuchs/ng-blog/backend/pkg/cors"
|
||||
"github.com/gorilla/mux"
|
||||
)
|
||||
|
||||
func CreateMux(cfg *config.Config) (r *mux.Router) {
|
||||
db := model.Init()
|
||||
blg := blog.New(db)
|
||||
auth := auth.New(&cfg.Auth, db)
|
||||
|
||||
r = mux.NewRouter()
|
||||
r.Use(cors.HandlerForOrigin("*"))
|
||||
r.HandleFunc("/login", auth.Login).Methods("POST")
|
||||
r.Handle("/posts", auth.Authenticated(blg.SavePost)).Methods("POST")
|
||||
r.Handle("/posts", auth.Authenticated(blg.SavePost)).Methods("PUT")
|
||||
r.Handle("/posts/{postID}", auth.Authenticated(blg.DeletePost)).Methods("DELETE")
|
||||
r.Handle("/posts", http.HandlerFunc(blg.GetAllPosts)).Methods("GET")
|
||||
r.Methods("OPTIONS").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// The CORS middleware should set up the headers for you
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
})
|
||||
|
||||
return
|
||||
}
|
9
backend/internal/model/auth.go
Normal file
9
backend/internal/model/auth.go
Normal file
@@ -0,0 +1,9 @@
|
||||
package model
|
||||
|
||||
type Login struct {
|
||||
Name string `json:"name"`
|
||||
Password string `json:"Password"`
|
||||
}
|
||||
type LoginResponse struct {
|
||||
Token string `json:"token"`
|
||||
}
|
19
backend/internal/model/blog.go
Normal file
19
backend/internal/model/blog.go
Normal file
@@ -0,0 +1,19 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type Post struct {
|
||||
gorm.Model
|
||||
ID uint `gorm:"primarykey" json:"id"`
|
||||
Title string `json:"title"`
|
||||
TLDR string `json:"tldr"`
|
||||
Content string `json:"content"`
|
||||
Comments []Comment
|
||||
}
|
||||
type Comment struct {
|
||||
ID uint
|
||||
PostID uint
|
||||
Content string `json:"content"`
|
||||
}
|
36
backend/internal/model/init.go
Normal file
36
backend/internal/model/init.go
Normal file
@@ -0,0 +1,36 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"log"
|
||||
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func Init() *gorm.DB {
|
||||
db, err := gorm.Open(sqlite.Open("./blog.db"))
|
||||
if err != nil {
|
||||
log.Panic(err)
|
||||
}
|
||||
db.AutoMigrate(&Post{}, &Comment{})
|
||||
|
||||
db.Save(&Post{
|
||||
ID: 1,
|
||||
Title: "Hello World",
|
||||
TLDR: "introduction to ng-blog",
|
||||
Content: `
|
||||
## Welcome
|
||||
|
||||
This is ng-blog, your simple blog written in Angular and Golang.
|
||||
|
||||
### Login
|
||||
|
||||
The default login is:
|
||||
> Username: admin
|
||||
>
|
||||
> Password: admin
|
||||
`,
|
||||
})
|
||||
|
||||
return db
|
||||
}
|
Reference in New Issue
Block a user