show first entry
This commit is contained in:
102
backend/auth/login.go
Normal file
102
backend/auth/login.go
Normal file
@ -0,0 +1,102 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.schreifuchs.ch/schreifuchs/ng-blog/backend/model"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
func Login(username, password string, secret []byte) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
var login model.Login
|
||||
if err := json.NewDecoder(r.Response.Request.Body).Decode(&login); err != nil {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
if login.Name == username && login.Password == password {
|
||||
token, err := createJWT(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 Authenticated(secret []byte) func(http.HandlerFunc) http.Handler {
|
||||
return func(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, secret)
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
next(w, r)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
BIN
backend/blog.db
Normal file
BIN
backend/blog.db
Normal file
Binary file not shown.
39
backend/blog/controller.go
Normal file
39
backend/blog/controller.go
Normal file
@ -0,0 +1,39 @@
|
||||
package blog
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"git.schreifuchs.ch/schreifuchs/ng-blog/backend/model"
|
||||
)
|
||||
|
||||
func (s Service) CreatePost(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)
|
||||
}
|
11
backend/blog/resource.go
Normal file
11
backend/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}
|
||||
}
|
25
backend/cors/cors.go
Normal file
25
backend/cors/cors.go
Normal file
@ -0,0 +1,25 @@
|
||||
package cors
|
||||
|
||||
import "net/http"
|
||||
|
||||
func HandlerForOrigin(origin string) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if origin := r.Header.Get("Origin"); origin != "" {
|
||||
w.Header().Set("Access-Control-Allow-Origin", origin)
|
||||
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
|
||||
w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
|
||||
w.Header().Set("Access-Control-Expose-Headers", "Authorization")
|
||||
w.Header().Set("Access-Control-Allow-Credentials", "true")
|
||||
}
|
||||
if r.Method == "OPTIONS" {
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func DeafaultHandler(next http.Handler) http.Handler {
|
||||
return HandlerForOrigin("*")(next)
|
||||
}
|
18
backend/go.mod
Normal file
18
backend/go.mod
Normal file
@ -0,0 +1,18 @@
|
||||
module git.schreifuchs.ch/schreifuchs/ng-blog/backend
|
||||
|
||||
go 1.24.2
|
||||
|
||||
require (
|
||||
github.com/golang-jwt/jwt/v5 v5.2.2
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/gorilla/mux v1.8.1
|
||||
gorm.io/driver/sqlite v1.5.7
|
||||
gorm.io/gorm v1.25.12
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/jinzhu/inflection v1.0.0 // indirect
|
||||
github.com/jinzhu/now v1.1.5 // indirect
|
||||
github.com/mattn/go-sqlite3 v1.14.22 // indirect
|
||||
golang.org/x/text v0.14.0 // indirect
|
||||
)
|
18
backend/go.sum
Normal file
18
backend/go.sum
Normal file
@ -0,0 +1,18 @@
|
||||
github.com/golang-jwt/jwt/v5 v5.2.2 h1:Rl4B7itRWVtYIHFrSNd7vhTiz9UpLdi6gZhZ3wEeDy8=
|
||||
github.com/golang-jwt/jwt/v5 v5.2.2/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
|
||||
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/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY=
|
||||
github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ=
|
||||
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
|
||||
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
|
||||
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
|
||||
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
|
||||
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
|
||||
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
|
||||
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
|
||||
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||
gorm.io/driver/sqlite v1.5.7 h1:8NvsrhP0ifM7LX9G4zPB97NwovUakUxc+2V2uuf3Z1I=
|
||||
gorm.io/driver/sqlite v1.5.7/go.mod h1:U+J8craQU6Fzkcvu8oLeAQmi50TkwPEhHDEjQZXDah4=
|
||||
gorm.io/gorm v1.25.12 h1:I0u8i2hWQItBq1WfE0o2+WuL9+8L21K9e2HHSTE/0f8=
|
||||
gorm.io/gorm v1.25.12/go.mod h1:xh7N7RHfYlNc5EmcI/El95gXusucDrQnHXe0+CgWcLQ=
|
38
backend/main.go
Normal file
38
backend/main.go
Normal file
@ -0,0 +1,38 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"os"
|
||||
|
||||
"git.schreifuchs.ch/schreifuchs/ng-blog/backend/auth"
|
||||
"git.schreifuchs.ch/schreifuchs/ng-blog/backend/blog"
|
||||
"git.schreifuchs.ch/schreifuchs/ng-blog/backend/cors"
|
||||
"git.schreifuchs.ch/schreifuchs/ng-blog/backend/model"
|
||||
"github.com/gorilla/mux"
|
||||
)
|
||||
|
||||
func main() {
|
||||
user, ok := os.LookupEnv("USERNAME")
|
||||
if !ok {
|
||||
user = "admin"
|
||||
}
|
||||
password, ok := os.LookupEnv("PASSWORD")
|
||||
if !ok {
|
||||
password = "admin"
|
||||
}
|
||||
secret, ok := os.LookupEnv("SECRET")
|
||||
if !ok {
|
||||
secret = "Foo"
|
||||
}
|
||||
|
||||
db := model.Init()
|
||||
blg := blog.New(db)
|
||||
r := mux.NewRouter()
|
||||
r.Handle("/login", auth.Login(user, password, []byte(secret))).Methods("POST")
|
||||
r.Handle("/posts", auth.Authenticated([]byte(secret))(blg.CreatePost)).Methods("POST")
|
||||
r.Handle("/posts", http.HandlerFunc(blg.GetAllPosts)).Methods("GET")
|
||||
|
||||
r.Use(cors.HandlerForOrigin("*"))
|
||||
|
||||
http.ListenAndServe(":8080", r)
|
||||
}
|
9
backend/model/auth.go
Normal file
9
backend/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/model/blog.go
Normal file
19
backend/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"`
|
||||
}
|
40
backend/model/init.go
Normal file
40
backend/model/init.go
Normal file
@ -0,0 +1,40 @@
|
||||
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: "Foo",
|
||||
TLDR: "Just some Foo Bar",
|
||||
Content: "fkdj kjfk adjflkjdlö jdslj alsödj fla",
|
||||
})
|
||||
db.Save(&Post{
|
||||
ID: 2,
|
||||
Title: "Bar",
|
||||
TLDR: "Just some Bar Baz",
|
||||
Content: `
|
||||
# Hello Worls
|
||||
|
||||
- alsödj
|
||||
- adf adf
|
||||
|
||||
| adsf | asdf |
|
||||
|------|------|
|
||||
| adf | adsf |
|
||||
`,
|
||||
})
|
||||
|
||||
return db
|
||||
}
|
Reference in New Issue
Block a user