mirror of
https://github.com/signaller-matrix/signaller.git
synced 2024-11-09 12:11:03 +00:00
Add simple username validation
This commit is contained in:
parent
4793970e87
commit
1816362e9a
@ -16,6 +16,7 @@ type Backend interface {
|
||||
GetRoomByID(id string) Room
|
||||
Sync(token string, request sync.SyncRequest) (response *sync.SyncReply, err models.ApiError)
|
||||
PublicRooms() []Room
|
||||
ValidateUsernameFunc() func(string) error
|
||||
}
|
||||
|
||||
type Room interface {
|
||||
|
@ -1,6 +1,8 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"regexp"
|
||||
"sort"
|
||||
"sync"
|
||||
|
||||
@ -12,10 +14,11 @@ import (
|
||||
)
|
||||
|
||||
type Backend struct {
|
||||
data map[string]internal.User
|
||||
rooms map[string]internal.Room
|
||||
hostname string
|
||||
mutex sync.Mutex // TODO: replace with RW mutex
|
||||
data map[string]internal.User
|
||||
rooms map[string]internal.Room
|
||||
hostname string
|
||||
validateUsernameFunc func(string) error // TODO: create ability to redefine validation func
|
||||
mutex sync.Mutex // TODO: replace with RW mutex
|
||||
}
|
||||
|
||||
type Token struct {
|
||||
@ -24,14 +27,22 @@ type Token struct {
|
||||
|
||||
func NewBackend(hostname string) *Backend {
|
||||
return &Backend{
|
||||
hostname: hostname,
|
||||
rooms: make(map[string]internal.Room),
|
||||
data: make(map[string]internal.User)}
|
||||
hostname: hostname,
|
||||
validateUsernameFunc: defaultValidationUsernameFunc,
|
||||
rooms: make(map[string]internal.Room),
|
||||
data: make(map[string]internal.User)}
|
||||
}
|
||||
|
||||
func (backend *Backend) Register(username, password, device string) (user internal.User, token string, err models.ApiError) {
|
||||
backend.mutex.Lock()
|
||||
|
||||
if backend.validateUsernameFunc != nil {
|
||||
err := backend.validateUsernameFunc(username)
|
||||
if err != nil {
|
||||
return nil, "", models.NewError(models.M_INVALID_USERNAME, err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
if _, ok := backend.data[username]; ok {
|
||||
backend.mutex.Unlock()
|
||||
return nil, "", models.NewError(models.M_USER_IN_USE, "trying to register a user ID which has been taken")
|
||||
@ -131,3 +142,20 @@ func (backend *Backend) PublicRooms() []internal.Room {
|
||||
|
||||
return rooms
|
||||
}
|
||||
|
||||
func (backend *Backend) ValidateUsernameFunc() func(string) error {
|
||||
backend.mutex.Lock()
|
||||
defer backend.mutex.Unlock()
|
||||
|
||||
return backend.validateUsernameFunc
|
||||
}
|
||||
|
||||
func defaultValidationUsernameFunc(userName string) error {
|
||||
const re = `\w{5,}`
|
||||
|
||||
if !regexp.MustCompile(re).MatchString(userName) {
|
||||
return fmt.Errorf("username does not match %s", re)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user