feat: add user management system with roles and permissions
Some checks failed
/ build ushare (push) Failing after 1m40s
/ clean (push) Successful in 2s

- Introduce SQLite persistence via GORM (stored at <data>/.ushare.db)
- Add Role model with two built-in roles: admin (all perms) and user (upload only)
- Add three permissions: user_manage, upload, token_manage (reserved)
- Rewrite UserManager: DB-backed login with in-memory session tokens
- Auto-seed default roles and admin user on first startup
- Add AuthPermission middleware for fine-grained permission checks
- Add /api/uauth/me endpoint for current session info
- Add /api/admin/* CRUD routes for user and role management
- Add admin console page (/admin) with user table and role permissions view
- Show admin console link in share page for users with user_manage permission

🤖 Generated with [Qoder][https://qoder.com]
This commit is contained in:
loveuer
2026-02-27 19:40:31 -08:00
parent 909a016a44
commit 5f187bb5d6
13 changed files with 1119 additions and 93 deletions

44
internal/model/role.go Normal file
View File

@@ -0,0 +1,44 @@
package model
import (
"strings"
"time"
)
const (
PermUserManage = "user_manage"
PermUpload = "upload"
PermTokenManage = "token_manage"
RoleAdmin = "admin"
RoleUser = "user"
)
type Role struct {
ID uint `gorm:"primarykey" json:"id"`
Name string `gorm:"uniqueIndex;not null" json:"name"`
Label string `gorm:"not null" json:"label"`
Permissions string `gorm:"not null" json:"permissions"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
func (r *Role) HasPermission(perm string) bool {
for _, p := range r.PermissionList() {
if p == perm {
return true
}
}
return false
}
func (r *Role) PermissionList() []string {
list := make([]string, 0)
for _, p := range strings.Split(r.Permissions, ",") {
p = strings.TrimSpace(p)
if p != "" {
list = append(list, p)
}
}
return list
}

View File

@@ -1,10 +1,27 @@
package model
import "time"
// User is the GORM database model for persistent user storage.
type User struct {
Id int `json:"id"`
Username string `json:"username"`
Key string `json:"key"`
Password string `json:"-"`
LoginAt int64 `json:"login_at"`
Token string `json:"token"`
ID uint `gorm:"primarykey" json:"id"`
Username string `gorm:"uniqueIndex;not null" json:"username"`
Password string `gorm:"not null" json:"-"`
RoleID uint `gorm:"not null" json:"role_id"`
Role Role `gorm:"foreignKey:RoleID" json:"role"`
Active bool `gorm:"default:true" json:"active"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
// Session is the in-memory representation of an authenticated user.
// It is created on login and stored in the UserManager session map.
type Session struct {
UserID uint `json:"user_id"`
Username string `json:"username"`
Role string `json:"role"`
RoleLabel string `json:"role_label"`
Permissions []string `json:"permissions"`
LoginAt int64 `json:"login_at"`
Token string `json:"token"`
}