package auth import ( "net/http" "strings" "git.aiterp.net/gisle/wrouter/response" ) type handler struct { } func (h *handler) Handle(path string, w http.ResponseWriter, req *http.Request, user *User) bool { // Get the subpath out of the path subpath := req.URL.Path[len(path):] if subpath[0] == '/' { subpath = subpath[1:] } method := FindAuthenticator(req.Form.Get("method")) if method == nil { if user == nil { response.Text(w, 400, "Invalid method: "+req.Form.Get("method")) return true } method = user.method } switch strings.ToLower(subpath) { case "login": { if req.Method != "POST" { response.Text(w, 405, req.Method+" not allowed") return true } username := req.Form.Get("username") password := req.Form.Get("password") w.Header().Set("X-Auth-Method", method.Name()) user, err := method.Login(username, password) if err == nil && user != nil { sess := OpenSession(user) http.SetCookie(w, &http.Cookie{Name: SessionCookieName, Value: sess.ID, Expires: sess.Time.Add(SessionMaxTime), Path: "/", HttpOnly: true}) response.JSON(w, 200, sess) } else { response.Text(w, 401, "Login failed") } } case "register": { if req.Method != "POST" { response.Text(w, 405, req.Method+" not allowed") return true } data := make(map[string]string) for key, value := range req.Form { if key != "username" && key != "password" && key != "method" { data[key] = value[0] } } username := req.Form.Get("username") password := req.Form.Get("password") user, err := method.Register(username, password, data) if err == nil && user != nil { sess := OpenSession(user) http.SetCookie(w, &http.Cookie{Name: SessionCookieName, Value: sess.ID, Expires: sess.Time.Add(SessionMaxTime), Path: "/", HttpOnly: true}) response.JSON(w, 200, sess) } else { response.Text(w, 401, err.Error()) } } case "logout-all": { if req.Method != "POST" { response.Text(w, 405, req.Method+" not allowed") return true } if user != nil { ClearSessions(user) response.Empty(w) } else { response.Text(w, 401, "Not logged in") } } case "status": { if req.Method != "GET" { response.Text(w, 405, req.Method+" not allowed") return true } if user != nil { response.JSON(w, 200, user) } else { response.Text(w, 401, "Not logged in") } } default: { response.Text(w, 404, "Operation not found: "+subpath) } } return true } var Handler = &handler{}