initial commit
This commit is contained in:
91
app/utils.go
Normal file
91
app/utils.go
Normal file
@@ -0,0 +1,91 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
func encodeURL(user User) string {
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
|
||||
"id": user.ID, "name": user.Username, "pass": user.Password,
|
||||
})
|
||||
tokenString, err := token.SignedString([]byte(os.Getenv("JWT_SECRET")))
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
tokenString = base64.RawURLEncoding.EncodeToString([]byte(tokenString))
|
||||
return tokenString
|
||||
}
|
||||
func decodeURL(tokenString string) (User, error) {
|
||||
var zero User
|
||||
tokenBytes, err := base64.RawURLEncoding.DecodeString(tokenString)
|
||||
if err != nil {
|
||||
return zero, err
|
||||
}
|
||||
token, err := jwt.Parse(string(tokenBytes), func(token *jwt.Token) (interface{}, error) {
|
||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
|
||||
}
|
||||
return []byte(os.Getenv("JWT_SECRET")), nil
|
||||
})
|
||||
if err != nil {
|
||||
return zero, err
|
||||
}
|
||||
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
|
||||
id := int(claims["id"].(float64))
|
||||
name := claims["name"].(string)
|
||||
pass := claims["pass"].(string)
|
||||
return User{ID: id, Username: name, Password: pass}, nil
|
||||
}
|
||||
return zero, nil
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
JWTSecret string
|
||||
Host string
|
||||
Port string
|
||||
ObfsPassword string
|
||||
SNI string
|
||||
NameFormat string
|
||||
}
|
||||
|
||||
var cfg *Config
|
||||
|
||||
func LoadConfig() {
|
||||
cfg = &Config{
|
||||
JWTSecret: os.Getenv("JWT_SECRET"),
|
||||
Host: os.Getenv("HOST"),
|
||||
Port: os.Getenv("PORT"),
|
||||
ObfsPassword: os.Getenv("OBFS_PASSWORD"),
|
||||
SNI: os.Getenv("SNI"),
|
||||
NameFormat: os.Getenv("NAME_FORMAT"),
|
||||
}
|
||||
}
|
||||
|
||||
var ip string
|
||||
|
||||
func LoadIP() {
|
||||
res, err := http.Get("https://api.ipify.org")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
defer res.Body.Close()
|
||||
data, err := io.ReadAll(res.Body)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
ip = string(data)
|
||||
log.Println(ip)
|
||||
}
|
||||
func formatConfigName(format string, user User) string {
|
||||
s := strings.ReplaceAll(format, "{username}", user.Username)
|
||||
s = strings.ReplaceAll(s, "{host}", ip)
|
||||
return s
|
||||
}
|
||||
Reference in New Issue
Block a user