fix(user_store): add checking and move some common vars

This commit is contained in:
hexxa 2022-03-24 14:46:22 +08:00 committed by Hexxa
parent c3a3b2dc5b
commit b7609e6c06
17 changed files with 567 additions and 560 deletions

View file

@ -9,20 +9,72 @@ import (
const (
SchemaV2 = "v2" // add size to file info
UsersNs = "users"
InfoNs = "sharing"
ShareIDNs = "sharingKey"
UserSchemaNs = "UserSchemaNs"
UserIDsNs = "UserIDsNs"
UsersNs = "UsersNs"
RolesNs = "RolesNs"
InfoNs = "InfoNs"
ShareIDNs = "ShareIDNs"
uploadsPrefix = "uploads"
KeyInitTime = "keyInitTime"
AdminRole = "admin"
UserRole = "user"
VisitorRole = "visitor"
)
var (
ErrBucketNotFound = errors.New("bucket not found")
ErrKeyNotFound = errors.New("key not found")
ErrCreateExisting = errors.New("create upload info which already exists")
ErrQuota = errors.New("quota limit reached")
ErrInvalidUser = errors.New("invalid user")
ErrInvalidQuota = errors.New("invalid quota")
ErrInvalidPreferences = errors.New("invalid preferences")
ErrBucketNotFound = errors.New("bucket not found")
ErrKeyNotFound = errors.New("key not found")
ErrCreateExisting = errors.New("create upload info which already exists")
ErrQuota = errors.New("quota limit reached")
DefaultSiteName = "Quickshare"
DefaultSiteDesc = "Quickshare"
DefaultBgConfig = &BgConfig{
Repeat: "repeated",
Position: "top",
Align: "fixed",
BgColor: "#ccc",
}
BgRepeatValues = map[string]bool{
"repeat-x": true,
"repeat-y": true,
"repeat": true,
"space": true,
"round": true,
"no-repeat": true,
}
BgAlignValues = map[string]bool{
"scroll": true,
"fixed": true,
"local": true,
}
BgPositionValues = map[string]bool{
"top": true,
"bottom": true,
"left": true,
"right": true,
"center": true,
}
DefaultCSSURL = ""
DefaultLanPackURL = ""
DefaultLan = "en_US"
DefaultTheme = "light"
DefaultAvatar = ""
DefaultEmail = ""
DefaultSpaceLimit = int64(1024 * 1024 * 1024) // 1GB
DefaultUploadSpeedLimit = 50 * 1024 * 1024 // 50MB
DefaultDownloadSpeedLimit = 50 * 1024 * 1024 // 50MB
VisitorUploadSpeedLimit = 10 * 1024 * 1024 // 10MB
VisitorDownloadSpeedLimit = 10 * 1024 * 1024 // 10MB
)
type FileInfo struct {
@ -33,20 +85,30 @@ type FileInfo struct {
Size int64 `json:"size"`
}
type UserCfg struct {
Name string `json:"name" yaml:"name"`
Role string `json:"role" yaml:"role"`
Pwd string `json:"pwd" yaml:"pwd"`
}
type Quota struct {
SpaceLimit int64 `json:"spaceLimit,string"`
UploadSpeedLimit int `json:"uploadSpeedLimit"`
DownloadSpeedLimit int `json:"downloadSpeedLimit"`
SpaceLimit int64 `json:"spaceLimit,string" yaml:"spaceLimit,string"`
UploadSpeedLimit int `json:"uploadSpeedLimit" yaml:"uploadSpeedLimit"`
DownloadSpeedLimit int `json:"downloadSpeedLimit" yaml:"downloadSpeedLimit"`
}
type Preferences struct {
Bg *BgConfig `json:"bg"`
CSSURL string `json:"cssURL"`
LanPackURL string `json:"lanPackURL"`
Lan string `json:"lan"`
Theme string `json:"theme"`
Avatar string `json:"avatar"`
Email string `json:"email"`
Bg *BgConfig `json:"bg" yaml:"bg"`
CSSURL string `json:"cssURL" yaml:"cssURL"`
LanPackURL string `json:"lanPackURL" yaml:"lanPackURL"`
Lan string `json:"lan" yaml:"lan"`
Theme string `json:"theme" yaml:"theme"`
Avatar string `json:"avatar" yaml:"avatar"`
Email string `json:"email" yaml:"email"`
}
type SiteConfig struct {
ClientCfg *ClientConfig `json:"clientCfg" yaml:"clientCfg"`
}
type ClientConfig struct {
@ -63,6 +125,22 @@ type BgConfig struct {
BgColor string `json:"bgColor" yaml:"bgColor"`
}
type User struct {
ID uint64 `json:"id,string" yaml:"id,string"`
Name string `json:"name" yaml:"name"`
Pwd string `json:"pwd" yaml:"pwd"`
Role string `json:"role" yaml:"role"`
UsedSpace int64 `json:"usedSpace,string" yaml:"usedSpace,string"`
Quota *Quota `json:"quota" yaml:"quota"`
Preferences *Preferences `json:"preferences" yaml:"preferences"`
}
type UploadInfo struct {
RealFilePath string `json:"realFilePath" yaml:"realFilePath"`
Size int64 `json:"size" yaml:"size"`
Uploaded int64 `json:"uploaded" yaml:"uploaded"`
}
func ComparePreferences(p1, p2 *Preferences) bool {
return p1.CSSURL == p2.CSSURL &&
p1.LanPackURL == p2.LanPackURL &&
@ -73,22 +151,158 @@ func ComparePreferences(p1, p2 *Preferences) bool {
reflect.DeepEqual(p1.Bg, p2.Bg)
}
type User struct {
ID uint64 `json:"id,string"`
Name string `json:"name"`
Pwd string `json:"pwd"`
Role string `json:"role"`
UsedSpace int64 `json:"usedSpace,string"`
Quota *Quota `json:"quota"`
Preferences *Preferences `json:"preferences"`
}
type UploadInfo struct {
RealFilePath string `json:"realFilePath"`
Size int64 `json:"size"`
Uploaded int64 `json:"uploaded"`
}
func UploadNS(user string) string {
return fmt.Sprintf("%s/%s", uploadsPrefix, user)
}
func CheckSiteCfg(cfg *SiteConfig, fillDefault bool) error {
if cfg.ClientCfg == nil {
if !fillDefault {
return errors.New("cfg.ClientCfg not defined")
}
cfg.ClientCfg = &ClientConfig{
SiteName: DefaultSiteName,
SiteDesc: DefaultSiteDesc,
Bg: &BgConfig{
Url: DefaultBgConfig.Url,
Repeat: DefaultBgConfig.Repeat,
Position: DefaultBgConfig.Position,
Align: DefaultBgConfig.Align,
BgColor: DefaultBgConfig.BgColor,
},
}
return nil
}
if cfg.ClientCfg.SiteName == "" {
cfg.ClientCfg.SiteName = DefaultSiteName
}
if cfg.ClientCfg.SiteDesc == "" {
cfg.ClientCfg.SiteDesc = DefaultSiteDesc
}
if cfg.ClientCfg.Bg == nil {
if !fillDefault {
return errors.New("cfg.ClientCfg.Bg not defined")
}
cfg.ClientCfg.Bg = DefaultBgConfig
}
if err := CheckBgConfig(cfg.ClientCfg.Bg, fillDefault); err != nil {
return err
}
return nil
}
func CheckQuota(quota *Quota) error {
if quota.SpaceLimit < 0 {
return ErrInvalidQuota
}
if quota.UploadSpeedLimit < 0 {
return ErrInvalidQuota
}
if quota.DownloadSpeedLimit < 0 {
return ErrInvalidQuota
}
return nil
}
func CheckPreferences(prefers *Preferences, fillDefault bool) error {
if prefers.CSSURL == "" {
prefers.CSSURL = DefaultCSSURL
}
if prefers.LanPackURL == "" {
prefers.LanPackURL = DefaultLanPackURL
}
if prefers.Lan == "" {
if !fillDefault {
return ErrInvalidPreferences
}
prefers.Lan = DefaultLan
}
if prefers.Theme == "" {
if !fillDefault {
return ErrInvalidPreferences
}
prefers.Theme = DefaultTheme
}
if prefers.Avatar == "" {
prefers.Avatar = DefaultAvatar
}
if prefers.Email == "" {
if !fillDefault {
return ErrInvalidPreferences
}
prefers.Email = DefaultEmail
}
if prefers.Bg == nil {
if !fillDefault {
return ErrInvalidPreferences
}
prefers.Bg = DefaultBgConfig
}
if err := CheckBgConfig(prefers.Bg, fillDefault); err != nil {
return err
}
return nil
}
func CheckBgConfig(cfg *BgConfig, fillDefault bool) error {
if cfg.Url == "" && cfg.BgColor == "" {
if !fillDefault {
return errors.New("one of Bg.Url or Bg.BgColor must be defined")
}
cfg.BgColor = DefaultBgConfig.BgColor
}
if !BgRepeatValues[cfg.Repeat] {
return fmt.Errorf("invalid repeat value (%s)", cfg.Repeat)
}
if !BgPositionValues[cfg.Position] {
return fmt.Errorf("invalid position value (%s)", cfg.Position)
}
if !BgAlignValues[cfg.Align] {
return fmt.Errorf("invalid align value (%s)", cfg.Align)
}
if cfg.Repeat == "" {
cfg.Repeat = DefaultBgConfig.Repeat
}
if cfg.Position == "" {
cfg.Position = DefaultBgConfig.Position
}
if cfg.Align == "" {
cfg.Align = DefaultBgConfig.Align
}
if cfg.BgColor == "" {
cfg.BgColor = DefaultBgConfig.BgColor
}
return nil
}
func CheckUser(user User, fillDefault bool) error {
if user.ID == 0 && user.Role != AdminRole {
return ErrInvalidUser
}
// TODO: add length check
if user.Name == "" || user.Pwd == "" || user.Role == "" {
return ErrInvalidUser
}
if user.UsedSpace < 0 {
return ErrInvalidUser
}
if user.Quota == nil || user.Preferences == nil {
return ErrInvalidUser
}
var err error
if err = CheckQuota(user.Quota); err != nil {
return err
}
if err = CheckPreferences(user.Preferences, fillDefault); err != nil {
return err
}
return nil
}

View file

@ -14,28 +14,13 @@ const (
KeySiteCfg = "KeySiteCfg"
)
var (
DefaultSiteName = "Quickshare"
DefaultSiteDesc = "Quickshare"
DefaultBgConfig = &db.BgConfig{
Repeat: "repeated",
Position: "top",
Align: "fixed",
BgColor: "#ccc",
}
)
var (
ErrNotFound = errors.New("site config not found")
)
type ISiteStore interface {
SetClientCfg(cfg *db.ClientConfig) error
GetCfg() (*SiteConfig, error)
}
type SiteConfig struct {
ClientCfg *db.ClientConfig `json:"clientCfg" yaml:"clientCfg"`
GetCfg() (*db.SiteConfig, error)
}
type SiteStore struct {
@ -50,7 +35,7 @@ func NewSiteStore(store kvstore.IKVStore) (*SiteStore, error) {
}, nil
}
func (st *SiteStore) Init(cfg *SiteConfig) error {
func (st *SiteStore) Init(cfg *db.SiteConfig) error {
_, ok := st.store.GetStringIn(NsSite, KeySiteCfg)
if !ok {
var err error
@ -63,26 +48,26 @@ func (st *SiteStore) Init(cfg *SiteConfig) error {
return nil
}
func (st *SiteStore) getCfg() (*SiteConfig, error) {
func (st *SiteStore) getCfg() (*db.SiteConfig, error) {
cfgStr, ok := st.store.GetStringIn(NsSite, KeySiteCfg)
if !ok {
return nil, ErrNotFound
}
cfg := &SiteConfig{}
cfg := &db.SiteConfig{}
err := json.Unmarshal([]byte(cfgStr), cfg)
if err != nil {
return nil, err
}
if err = CheckCfg(cfg, true); err != nil {
if err = db.CheckSiteCfg(cfg, true); err != nil {
return nil, err
}
return cfg, nil
}
func (st *SiteStore) setCfg(cfg *SiteConfig) error {
if err := CheckCfg(cfg, false); err != nil {
func (st *SiteStore) setCfg(cfg *db.SiteConfig) error {
if err := db.CheckSiteCfg(cfg, false); err != nil {
return err
}
@ -106,64 +91,9 @@ func (st *SiteStore) SetClientCfg(cfg *db.ClientConfig) error {
return st.setCfg(siteCfg)
}
func (st *SiteStore) GetCfg() (*SiteConfig, error) {
func (st *SiteStore) GetCfg() (*db.SiteConfig, error) {
st.mtx.RLock()
defer st.mtx.RUnlock()
return st.getCfg()
}
func CheckCfg(cfg *SiteConfig, autoFill bool) error {
if cfg.ClientCfg == nil {
if !autoFill {
return errors.New("cfg.ClientCfg not defined")
}
cfg.ClientCfg = &db.ClientConfig{
SiteName: DefaultSiteName,
SiteDesc: DefaultSiteDesc,
Bg: &db.BgConfig{
Url: DefaultBgConfig.Url,
Repeat: DefaultBgConfig.Repeat,
Position: DefaultBgConfig.Position,
Align: DefaultBgConfig.Align,
BgColor: DefaultBgConfig.BgColor,
},
}
return nil
}
if cfg.ClientCfg.SiteName == "" {
cfg.ClientCfg.SiteName = DefaultSiteName
}
if cfg.ClientCfg.SiteDesc == "" {
cfg.ClientCfg.SiteDesc = DefaultSiteDesc
}
if cfg.ClientCfg.Bg == nil {
if !autoFill {
return errors.New("cfg.ClientCfg.Bg not defined")
}
cfg.ClientCfg.Bg = DefaultBgConfig
}
if cfg.ClientCfg.Bg.Url == "" && cfg.ClientCfg.Bg.BgColor == "" {
if !autoFill {
return errors.New("one of Bg.Url or Bg.BgColor must be defined")
}
cfg.ClientCfg.Bg.BgColor = DefaultBgConfig.BgColor
}
if cfg.ClientCfg.Bg.Repeat == "" {
cfg.ClientCfg.Bg.Repeat = DefaultBgConfig.Repeat
}
if cfg.ClientCfg.Bg.Position == "" {
cfg.ClientCfg.Bg.Position = DefaultBgConfig.Position
}
if cfg.ClientCfg.Bg.Align == "" {
cfg.ClientCfg.Bg.Align = DefaultBgConfig.Align
}
if cfg.ClientCfg.Bg.BgColor == "" {
cfg.ClientCfg.Bg.BgColor = DefaultBgConfig.BgColor
}
return nil
}

View file

@ -14,15 +14,15 @@ import (
func TestSiteStore(t *testing.T) {
testSiteMethods := func(t *testing.T, store ISiteStore) {
siteCfg := &SiteConfig{
siteCfg := &db.SiteConfig{
ClientCfg: &db.ClientConfig{
SiteName: "quickshare",
SiteDesc: "simpel file sharing",
Bg: &db.BgConfig{
Url: "/imgs/bg.jpg",
Repeat: "no-repeat",
Position: "fixed",
Align: "center",
Position: "center",
Align: "fixed",
BgColor: "#ccc",
},
},
@ -55,16 +55,16 @@ func TestSiteStore(t *testing.T) {
if err != nil {
t.Fatal("fail to new kvstore", err)
}
err = store.Init(&SiteConfig{
err = store.Init(&db.SiteConfig{
ClientCfg: &db.ClientConfig{
SiteName: "",
SiteDesc: "",
Bg: &db.BgConfig{
Url: "",
Repeat: "",
Position: "",
Align: "",
BgColor: "#ccc",
Url: "/imgs/bg.jpg",
Repeat: "repeat",
Position: "top",
Align: "scroll",
BgColor: "#000",
},
},
})

View file

@ -11,51 +11,29 @@ import (
"github.com/ihexxa/quickshare/src/kvstore"
)
// TODO: use sync.Pool instead
const (
AdminRole = "admin"
UserRole = "user"
VisitorRole = "visitor"
InitNs = "usersInit"
IDsNs = "ids"
RoleListNs = "roleList"
InitTimeKey = "initTime"
VisitorID = uint64(1)
VisitorName = "visitor"
defaultSpaceLimit = 1024 * 1024 * 1024 // 1GB
defaultUploadSpeedLimit = 50 * 1024 * 1024 // 50MB
defaultDownloadSpeedLimit = 50 * 1024 * 1024 // 50MB
visitorUploadSpeedLimit = 10 * 1024 * 1024 // 10MB
visitorDownloadSpeedLimit = 10 * 1024 * 1024 // 10MB
)
var (
ErrReachedLimit = errors.New("reached space limit")
ErrNotFound = errors.New("not found")
ErrReachedLimit = errors.New("reached space limit")
ErrUserNotFound = errors.New("user not found")
ErrNegtiveUsedSpace = errors.New("used space can not be negative")
DefaultPreferences = db.Preferences{
Bg: &db.BgConfig{
Url: "",
Repeat: "no-repeat",
Position: "center",
Align: "fixed",
BgColor: "#ccc",
},
CSSURL: "",
LanPackURL: "",
Lan: "en_US",
Theme: "light",
Avatar: "",
Email: "",
Bg: db.DefaultBgConfig,
CSSURL: db.DefaultCSSURL,
LanPackURL: db.DefaultLanPackURL,
Lan: db.DefaultLan,
Theme: db.DefaultTheme,
Avatar: db.DefaultAvatar,
Email: db.DefaultEmail,
}
)
type UserCfg struct {
Name string `json:"name" yaml:"name"`
Role string `json:"role" yaml:"role"`
Pwd string `json:"pwd" yaml:"pwd"`
}
type IUserStore interface {
Init(rootName, rootPwd string) error
IsInited() bool
@ -64,7 +42,7 @@ type IUserStore interface {
GetUser(id uint64) (*db.User, error)
GetUserByName(name string) (*db.User, error)
SetInfo(id uint64, user *db.User) error
CanIncrUsed(id uint64, capacity int64) (bool, error)
// CanIncrUsed(id uint64, capacity int64) (bool, error)
SetUsed(id uint64, incr bool, capacity int64) error
ResetUsed(id uint64, used int64) error
SetPwd(id uint64, pwd string) error
@ -82,57 +60,53 @@ type KVUserStore struct {
}
func NewKVUserStore(store kvstore.IKVStore) (*KVUserStore, error) {
_, ok := store.GetStringIn(InitNs, InitTimeKey)
if !ok {
var err error
for _, nsName := range []string{
IDsNs,
db.UsersNs,
InitNs,
RoleListNs,
} {
if err = store.AddNamespace(nsName); err != nil {
return nil, err
}
}
}
usStore := &KVUserStore{
return &KVUserStore{
store: store,
mtx: &sync.RWMutex{},
}
return usStore, nil
}, nil
}
func (us *KVUserStore) Init(rootName, rootPwd string) error {
var err error
adminPreferences := DefaultPreferences
for _, namespace := range []string{
db.UserSchemaNs,
db.UserIDsNs,
db.UsersNs,
db.RolesNs,
} {
_, ok := us.store.GetStringIn(namespace, db.KeyInitTime)
if !ok {
if err = us.store.AddNamespace(namespace); err != nil {
return err
}
}
}
admin := &db.User{
ID: 0,
Name: rootName,
Pwd: rootPwd,
Role: AdminRole,
Role: db.AdminRole,
Quota: &db.Quota{
SpaceLimit: defaultSpaceLimit,
UploadSpeedLimit: defaultUploadSpeedLimit,
DownloadSpeedLimit: defaultDownloadSpeedLimit,
SpaceLimit: db.DefaultSpaceLimit,
UploadSpeedLimit: db.DefaultUploadSpeedLimit,
DownloadSpeedLimit: db.DefaultDownloadSpeedLimit,
},
Preferences: &adminPreferences,
Preferences: &DefaultPreferences,
}
visitorPreferences := DefaultPreferences
visitor := &db.User{
ID: VisitorID,
Name: VisitorName,
Pwd: rootPwd,
Role: VisitorRole,
Role: db.VisitorRole,
Quota: &db.Quota{
SpaceLimit: 0,
UploadSpeedLimit: visitorUploadSpeedLimit,
DownloadSpeedLimit: visitorDownloadSpeedLimit,
UploadSpeedLimit: db.VisitorUploadSpeedLimit,
DownloadSpeedLimit: db.VisitorDownloadSpeedLimit,
},
Preferences: &visitorPreferences,
Preferences: &DefaultPreferences,
}
for _, user := range []*db.User{admin, visitor} {
@ -142,39 +116,26 @@ func (us *KVUserStore) Init(rootName, rootPwd string) error {
}
}
for _, role := range []string{AdminRole, UserRole, VisitorRole} {
for _, role := range []string{db.AdminRole, db.UserRole, db.VisitorRole} {
err = us.AddRole(role)
if err != nil {
return err
}
}
return us.store.SetStringIn(InitNs, InitTimeKey, fmt.Sprintf("%d", time.Now().Unix()))
return us.store.SetStringIn(db.UserSchemaNs, db.KeyInitTime, fmt.Sprintf("%d", time.Now().Unix()))
}
func (us *KVUserStore) IsInited() bool {
_, ok := us.store.GetStringIn(InitNs, InitTimeKey)
_, ok := us.store.GetStringIn(db.UserSchemaNs, db.KeyInitTime)
return ok
}
func (us *KVUserStore) AddUser(user *db.User) error {
us.mtx.Lock()
defer us.mtx.Unlock()
func (us *KVUserStore) setUser(user *db.User) error {
var err error
userID := fmt.Sprint(user.ID)
_, ok := us.store.GetStringIn(db.UsersNs, userID)
if ok {
return fmt.Errorf("userID (%d) exists", user.ID)
}
if user.Name == "" || user.Pwd == "" {
return errors.New("user name or password can not be empty")
}
_, ok = us.store.GetStringIn(IDsNs, user.Name)
if ok {
return fmt.Errorf("user name (%s) exists", user.Name)
}
err := us.store.SetStringIn(IDsNs, user.Name, userID)
err = us.store.SetStringIn(db.UserIDsNs, user.Name, userID)
if err != nil {
return err
}
@ -185,24 +146,60 @@ func (us *KVUserStore) AddUser(user *db.User) error {
return us.store.SetStringIn(db.UsersNs, userID, string(userBytes))
}
func (us *KVUserStore) getUser(id uint64) (*db.User, error) {
userID := fmt.Sprint(id)
userBytes, ok := us.store.GetStringIn(db.UsersNs, userID)
if !ok {
return nil, ErrUserNotFound
}
user := &db.User{}
err := json.Unmarshal([]byte(userBytes), user)
if err != nil {
return nil, err
}
return user, nil
}
func (us *KVUserStore) getUserByName(name string) (*db.User, error) {
userID, ok := us.store.GetStringIn(db.UserIDsNs, name)
if !ok {
return nil, ErrUserNotFound
}
userBytes, ok := us.store.GetStringIn(db.UsersNs, userID)
if !ok {
return nil, ErrUserNotFound
}
user := &db.User{}
err := json.Unmarshal([]byte(userBytes), user)
if err != nil {
return nil, err
}
return user, nil
}
func (us *KVUserStore) AddUser(user *db.User) error {
us.mtx.Lock()
defer us.mtx.Unlock()
return us.setUser(user)
}
func (us *KVUserStore) DelUser(id uint64) error {
us.mtx.Lock()
defer us.mtx.Unlock()
userID := fmt.Sprint(id)
infoStr, ok := us.store.GetStringIn(db.UsersNs, userID)
if !ok {
return fmt.Errorf("userID (%s) does not exist", userID)
}
user := &db.User{}
err := json.Unmarshal([]byte(infoStr), user)
user, err := us.getUser(id)
if err != nil {
return err
}
// TODO: add complement operations if part of the actions fails
err1 := us.store.DelStringIn(IDsNs, user.Name)
err2 := us.store.DelStringIn(db.UsersNs, userID)
err1 := us.store.DelStringIn(db.UserIDsNs, user.Name)
err2 := us.store.DelStringIn(db.UsersNs, fmt.Sprint(user.ID))
if err1 != nil || err2 != nil {
return fmt.Errorf("DelUser: err1(%s) err2(%s)", err1, err2)
}
@ -213,143 +210,64 @@ func (us *KVUserStore) GetUser(id uint64) (*db.User, error) {
us.mtx.RLock()
defer us.mtx.RUnlock()
userID := fmt.Sprint(id)
infoStr, ok := us.store.GetStringIn(db.UsersNs, userID)
if !ok {
return nil, fmt.Errorf("user (%s) not found", userID)
}
user := &db.User{}
err := json.Unmarshal([]byte(infoStr), user)
if err != nil {
return nil, err
}
gotID, ok := us.store.GetStringIn(IDsNs, user.Name)
if !ok {
return nil, fmt.Errorf("user id (%s) not found", user.Name)
} else if gotID != userID {
return nil, fmt.Errorf("user id (%s) not match: got(%s) expected(%s)", user.Name, gotID, userID)
}
// TODO: use sync.Pool instead
return user, nil
return us.getUser(id)
}
func (us *KVUserStore) GetUserByName(name string) (*db.User, error) {
us.mtx.RLock()
defer us.mtx.RUnlock()
userID, ok := us.store.GetStringIn(IDsNs, name)
if !ok {
return nil, ErrNotFound
}
infoStr, ok := us.store.GetStringIn(db.UsersNs, userID)
if !ok {
return nil, ErrNotFound
}
user := &db.User{}
err := json.Unmarshal([]byte(infoStr), user)
if err != nil {
return nil, err
}
if user.Name != name {
return nil, fmt.Errorf("user id (%s) not match: got(%s) expected(%s)", userID, user.Name, name)
}
// TODO: use sync.Pool instead
return user, nil
return us.getUserByName(name)
}
func (us *KVUserStore) SetPwd(id uint64, pwd string) error {
us.mtx.Lock()
defer us.mtx.Unlock()
userID := fmt.Sprint(id)
infoStr, ok := us.store.GetStringIn(db.UsersNs, userID)
if !ok {
return fmt.Errorf("user (%d) does not exist", id)
}
gotUser := &db.User{}
err := json.Unmarshal([]byte(infoStr), gotUser)
user, err := us.getUser(id)
if err != nil {
return err
} else if gotUser.ID != id {
return fmt.Errorf("user id key(%d) info(%d) does match", id, gotUser.ID)
}
gotUser.Pwd = pwd
infoBytes, err := json.Marshal(gotUser)
user.Pwd = pwd
return us.setUser(user)
}
func (us *KVUserStore) SetInfo(id uint64, user *db.User) error {
us.mtx.Lock()
defer us.mtx.Unlock()
gotUser, err := us.getUser(id)
if err != nil {
return err
}
return us.store.SetStringIn(db.UsersNs, userID, string(infoBytes))
gotUser.Role = user.Role
gotUser.Quota = user.Quota
gotUser.UsedSpace = user.UsedSpace
return us.setUser(gotUser)
}
func (us *KVUserStore) SetPreferences(id uint64, prefers *db.Preferences) error {
us.mtx.Lock()
defer us.mtx.Unlock()
userID := fmt.Sprint(id)
infoStr, ok := us.store.GetStringIn(db.UsersNs, userID)
if !ok {
return fmt.Errorf("user (%d) does not exist", id)
}
gotUser := &db.User{}
err := json.Unmarshal([]byte(infoStr), gotUser)
if err != nil {
return err
} else if gotUser.ID != id {
return fmt.Errorf("user id key(%d) info(%d) does match", id, gotUser.ID)
}
gotUser.Preferences = prefers
infoBytes, err := json.Marshal(gotUser)
user, err := us.getUser(id)
if err != nil {
return err
}
return us.store.SetStringIn(db.UsersNs, userID, string(infoBytes))
}
func (us *KVUserStore) CanIncrUsed(id uint64, capacity int64) (bool, error) {
us.mtx.Lock()
defer us.mtx.Unlock()
userID := fmt.Sprint(id)
infoStr, ok := us.store.GetStringIn(db.UsersNs, userID)
if !ok {
return false, fmt.Errorf("user (%d) does not exist", id)
}
gotUser := &db.User{}
err := json.Unmarshal([]byte(infoStr), gotUser)
if err != nil {
return false, err
} else if gotUser.ID != id {
return false, fmt.Errorf("user id key(%d) info(%d) does match", id, gotUser.ID)
}
return gotUser.UsedSpace+capacity <= int64(gotUser.Quota.SpaceLimit), nil
user.Preferences = prefers
return us.setUser(user)
}
func (us *KVUserStore) SetUsed(id uint64, incr bool, capacity int64) error {
us.mtx.Lock()
defer us.mtx.Unlock()
userID := fmt.Sprint(id)
infoStr, ok := us.store.GetStringIn(db.UsersNs, userID)
if !ok {
return fmt.Errorf("user (%d) does not exist", id)
}
gotUser := &db.User{}
err := json.Unmarshal([]byte(infoStr), gotUser)
gotUser, err := us.getUser(id)
if err != nil {
return err
} else if gotUser.ID != id {
return fmt.Errorf("user id key(%d) info(%d) does match", id, gotUser.ID)
}
if incr && gotUser.UsedSpace+capacity > int64(gotUser.Quota.SpaceLimit) {
@ -359,78 +277,26 @@ func (us *KVUserStore) SetUsed(id uint64, incr bool, capacity int64) error {
if incr {
gotUser.UsedSpace = gotUser.UsedSpace + capacity
} else {
gotUser.UsedSpace = gotUser.UsedSpace - capacity
if gotUser.UsedSpace < 0 { // TODO: this is a work around
gotUser.UsedSpace = 0
if gotUser.UsedSpace-capacity < 0 {
return ErrNegtiveUsedSpace
}
gotUser.UsedSpace = gotUser.UsedSpace - capacity
}
infoBytes, err := json.Marshal(gotUser)
if err != nil {
return err
}
return us.store.SetStringIn(db.UsersNs, userID, string(infoBytes))
return us.setUser(gotUser)
}
func (us *KVUserStore) ResetUsed(id uint64, used int64) error {
us.mtx.Lock()
defer us.mtx.Unlock()
userID := fmt.Sprint(id)
infoStr, ok := us.store.GetStringIn(db.UsersNs, userID)
if !ok {
return fmt.Errorf("user (%d) does not exist", id)
}
gotUser := &db.User{}
err := json.Unmarshal([]byte(infoStr), gotUser)
gotUser, err := us.getUser(id)
if err != nil {
return err
} else if gotUser.ID != id {
return fmt.Errorf("user id key(%d) info(%d) does match", id, gotUser.ID)
}
gotUser.UsedSpace = used
infoBytes, err := json.Marshal(gotUser)
if err != nil {
return err
}
return us.store.SetStringIn(db.UsersNs, userID, string(infoBytes))
}
func (us *KVUserStore) SetInfo(id uint64, user *db.User) error {
us.mtx.Lock()
defer us.mtx.Unlock()
userID := fmt.Sprint(id)
infoStr, ok := us.store.GetStringIn(db.UsersNs, userID)
if !ok {
return fmt.Errorf("user (%d) does not exist", id)
}
gotUser := &db.User{}
err := json.Unmarshal([]byte(infoStr), gotUser)
if err != nil {
return err
} else if gotUser.ID != id {
return fmt.Errorf("user id key(%d) info(%d) does match", id, gotUser.ID)
}
// name and password can not be updated here
if user.Role != "" {
gotUser.Role = user.Role
}
if user.Quota != nil {
gotUser.Quota = user.Quota
}
if user.UsedSpace > 0 {
gotUser.UsedSpace = user.UsedSpace
}
infoBytes, err := json.Marshal(gotUser)
if err != nil {
return err
}
return us.store.SetStringIn(db.UsersNs, userID, string(infoBytes))
return us.setUser(gotUser)
}
func (us *KVUserStore) ListUsers() ([]*db.User, error) {
@ -441,7 +307,7 @@ func (us *KVUserStore) ListUsers() ([]*db.User, error) {
if err != nil {
return nil, err
}
nameToID, err := us.store.ListStringsIn(IDsNs)
nameToID, err := us.store.ListStringsIn(db.UserIDsNs)
if err != nil {
return nil, err
}
@ -474,7 +340,7 @@ func (us *KVUserStore) ListUsers() ([]*db.User, error) {
for name, id := range nameToID {
_, ok := idToInfo[id]
if !ok {
err = us.store.DelStringIn(IDsNs, name)
err = us.store.DelStringIn(db.UserIDsNs, name)
if err != nil {
return nil, err
}
@ -490,35 +356,35 @@ func (us *KVUserStore) ListUserIDs() (map[string]string, error) {
us.mtx.RLock()
defer us.mtx.RUnlock()
return us.store.ListStringsIn(IDsNs)
return us.store.ListStringsIn(db.UserIDsNs)
}
func (us *KVUserStore) AddRole(role string) error {
us.mtx.Lock()
defer us.mtx.Unlock()
_, ok := us.store.GetBoolIn(RoleListNs, role)
_, ok := us.store.GetBoolIn(db.RolesNs, role)
if ok {
return fmt.Errorf("role (%s) exists", role)
}
return us.store.SetBoolIn(RoleListNs, role, true)
return us.store.SetBoolIn(db.RolesNs, role, true)
}
func (us *KVUserStore) DelRole(role string) error {
us.mtx.Lock()
defer us.mtx.Unlock()
if role == AdminRole || role == UserRole || role == VisitorRole {
if role == db.AdminRole || role == db.UserRole || role == db.VisitorRole {
return errors.New("predefined roles can not be deleted")
}
return us.store.DelBoolIn(RoleListNs, role)
return us.store.DelBoolIn(db.RolesNs, role)
}
func (us *KVUserStore) ListRoles() (map[string]bool, error) {
us.mtx.Lock()
defer us.mtx.Unlock()
return us.store.ListBoolsIn(RoleListNs)
return us.store.ListBoolsIn(db.RolesNs)
}

View file

@ -8,7 +8,6 @@ import (
"testing"
"github.com/ihexxa/quickshare/src/db"
"github.com/ihexxa/quickshare/src/db/sitestore"
"github.com/ihexxa/quickshare/src/kvstore/boltdbpvd"
)
@ -26,16 +25,16 @@ func TestUserStores(t *testing.T) {
if root.Pwd != rootPwd {
t.Fatalf("passwords not match %s", err)
}
if root.Role != AdminRole {
if root.Role != db.AdminRole {
t.Fatalf("incorrect root role")
}
if root.Quota.SpaceLimit != defaultSpaceLimit {
if root.Quota.SpaceLimit != db.DefaultSpaceLimit {
t.Fatalf("incorrect root SpaceLimit")
}
if root.Quota.UploadSpeedLimit != defaultUploadSpeedLimit {
if root.Quota.UploadSpeedLimit != db.DefaultUploadSpeedLimit {
t.Fatalf("incorrect root UploadSpeedLimit")
}
if root.Quota.DownloadSpeedLimit != defaultDownloadSpeedLimit {
if root.Quota.DownloadSpeedLimit != db.DefaultDownloadSpeedLimit {
t.Fatalf("incorrect root DownloadSpeedLimit")
}
if !db.ComparePreferences(root.Preferences, &DefaultPreferences) {
@ -52,16 +51,16 @@ func TestUserStores(t *testing.T) {
if visitor.Pwd != rootPwd {
t.Fatalf("passwords not match %s", err)
}
if visitor.Role != VisitorRole {
if visitor.Role != db.VisitorRole {
t.Fatalf("incorrect visitor role")
}
if visitor.Quota.SpaceLimit != 0 {
t.Fatalf("incorrect visitor SpaceLimit")
}
if visitor.Quota.UploadSpeedLimit != visitorUploadSpeedLimit {
if visitor.Quota.UploadSpeedLimit != db.VisitorUploadSpeedLimit {
t.Fatalf("incorrect visitor UploadSpeedLimit")
}
if visitor.Quota.DownloadSpeedLimit != visitorDownloadSpeedLimit {
if visitor.Quota.DownloadSpeedLimit != db.VisitorDownloadSpeedLimit {
t.Fatalf("incorrect visitor DownloadSpeedLimit")
}
if !db.ComparePreferences(visitor.Preferences, &DefaultPreferences) {
@ -70,7 +69,7 @@ func TestUserStores(t *testing.T) {
id, name1 := uint64(2), "test_user1"
pwd1, pwd2 := "666", "888"
role1, role2 := UserRole, AdminRole
role1, role2 := db.UserRole, db.AdminRole
spaceLimit1, upLimit1, downLimit1 := int64(17), 5, 7
spaceLimit2, upLimit2, downLimit2 := int64(19), 13, 17
@ -121,7 +120,7 @@ func TestUserStores(t *testing.T) {
}
for _, user := range users {
if user.ID == 0 {
if user.Name != rootName || user.Role != AdminRole {
if user.Name != rootName || user.Role != db.AdminRole {
t.Fatalf("incorrect root info %v", user)
}
}
@ -130,6 +129,9 @@ func TestUserStores(t *testing.T) {
t.Fatalf("incorrect user info %v", user)
}
}
if user.Pwd != "" {
t.Fatalf("password must be empty")
}
}
err = store.SetPwd(id, pwd2)
@ -243,10 +245,10 @@ func TestUserStores(t *testing.T) {
t.Fatalf("users size should be 2 (%d)", len(users))
}
for _, user := range users {
if user.ID == 0 && user.Name != rootName && user.Role != AdminRole {
if user.ID == 0 && user.Name != rootName && user.Role != db.AdminRole {
t.Fatalf("incorrect root info %v", user)
}
if user.ID == VisitorID && user.Name != VisitorName && user.Role != VisitorRole {
if user.ID == VisitorID && user.Name != VisitorName && user.Role != db.VisitorRole {
t.Fatalf("incorrect visitor info %v", user)
}
}
@ -276,7 +278,7 @@ func TestUserStores(t *testing.T) {
}
for _, role := range append(roles, []string{
AdminRole, UserRole, VisitorRole,
db.AdminRole, db.UserRole, db.VisitorRole,
}...) {
if !roleMap[role] {
t.Fatalf("role(%s) not found", role)