started implementing api

This commit is contained in:
ACoolName 2024-05-07 21:10:35 +03:00
parent 7905062cdc
commit 10c5367b9b
6 changed files with 147 additions and 30 deletions

View File

@ -2,9 +2,16 @@ package auth
import (
"context"
"encoding/json"
"fmt"
"hash"
"net/http"
"time"
"acoolname.co/backend/user"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
)
@ -21,27 +28,136 @@ const (
Admin
)
type User struct {
Username string `json:"username"`
Email string `json:"email"`
MaxOwnedServers int `json:"maxed_owned_servers"`
Permissions []string `json:"permissions"`
HashedPass string `json:"HashedPass"`
}
var hmacSampleSecret []byte
type Connection struct {
connection *mongo.Client
}
func (con Connection) AuthorizedTo(requiredPermissions Permission) gin.HandlerFunc {
type TokenInfo struct {
Username string `json:"username"`
Permissions Permission `json:"permissions"`
}
type AuthClaims struct {
*jwt.StandardClaims
TokenInfo
}
func signToken(token TokenInfo) (string, error) {
t := jwt.New(jwt.GetSigningMethod("HS512"))
t.Claims = &AuthClaims{
&jwt.StandardClaims{
ExpiresAt: time.Now().Add(time.Hour * 24 * 30).Unix(),
},
token,
}
return t.SignedString(hmacSampleSecret)
}
func AuthorizedTo(requiredPermissions Permission) gin.HandlerFunc {
return func(ctx *gin.Context) {
fmt.Println("Auth logic starts")
authCookie, err := ctx.Request.Cookie("auth")
if err != nil {
ctx http.Response{
Status: "403",
Body: "Authorization Required",
ctx.AbortWithError(403, err)
}
token, err := jwt.ParseWithClaims(authCookie.Value, &AuthClaims{}, func(token *jwt.Token) (interface{}, 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"])
}
// hmacSampleSecret is a []byte containing your secret, e.g. []byte("my_secret_key")
return hmacSampleSecret, nil
})
fmt.Println(token.Claims)
if claims, ok := token.Claims.(*AuthClaims); ok && token.Valid {
ctx.Set("claims", claims)
if requiredPermissions&claims.Permissions != requiredPermissions {
ctx.AbortWithStatus(403)
}
} else {
ctx.AbortWithStatus(500)
}
con.connection.Database("Backend").Collection("users").Find(context.TODO(), bson.D{})
}
}
func (con Connection) signUp(c *gin.Context) {
var token TokenInfo
type SignUpRequest struct {
token string
username string
password string
}
err := json.NewDecoder(c.Request.Body).Decode(&token)
if err != nil {
c.AbortWithError(500, err)
}
signedToken, err := signToken(token)
if err != nil {
c.AbortWithError(500, err)
}
c.SetCookie("auth", signedToken, -1, "", "", false, false)
c.IndentedJSON(http.StatusOK, signedToken)
}
type SignInRequest struct {
username string
password string
}
func (con Connection) signIn(c *gin.Context) {
type signInRequest struct {
username string
password string
}
var request signInRequest
err := json.NewDecoder(c.Request.Body).Decode(&request)
if err != nil {
c.AbortWithError(500, err)
}
var userItem user.User
err = con.connection.Database("Backend").Collection("Users").FindOne(context.TODO(), bson.D{{Key: "username", Value: request.username}}).Decode(&userItem)
if err != nil {
c.AbortWithError(403, err)
}
if userItem.hashedPass == hash.Hash64() {
}
signedToken, err := signToken(token)
if err != nil {
c.AbortWithError(500, err)
}
c.SetCookie("auth", signedToken, -1, "", "", false, false)
c.IndentedJSON(http.StatusOK, signedToken)
}
func (con Connection) test(c *gin.Context) {
claims, exists := c.Get("claims")
if !exists {
fmt.Println("No Claims")
c.AbortWithStatus(403)
}
c.IndentedJSON(http.StatusOK, claims)
}
func LoadGroup(group *gin.RouterGroup, client *mongo.Client) {
connection := Connection{connection: client}
group.POST("/signup", connection.signUp)
group.Use(AuthorizedTo(Admin))
{
group.GET("/test", connection.test)
}
}

2
go.mod
View File

@ -9,10 +9,12 @@ require (
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect
github.com/gabriel-vasile/mimetype v1.4.2 // indirect
github.com/gin-contrib/sse v0.1.0 // indirect
github.com/go-oas/docs v1.1.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.14.0 // indirect
github.com/goccy/go-json v0.10.2 // indirect
github.com/golang-jwt/jwt v3.2.2+incompatible // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.2.4 // indirect
github.com/leodido/go-urn v1.2.4 // indirect

4
go.sum
View File

@ -12,6 +12,8 @@ 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.9.1 h1:4idEAncQnU5cB7BeOkPtxjfCSye0AAm1R0RVIqJ+Jmg=
github.com/gin-gonic/gin v1.9.1/go.mod h1:hPrL7YrpYKXt5YId3A/Tnip5kqbEAP+KLuI3SUcPTeU=
github.com/go-oas/docs v1.1.0 h1:XKyq37JX50ig//ffA/nhssj5TjUHNkRvhTbTC4aSbZE=
github.com/go-oas/docs v1.1.0/go.mod h1:D0KIPMVoqhr7gCAQxiVYedIWkVyi1dmUl5H3SiCmWrM=
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=
@ -20,6 +22,8 @@ github.com/go-playground/validator/v10 v10.14.0 h1:vgvQWe3XCz3gIeFDm/HnTIbj6UGmg
github.com/go-playground/validator/v10 v10.14.0/go.mod h1:9iXMNT7sEkjXb0I+enO7QXmzG6QCsPWY4zveKFVRSyU=
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/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY=
github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I=
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=

View File

@ -1,6 +1,9 @@
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.15.0/go.mod h1:BDl952bC7+uMoWR75FIrCDx79TPU9oHkTZ9yRbYOrX0=
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=

View File

@ -3,6 +3,7 @@ package main
import (
"context"
"acooldomain.co/backend/auth"
"acooldomain.co/backend/dbhandler"
"acooldomain.co/backend/users"
"github.com/gin-gonic/gin"
@ -22,6 +23,7 @@ func main() {
panic(err)
}
users.LoadGroup(router.Group("/users"), client)
auth.LoadGroup(router.Group("/auth"), client)
router.Run("localhost:8080")
}

View File

@ -4,28 +4,18 @@ import (
"context"
"net/http"
"acooldomain.co/backend/auth"
"github.com/gin-gonic/gin"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
)
type Permission int
const (
Start Permission = 1 << iota
Stop
Browse
Create
Delete
RunCommand
Admin
)
type User struct {
Username string `json:"username"`
Email string `json:"email"`
MaxOwnedServers int `json:"maxed_owned_servers"`
Permissions []string `json:"permissions"`
Permissions auth.Permission `json:"permissions"`
HashedPass auth.Permission `json:"hashedPass"`
}
type Connection struct {
@ -50,5 +40,5 @@ func (con Connection) GetUsers(c *gin.Context) {
func LoadGroup(group *gin.RouterGroup, client *mongo.Client) {
connection := Connection{connection: client}
group.GET("/", connection.GetUsers)
group.Use(auth.AuthorizedTo(0)).GET("/", connection.GetUsers)
}