Encrypted messaging app
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123 lines
2.7 KiB

package Database
import (
"errors"
"github.com/gofrs/uuid"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
// BeforeUpdate prevents updating the username or email if it has not changed
// This stops a unique constraint error
func (u *User) BeforeUpdate(tx *gorm.DB) (err error) {
if !tx.Statement.Changed("Username") {
tx.Statement.Omit("Username")
}
if !tx.Statement.Changed("Email") {
tx.Statement.Omit("Email")
}
return nil
}
// User holds user data
type User struct {
Base
Username string `gorm:"not null;unique" json:"username"`
Password string `gorm:"not null" json:"password"`
ConfirmPassword string `gorm:"-" json:"confirm_password"`
Email string ` json:"email"`
AsymmetricPrivateKey string `gorm:"not null" json:"asymmetric_private_key"` // Stored encrypted
AsymmetricPublicKey string `gorm:"not null" json:"asymmetric_public_key"`
SymmetricKey string `gorm:"not null" json:"symmetric_key"` // Stored encrypted
AttachmentID *uuid.UUID ` json:"attachment_id"`
Attachment Attachment ` json:"attachment"`
MessageExpiryDefault MessageExpiry `gorm:"default:no_expiry" json:"-" sql:"type:ENUM('fifteen_min', 'thirty_min', 'one_hour', 'three_hour', 'six_hour', 'twelve_hour', 'one_day', 'three_day', 'no_expiry')"` // Stored encrypted
}
func GetUserById(id string) (User, error) {
var (
user User
err error
)
err = DB.Preload(clause.Associations).
First(&user, "id = ?", id).
Error
return user, err
}
func GetUserByUsername(username string) (User, error) {
var (
user User
err error
)
err = DB.Preload(clause.Associations).
First(&user, "username = ?", username).
Error
return user, err
}
func CheckUniqueUsername(username string) error {
var (
exists bool
err error
)
err = DB.Model(User{}).
Select("count(*) > 0").
Where("username = ?", username).
Find(&exists).
Error
if err != nil {
return err
}
if exists {
return errors.New("Invalid username")
}
return nil
}
func (user *User) CreateUser() error {
var err error
err = DB.Session(&gorm.Session{FullSaveAssociations: true}).
Create(user).
Error
return err
}
func (user *User) UpdateUser() error {
var err error
err = DB.Model(&user).
Omit("id").
Where("id = ?", user.ID.String()).
Updates(user).
Error
if err != nil {
return err
}
err = DB.Model(User{}).
Where("id = ?", user.ID.String()).
First(user).
Error
return err
}
func (user *User) DeleteUser() error {
return DB.Session(&gorm.Session{FullSaveAssociations: true}).
Delete(user).
Error
}