diff options
author | Andinus <andinus@nand.sh> | 2020-03-27 21:20:12 +0530 |
---|---|---|
committer | Andinus <andinus@nand.sh> | 2020-03-27 21:20:12 +0530 |
commit | 3dee7955670274b92ad8b3931e6c36995f1ee418 (patch) | |
tree | c312153b27a2e6e32e900112978696c7aae312b8 /handler/web | |
parent | 97f36a08c7a5e3bd7921a26af89eee8ad9b3e3d7 (diff) | |
download | perseus-3dee7955670274b92ad8b3931e6c36995f1ee418.tar.gz |
Add registration handler
Diffstat (limited to 'handler/web')
-rw-r--r-- | handler/web/page.go | 12 | ||||
-rw-r--r-- | handler/web/register.go | 73 |
2 files changed, 85 insertions, 0 deletions
diff --git a/handler/web/page.go b/handler/web/page.go new file mode 100644 index 0000000..cf96395 --- /dev/null +++ b/handler/web/page.go @@ -0,0 +1,12 @@ +package web + +import "html/template" + +// Page holds page information +type Page struct { + SafeList []template.HTML + List []string + Error []string + Success []string + Notice []string +} diff --git a/handler/web/register.go b/handler/web/register.go new file mode 100644 index 0000000..232768e --- /dev/null +++ b/handler/web/register.go @@ -0,0 +1,73 @@ +package web + +import ( + "fmt" + "html/template" + "log" + "net/http" + "strings" + + "tildegit.org/andinus/perseus/auth" + "tildegit.org/andinus/perseus/storage/sqlite3" +) + +// HandleRegister handles /register pages. +func HandleRegister(w http.ResponseWriter, r *http.Request, db *sqlite3.DB) { + p := Page{} + p.Notice = []string{ + "Only [a-z] & [0-9] allowed for username", + "Password length must be greater than 8 characters", + } + switch r.Method { + case http.MethodGet: + t, _ := template.ParseFiles("web/register.html") + t.Execute(w, p) + + case http.MethodPost: + if err := r.ParseForm(); err != nil { + log.Printf("web/register.go: 400 Bad Request :: %s", err.Error()) + http.Error(w, "400 Bad Request", http.StatusBadRequest) + return + } + + // Get form values + uInfo := make(map[string]string) + uInfo["username"] = r.FormValue("username") + uInfo["password"] = r.FormValue("password") + + // Perform registration + err := auth.Register(db, uInfo) + + if err != nil { + log.Printf("web/register.go: %s :: %s :: %s", + "registration failed", + uInfo["username"], + err.Error()) + + error := []string{} + error = append(error, + fmt.Sprintf("Registration failed")) + + // Check if the error was because of username + // not being unique. + if strings.HasPrefix(err.Error(), "UNIQUE constraint failed") { + error = append(error, + fmt.Sprintf("Username not unique")) + } + p.Error = error + } else { + success := []string{} + success = append(success, + fmt.Sprintf("Registration successful")) + p.Success = success + } + + t, _ := template.ParseFiles("web/register.html") + t.Execute(w, p) + + default: + w.WriteHeader(http.StatusMethodNotAllowed) + log.Printf("web/register.go: %v not allowed on %v", r.Method, r.URL) + } + +} |