diff options
author | Brian Picciano <mediocregopher@gmail.com> | 2021-08-18 18:13:18 -0600 |
---|---|---|
committer | Brian Picciano <mediocregopher@gmail.com> | 2021-08-18 18:13:44 -0600 |
commit | a9d8aa2591cd03fe1a9da72bab8d311e4840e8f1 (patch) | |
tree | 98a32eb3a2719f10dc0d55a206851e3793e61388 /srv/api | |
parent | bec64827d19d64aae86ca3d2b26de800b427a540 (diff) |
implemented basic userID generation
Diffstat (limited to 'srv/api')
-rw-r--r-- | srv/api/api.go | 9 | ||||
-rw-r--r-- | srv/api/chat.go | 47 |
2 files changed, 52 insertions, 4 deletions
diff --git a/srv/api/api.go b/srv/api/api.go index 15627f8..39d73d9 100644 --- a/srv/api/api.go +++ b/srv/api/api.go @@ -22,10 +22,11 @@ import ( // Params are used to instantiate a new API instance. All fields are required // unless otherwise noted. type Params struct { - Logger *mlog.Logger - PowManager pow.Manager - MailingList mailinglist.MailingList - GlobalRoom chat.Room + Logger *mlog.Logger + PowManager pow.Manager + MailingList mailinglist.MailingList + GlobalRoom chat.Room + UserIDCalculator chat.UserIDCalculator // ListenProto and ListenAddr are passed into net.Listen to create the // API's listener. Both "tcp" and "unix" protocols are explicitly diff --git a/srv/api/chat.go b/srv/api/chat.go index 84fffde..55d9d02 100644 --- a/srv/api/chat.go +++ b/srv/api/chat.go @@ -4,6 +4,8 @@ import ( "errors" "fmt" "net/http" + "strings" + "unicode" "github.com/mediocregopher/blog.mediocregopher.com/srv/chat" ) @@ -39,3 +41,48 @@ func (a *api) chatHistoryHandler() http.Handler { }) }) } + +func (a *api) getUserID(r *http.Request) (chat.UserID, error) { + name := r.PostFormValue("name") + if l := len(name); l == 0 { + return chat.UserID{}, errors.New("name is required") + } else if l > 16 { + return chat.UserID{}, errors.New("name too long") + } + + nameClean := strings.Map(func(r rune) rune { + if !unicode.IsPrint(r) { + return -1 + } + return r + }, name) + + if nameClean != name { + return chat.UserID{}, errors.New("name contains invalid characters") + } + + password := r.PostFormValue("password") + if l := len(password); l == 0 { + return chat.UserID{}, errors.New("password is required") + } else if l > 128 { + return chat.UserID{}, errors.New("password too long") + } + + return a.params.UserIDCalculator.Calculate(name, password), nil +} + +func (a *api) getUserIDHandler() http.Handler { + return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { + userID, err := a.getUserID(r) + if err != nil { + badRequest(rw, r, err) + return + } + + jsonResult(rw, r, struct { + UserID chat.UserID `json:"userID"` + }{ + UserID: userID, + }) + }) +} |