tricrypt/cmd/server/users.go

78 lines
1.4 KiB
Go
Raw Normal View History

2024-06-07 08:48:13 +02:00
package main
import (
"errors"
2024-06-07 11:20:34 +02:00
"log"
2024-06-07 08:48:13 +02:00
"math/rand"
"sync"
)
var (
userCenter UserCenter
)
type UserCenter struct {
2024-06-07 11:19:37 +02:00
UsersSTOI map[string]uint16
UsersITOS map[uint16]string
2024-06-07 08:48:13 +02:00
Mu sync.Mutex
}
func (u *UserCenter) Init() {
2024-06-07 11:19:37 +02:00
u.UsersSTOI = make(map[string]uint16)
u.UsersITOS = make(map[uint16]string)
2024-06-07 08:48:13 +02:00
}
var (
2024-06-08 20:45:36 +02:00
ERROR_ALREADY_HAVE = errors.New("Already taken")
ERROR_DONT_HAVE = errors.New("Not found")
2024-06-07 08:48:13 +02:00
)
2024-06-07 11:19:37 +02:00
func (u *UserCenter) AddUser(name string) (uint16, error) {
2024-06-07 08:48:13 +02:00
u.Mu.Lock()
defer u.Mu.Unlock()
_, alreadyHave := u.UsersSTOI[name]
if alreadyHave {
2024-06-07 11:19:37 +02:00
return 0, ERROR_ALREADY_HAVE
2024-06-07 08:48:13 +02:00
}
2024-06-07 11:19:37 +02:00
var ret uint16
2024-06-07 08:48:13 +02:00
for {
rInt := rand.Int31()
2024-06-07 11:19:37 +02:00
_, taken := u.UsersITOS[uint16(rInt)]
2024-06-07 08:48:13 +02:00
if !taken {
2024-06-07 11:19:37 +02:00
ret = uint16(rInt)
2024-06-07 08:48:13 +02:00
break
}
}
2024-06-07 11:20:34 +02:00
log.Printf("Users: add %s with %d id\n", name, ret)
2024-06-07 08:48:13 +02:00
u.UsersITOS[ret] = name
u.UsersSTOI[name] = ret
return ret, nil
}
func (u *UserCenter) DeleteIfHaveOne(id uint16) {
name, found := u.UsersITOS[id]
if !found {
log.Printf("User with %d id is not found; Can not delete\n", id)
return
}
delete(u.UsersITOS, id)
delete(u.UsersSTOI, name)
log.Printf("User with %s name and %d id was found; User is deleted\n", name, id)
}
2024-06-07 11:19:37 +02:00
func (u *UserCenter) GetID(name string) (uint16, error) {
2024-06-07 08:48:13 +02:00
id, have := u.UsersSTOI[name]
if !have {
2024-06-07 11:19:37 +02:00
return 0, ERROR_DONT_HAVE
2024-06-07 08:48:13 +02:00
}
return id, nil
}
2024-06-07 11:19:37 +02:00
func (u *UserCenter) GetName(id uint16) (string, error) {
2024-06-07 08:48:13 +02:00
name, have := u.UsersITOS[id]
if !have {
return "", ERROR_DONT_HAVE
}
return name, nil
}