This commit is contained in:
2026-08-26 11:01:46 +03:00
parent 34a798d345
commit 4bd1512994
712 changed files with 538122 additions and 0 deletions
+28
View File
@@ -0,0 +1,28 @@
package auth
import (
"crypto/sha256"
"fmt"
)
var Salt = ""
func SetSalt(s string) {
Salt = s
}
func Validate(id string, hash string) bool {
return Generate(id) == hash
}
func Generate(id string) string {
return hashSha(Salt, id)
}
func hashSha(strings ...string) string {
h := sha256.New()
for _, s := range strings {
h.Write([]byte(s))
}
return fmt.Sprintf("%x", h.Sum(nil))
}
+36
View File
@@ -0,0 +1,36 @@
package auth
import (
"github.com/labstack/echo"
"net/http"
"strconv"
)
const HashCookieName = "hash"
const IdCookieName = "user_id"
func Cookies(id int64) (*http.Cookie, *http.Cookie) {
ids := strconv.FormatInt(id, 10)
return &http.Cookie{Value: ids, Name: IdCookieName}, &http.Cookie{Value: Generate(ids), Name: HashCookieName}
}
type Context struct {
echo.Context
}
func (uc *Context) GetId() (uid int64) {
idc, err := uc.Cookie(IdCookieName)
if err != nil {
return
}
hashc, err := uc.Cookie(HashCookieName)
if err != nil {
return
}
v, err := strconv.ParseInt(idc.Value, 10, 64)
if Validate(idc.Value, hashc.Value) && err == nil {
uid = v
}
return
}
@@ -0,0 +1,16 @@
package auth
import (
"github.com/labstack/echo"
"net/http"
)
func RequiredMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
ac := c.(*Context)
if ac == nil || ac.GetId() == 0 {
return c.Redirect(http.StatusFound, "/login")
}
return next(c)
}
}