Adding models, DB access, signup, login

* Created Base, Auth, User and Admin models
* Added skeleton API structure containing: User signup, User & Admin
login, authorized zones, ping tests
* Simple user signup functional
* Skeleton user login functional, no means to verify as of yet
* Added POSTMAN file
This commit is contained in:
🐙PiperYxzzy
2022-04-29 23:50:55 +02:00
parent b74158a7a5
commit 47ac0cdc07
10 changed files with 508 additions and 2 deletions

24
models/admin.go Normal file
View File

@@ -0,0 +1,24 @@
package models
import (
"errors"
"github.com/yxzzy-wtf/gin-gonic-prepack/database"
)
type Admin struct {
Auth
Email string
}
func (a *Admin) GetJwt() (string, int) {
return "", 0
}
func (a *Admin) ByEmail(email string) error {
if err := database.Db.Where("email = ?", email).First(&a).Error; err != nil {
return errors.New("not found")
}
return nil
}

43
models/auth.go Normal file
View File

@@ -0,0 +1,43 @@
package models
import (
"errors"
"time"
"golang.org/x/crypto/bcrypt"
)
type Auth struct {
Base
PasswordHash string
TwoFactorSecret string
TwoFactorRecovery string
Verified bool
}
func (a *Auth) SetPassword(pass string) error {
passHash, _ := bcrypt.GenerateFromPassword([]byte(pass), bcrypt.DefaultCost)
a.PasswordHash = string(passHash)
return nil
}
func (a *Auth) CheckPassword(pass string) error {
return bcrypt.CompareHashAndPassword([]byte(a.PasswordHash), []byte(pass))
}
func (a *Auth) ValidateTwoFactor(tfCode string, stamp time.Time) error {
if tfCode == "" && a.TwoFactorSecret != "" {
return errors.New("requires 2FA")
} else if tfCode == "" && a.TwoFactorSecret == "" {
return nil
}
//TODO two factor
if len(tfCode) == 6 {
// Test 2FA
return errors.New("2FA invalid")
} else {
// May be a renewal code
return errors.New("unlock invalid")
}
}

31
models/base.go Normal file
View File

@@ -0,0 +1,31 @@
package models
import (
"time"
"github.com/google/uuid"
"gorm.io/gorm"
)
type Base struct {
Uid uuid.UUID `gorm:"type:uuid;primary_key;"`
Created time.Time
Updated time.Time
Deleted time.Time `sql:"index"`
Tenant uuid.UUID
}
func (b *Base) BeforeCreate(scope *gorm.DB) error {
b.Uid = uuid.New()
b.Created = time.Now()
return nil
}
func (b *Base) BeforeSave(tx *gorm.DB) error {
b.Updated = time.Now()
return nil
}
func (b *Base) Delete() {
b.Deleted = time.Now()
}

24
models/user.go Normal file
View File

@@ -0,0 +1,24 @@
package models
import (
"errors"
"github.com/yxzzy-wtf/gin-gonic-prepack/database"
)
type User struct {
Auth
Email string `gorm:"unique"`
}
func (u *User) GetJwt() (string, int) {
return "", 0
}
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
}