95 lines
1.7 KiB
Go
95 lines
1.7 KiB
Go
package helpers
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"log"
|
|
"main/db"
|
|
"main/models"
|
|
"sort"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/golang-jwt/jwt/v4"
|
|
"go.mongodb.org/mongo-driver/bson"
|
|
)
|
|
|
|
func JoinNodeSelector(m map[string]string) string {
|
|
if len(m) == 0 {
|
|
return ""
|
|
}
|
|
keys := make([]string, 0, len(m))
|
|
for k := range m {
|
|
keys = append(keys, k)
|
|
}
|
|
sort.Strings(keys)
|
|
|
|
parts := make([]string, 0, len(keys))
|
|
for _, k := range keys {
|
|
parts = append(parts, k+"="+m[k])
|
|
}
|
|
return strings.Join(parts, ",")
|
|
}
|
|
|
|
// human prints like 3d4h5m (compact)
|
|
func Human(d time.Duration) string {
|
|
if d < 0 {
|
|
d = -d
|
|
}
|
|
d = d.Round(time.Second)
|
|
|
|
days := int(d / (24 * time.Hour))
|
|
d -= time.Duration(days) * 24 * time.Hour
|
|
|
|
hours := int(d / time.Hour)
|
|
d -= time.Duration(hours) * time.Hour
|
|
|
|
mins := int(d / time.Minute)
|
|
d -= time.Duration(mins) * time.Minute
|
|
|
|
secs := int(d / time.Second)
|
|
|
|
if days > 0 {
|
|
if mins > 0 {
|
|
return fmt.Sprintf("%dd%dm", days, mins)
|
|
}
|
|
return fmt.Sprintf("%dd", days)
|
|
}
|
|
if hours > 0 {
|
|
if mins > 0 {
|
|
return fmt.Sprintf("%dh%dm", hours, mins)
|
|
}
|
|
return fmt.Sprintf("%dh", hours)
|
|
}
|
|
if mins > 0 {
|
|
return fmt.Sprintf("%dm", mins)
|
|
}
|
|
return fmt.Sprintf("%ds", secs)
|
|
}
|
|
|
|
var jwtKey = []byte("mysecret123")
|
|
|
|
func DecodeJwt(tokenString *string, user *models.User) {
|
|
claims := jwt.MapClaims{}
|
|
_, err := jwt.ParseWithClaims(*tokenString, claims, func(token *jwt.Token) (interface{}, error) {
|
|
return []byte(jwtKey), nil
|
|
})
|
|
|
|
if err != nil {
|
|
log.Println(err)
|
|
return
|
|
}
|
|
|
|
user.Username = claims["username"].(string)
|
|
}
|
|
|
|
func ValidateUser(user string) error {
|
|
count, err := db.UserCollection.CountDocuments(context.TODO(), bson.M{"username": user})
|
|
|
|
if err != nil || count <= 0 {
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|