95 lines
2.0 KiB
Go
95 lines
2.0 KiB
Go
package keys
|
|
|
|
import (
|
|
"clortho/lib/db"
|
|
"errors"
|
|
)
|
|
|
|
// GetKeys retrieves all keys
|
|
func GetKeys() []db.Key {
|
|
var keys []db.Key
|
|
db.Connection.Preload("User").Find(&keys)
|
|
return keys
|
|
}
|
|
|
|
// GetKeysByUser retrieves all keys for a specific user
|
|
func GetKeysByUser(userID uint) []db.Key {
|
|
var keys []db.Key
|
|
db.Connection.Preload("User").Where("user_id = ?", userID).Find(&keys)
|
|
return keys
|
|
}
|
|
|
|
// GetKey retrieves a specific key by ID
|
|
func GetKey(id uint) (*db.Key, error) {
|
|
var key db.Key
|
|
result := db.Connection.Preload("User").First(&key, id)
|
|
if result.RowsAffected == 0 {
|
|
return nil, errors.New("key not found")
|
|
}
|
|
return &key, nil
|
|
}
|
|
|
|
// CreateKey creates a new key for a user
|
|
func CreateKey(userID uint, name string, content string) (*db.Key, error) {
|
|
key := db.Key{
|
|
UserID: userID,
|
|
Name: name,
|
|
Content: content,
|
|
}
|
|
result := db.Connection.Create(&key)
|
|
if result.Error != nil {
|
|
return nil, result.Error
|
|
}
|
|
|
|
// Reload the key to get the User relationship
|
|
db.Connection.Preload("User").First(&key, key.ID)
|
|
return &key, nil
|
|
}
|
|
|
|
// UpdateKey updates an existing key
|
|
func UpdateKey(id uint, name string, content string) (*db.Key, error) {
|
|
key, err := GetKey(id)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
key.Name = name
|
|
key.Content = content
|
|
result := db.Connection.Save(key)
|
|
if result.Error != nil {
|
|
return nil, result.Error
|
|
}
|
|
return key, nil
|
|
}
|
|
|
|
// DeleteKey deletes a key
|
|
func DeleteKey(id uint) error {
|
|
result := db.Connection.Delete(&db.Key{}, id)
|
|
if result.RowsAffected == 0 {
|
|
return errors.New("key not found")
|
|
}
|
|
return result.Error
|
|
}
|
|
|
|
// CanAccessKey checks if a user can access a key (admin or owner)
|
|
func CanAccessKey(userID uint, keyID uint) (bool, error) {
|
|
key, err := GetKey(keyID)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
|
|
// Check if user is the owner of the key
|
|
if key.UserID == userID {
|
|
return true, nil
|
|
}
|
|
|
|
// Check if user is an admin
|
|
var user db.User
|
|
result := db.Connection.First(&user, userID)
|
|
if result.RowsAffected == 0 {
|
|
return false, errors.New("user not found")
|
|
}
|
|
|
|
return user.Admin, nil
|
|
}
|