Files
gin-gonic-prepack/models/user.go
🐙PiperYxzzy 8ab45e2401 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
2022-05-01 12:31:41 +02:00

46 lines
930 B
Go

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 {
Auth
Email string `gorm:"unique" sql:"index"`
}
const userJwtDuration = time.Hour * 24
var UserHmac = util.GenerateHmac()
func (u *User) GetJwt() (string, int) {
j := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"sub": u.Uid.String(),
"iat": time.Now().Unix(),
"exp": time.Now().Add(userJwtDuration).Unix(),
"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 {
if err := database.Db.Where("email = ?", email).First(&u).Error; err != nil {
return errors.New("not found")
}
return nil
}