From 1816362e9a72ce7291284b85c160df7b822fc090 Mon Sep 17 00:00:00 2001 From: nxshock Date: Sat, 3 Aug 2019 12:54:32 +0500 Subject: [PATCH] Add simple username validation --- internal/backend.go | 1 + internal/backends/memory/backend.go | 42 ++++++++++++++++++++++++----- 2 files changed, 36 insertions(+), 7 deletions(-) diff --git a/internal/backend.go b/internal/backend.go index 40b7ab2..30a72bf 100644 --- a/internal/backend.go +++ b/internal/backend.go @@ -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 { diff --git a/internal/backends/memory/backend.go b/internal/backends/memory/backend.go index 4c5919b..ccaa052 100644 --- a/internal/backends/memory/backend.go +++ b/internal/backends/memory/backend.go @@ -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 +}