package user import ( "encoding/json" "fmt" "os" "path" "strings" ) func NewUserFromFile(fileName string) (*User, error) { jsonBytes, err := os.ReadFile(fileName) if err != nil { return nil, err } // var usr User var userJson UserJson if err := json.Unmarshal(jsonBytes, &userJson); err != nil { return nil, fmt.Errorf("%s: %v\n", fileName, err) } else { _, fileNameShort := path.Split(fileName) id := strings.TrimSuffix(fileNameShort, ".json") return &User{ id: id, name: userJson.Name, filename: fileName, role: userJson.Role, authcode: userJson.Authcode, gameId: userJson.GameId, }, nil } } func CreateUser(fileName, gameId string) *User { _, fileNameShort := path.Split(fileName) id := strings.TrimSuffix(fileNameShort, ".json") return &User{ id: id, filename: fileName, gameId: gameId, } } func (usr *User) SaveUser() error { usr.mu.Lock() defer usr.mu.Unlock() userJson := UserJson{ Name: usr.name, Authcode: usr.authcode, Role: usr.role, GameId: usr.gameId, } if jsonBytes, err := json.Marshal(userJson); err != nil { return err } else { if err := os.WriteFile(usr.filename, jsonBytes, 0666); err != nil { return err } } return nil } func (usr *User) GetId() string { usr.mu.Lock() defer usr.mu.Unlock() return usr.id } func (usr *User) GetAuthCode() string { usr.mu.Lock() defer usr.mu.Unlock() return usr.authcode } func (usr *User) SetAuthcode(authcode string) { usr.mu.Lock() defer usr.mu.Unlock() usr.authcode = authcode } func (usr *User) GetName() string { usr.mu.Lock() defer usr.mu.Unlock() return usr.name } func (usr *User) SetName(name string) { usr.mu.Lock() defer usr.mu.Unlock() usr.name = name } func (usr *User) GetRole() string { usr.mu.Lock() defer usr.mu.Unlock() return usr.role } func (usr *User) SetRole(role string) { usr.mu.Lock() defer usr.mu.Unlock() usr.role = role } func (usr *User) GetGameId() string { usr.mu.Lock() defer usr.mu.Unlock() return usr.gameId } func (usr *User) IsPlayer() bool { return true } func (usr *User) IsGamemaster() bool { usr.mu.Lock() defer usr.mu.Unlock() return usr.role == ROLE_GAMEMASTER || usr.role == ROLE_ADMIN } func (usr *User) IsAdmin() bool { usr.mu.Lock() defer usr.mu.Unlock() return usr.role == ROLE_ADMIN }