sum7/warehost
sum7
/
warehost
Archived
1
0
Fork 0
This repository has been archived on 2020-09-27. You can view files and clone it, but cannot push or open issues or pull requests.
warehost/system/models.go

85 lines
2.4 KiB
Go

package system
import (
"time"
"github.com/jinzhu/gorm"
liblog "dev.sum7.eu/sum7/warehost/lib/log"
libpassword "dev.sum7.eu/sum7/warehost/lib/password"
)
// MINPASSWORDLENTH to validate password
const MINPASSWORDLENTH = 3
/*
* API Model
*/
// RequestLogin for api request to log in
type RequestLogin struct {
Username string `json:"username"`
Password string `json:"password"`
Superadmin bool `json:"superadmin,oemitempty"`
}
// ChangePasswordRequest for api request of a new password
type ChangePasswordRequest struct {
CurrentPassword string `json:"currentpassword"`
NewPassword string `json:"newpassword"`
}
/*
* Database Model
*/
// Login found
type Login struct {
ID int64
Username string `gorm:"type:varchar(255);unique;column:mail" json:"username"`
Password string `gorm:"type:varchar(255);column:password" json:"-"`
Active bool `gorm:"default:false;column:active" json:"active"`
Code string `gorm:"type:varchar(255);column:code" json:"-"`
Superadmin bool `gorm:"default:false;column:superadmin" json:"superadmin"`
CreateAt time.Time `sql:"default:current_timestamp" gorm:"column:createat" json:"createat"`
LastLoginAt time.Time `gorm:"column:lastloginat" json:"lastloginat"`
Invites []Invite `gorm:"foreignkey:Login" json:"invites"`
}
// Invite struct
type Invite struct {
LoginID int64 `sql:"type:bigint REFERENCES login(id) ON UPDATE CASCADE ON DELETE CASCADE;column:login;primary_key"`
Login Login `gorm:"column:login" json:"login"`
InvitedID int64 `sql:"type:bigint REFERENCES login(id) ON UPDATE CASCADE ON DELETE CASCADE;column:invited;primary_key"`
Invited Login `gorm:"column:invited" json:"invited"`
Admin bool `sql:"default:false" json:"admin"`
}
// GetInvitedby of current login -> Invitor
func (l *Login) GetInvitedby(dbconnection *gorm.DB) (invited Invite) {
invited = Invite{InvitedID: l.ID}
dbconnection.Where("invited = ?", invited.InvitedID).First(&invited)
return
}
// SyncModels to verify the database schema
func SyncModels(dbconnection *gorm.DB) {
dbconnection.AutoMigrate(&Login{}, &Invite{})
var result int64
dbconnection.Model(&Login{}).Count(&result)
if result <= 0 {
login := &Login{
Username: "root",
Active: true,
Superadmin: true,
Password: libpassword.NewHash("root"),
}
dbconnection.Create(login)
liblog.Log.Error("have to create \"login\"")
} else {
liblog.Log.Info("Connection to \"login\" works")
}
}