services
This commit is contained in:
@@ -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))
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user