Login, JWT and auth overstructure

* Signup -> Login -> JWT-Doot flow now works for users
* Administrators cannot currently sign up for obvious reasons
* Segmented the main.go methods into a core controller package
This commit is contained in:
🐙PiperYxzzy
2022-05-01 12:31:41 +02:00
parent 6db02148ea
commit 8ab45e2401
6 changed files with 231 additions and 162 deletions

View File

@@ -11,7 +11,7 @@ import (
type Admin struct {
Auth
Email string
Email string `gorm:"unique" sql:"index"`
}
const adminJwtDuration = time.Hour * 2
@@ -19,11 +19,10 @@ const adminJwtDuration = time.Hour * 2
var adminHmac = util.GenerateHmac()
func (a *Admin) GetJwt() (string, int) {
exp := time.Now().Add(adminJwtDuration)
j := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"sub": a.Uid.String(),
"iat": time.Now(),
"exp": exp,
"iat": time.Now().Unix(),
"exp": time.Now().Add(adminJwtDuration).Unix(),
"role": "admin",
})

View File

@@ -1,6 +1,7 @@
package models
import (
"errors"
"time"
"github.com/google/uuid"
@@ -12,7 +13,7 @@ type Base struct {
Created time.Time
Updated time.Time
Deleted time.Time `sql:"index"`
Tenant uuid.UUID
Tenant uuid.UUID `sql:"index"`
}
func (b *Base) BeforeCreate(scope *gorm.DB) error {
@@ -21,7 +22,11 @@ func (b *Base) BeforeCreate(scope *gorm.DB) error {
return nil
}
func (b *Base) BeforeSave(tx *gorm.DB) error {
func (b *Base) BeforeSave(scope *gorm.DB) error {
if b.Tenant == uuid.Nil {
return errors.New("cannot save an untenanted object")
}
b.Updated = time.Now()
return nil
}

View File

@@ -11,24 +11,23 @@ import (
type User struct {
Auth
Email string `gorm:"unique"`
Email string `gorm:"unique" sql:"index"`
}
const userJwtDuration = time.Hour * 24
var userHmac = util.GenerateHmac()
var UserHmac = util.GenerateHmac()
func (u *User) GetJwt() (string, int) {
exp := time.Now().Add(userJwtDuration)
j := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"sub": u.Uid.String(),
"iat": time.Now(),
"exp": exp,
"iat": time.Now().Unix(),
"exp": time.Now().Add(userJwtDuration).Unix(),
"role": "user",
"tid": u.Tenant.String(),
})
jstr, err := j.SignedString(userHmac)
jstr, err := j.SignedString(UserHmac)
if err != nil {
// we should ALWAYS be able to build and sign a str
panic(err)