Building and returning JWTs on login
* Created Util package for assorted items * Currently generates an HMAC key on startup, to be changed * JWT also includes login role
This commit is contained in:
@@ -2,8 +2,11 @@ package models
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt"
|
||||
"github.com/yxzzy-wtf/gin-gonic-prepack/database"
|
||||
"github.com/yxzzy-wtf/gin-gonic-prepack/util"
|
||||
)
|
||||
|
||||
type Admin struct {
|
||||
@@ -11,8 +14,26 @@ type Admin struct {
|
||||
Email string
|
||||
}
|
||||
|
||||
const adminJwtDuration = time.Hour * 2
|
||||
|
||||
var adminHmac = util.GenerateHmac()
|
||||
|
||||
func (a *Admin) GetJwt() (string, int) {
|
||||
return "", 0
|
||||
exp := time.Now().Add(adminJwtDuration)
|
||||
j := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
|
||||
"sub": a.Uid.String(),
|
||||
"iat": time.Now(),
|
||||
"exp": exp,
|
||||
"role": "admin",
|
||||
})
|
||||
|
||||
jstr, err := j.SignedString(adminHmac)
|
||||
if err != nil {
|
||||
// we should ALWAYS be able to build and sign a str
|
||||
panic(err)
|
||||
}
|
||||
|
||||
return jstr, int(adminJwtDuration.Seconds())
|
||||
}
|
||||
|
||||
func (a *Admin) ByEmail(email string) error {
|
||||
|
||||
@@ -2,8 +2,11 @@ package models
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt"
|
||||
"github.com/yxzzy-wtf/gin-gonic-prepack/database"
|
||||
"github.com/yxzzy-wtf/gin-gonic-prepack/util"
|
||||
)
|
||||
|
||||
type User struct {
|
||||
@@ -11,8 +14,27 @@ type User struct {
|
||||
Email string `gorm:"unique"`
|
||||
}
|
||||
|
||||
const userJwtDuration = time.Hour * 24
|
||||
|
||||
var userHmac = util.GenerateHmac()
|
||||
|
||||
func (u *User) GetJwt() (string, int) {
|
||||
return "", 0
|
||||
exp := time.Now().Add(userJwtDuration)
|
||||
j := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
|
||||
"sub": u.Uid.String(),
|
||||
"iat": time.Now(),
|
||||
"exp": exp,
|
||||
"role": "user",
|
||||
"tid": u.Tenant.String(),
|
||||
})
|
||||
|
||||
jstr, err := j.SignedString(userHmac)
|
||||
if err != nil {
|
||||
// we should ALWAYS be able to build and sign a str
|
||||
panic(err)
|
||||
}
|
||||
|
||||
return jstr, int(userJwtDuration.Seconds())
|
||||
}
|
||||
|
||||
func (u *User) ByEmail(email string) error {
|
||||
|
||||
12
util/util.go
Normal file
12
util/util.go
Normal file
@@ -0,0 +1,12 @@
|
||||
package util
|
||||
|
||||
import "crypto/rand"
|
||||
|
||||
func GenerateHmac() []byte {
|
||||
b := make([]byte, 64)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
return b
|
||||
}
|
||||
Reference in New Issue
Block a user