From 1bcebaed591902be1abec6b342e8d3ad0e3d6f7b Mon Sep 17 00:00:00 2001 From: Gregory Eremin Date: Thu, 5 Mar 2015 22:25:26 +0700 Subject: [PATCH] User orgs api --- db/org.go | 30 ++++++++++++++++++++++++++++++ server/api.go | 17 +++++++++++++++++ server/auth.go | 10 ++++++---- server/server.go | 6 ++++++ 4 files changed, 59 insertions(+), 4 deletions(-) create mode 100644 db/org.go create mode 100644 server/api.go diff --git a/db/org.go b/db/org.go new file mode 100644 index 0000000..36508b8 --- /dev/null +++ b/db/org.go @@ -0,0 +1,30 @@ +package db + +type ( + Org struct { + Login string + Descr string + ID int64 + AvatarURL string + } +) + +const ( + userOrgsQuery = "select org from members where user = ?" +) + +func UserOrgs(login string) (orgs []string) { + if res, err := stmt(userOrgsQuery).Query(login); err == nil { + defer res.Close() + for res.Next() { + var org string + if err := res.Scan(&org); err != nil { + panic(err) + } + orgs = append(orgs, org) + } + } else { + panic(err) + } + return +} diff --git a/server/api.go b/server/api.go new file mode 100644 index 0000000..5df3b55 --- /dev/null +++ b/server/api.go @@ -0,0 +1,17 @@ +package server + +import ( + "encoding/json" + "net/http" + + "github.com/localhots/empact/db" +) + +func orgsListHandler(w http.ResponseWriter, r *http.Request) { + jsonHandler(w, r) + login := currentUser(r) + orgs := db.UserOrgs(login) + + b, _ := json.Marshal(orgs) + w.Write(b) +} diff --git a/server/auth.go b/server/auth.go index bcb6b86..cb603ba 100644 --- a/server/auth.go +++ b/server/auth.go @@ -12,10 +12,6 @@ import ( ) func authHelloHandler(w http.ResponseWriter, r *http.Request) { - if currentUser(r) != "" { - http.Redirect(w, r, "/app", 302) - return - } w.Header().Set("Content-Type", "text/html; charset=utf8") helloTmpl.ExecuteTemplate(w, "hello", map[string]interface{}{}) } @@ -49,3 +45,9 @@ func authCallbackHandler(w http.ResponseWriter, r *http.Request) { } } } + +func authHandler(w http.ResponseWriter, r *http.Request) { + if currentUser(r) == "" { + http.Redirect(w, r, "/auth/hello", 302) + } +} diff --git a/server/server.go b/server/server.go index b8549d6..e68a78d 100644 --- a/server/server.go +++ b/server/server.go @@ -19,11 +19,17 @@ func init() { helloTmpl, _ = helloTmpl.Parse(tmplText) http.HandleFunc("/", sessionHandler) + http.HandleFunc("/api/", authHandler) + http.HandleFunc("/api/orgs", orgsListHandler) http.HandleFunc("/auth/hello", authHelloHandler) http.HandleFunc("/auth/signin", authSigninHandler) http.HandleFunc("/auth/callback", authCallbackHandler) } +func jsonHandler(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json; charset=utf8") +} + func Start() { fmt.Println("Starting server at http://localhost:8080") http.ListenAndServe(":8080", nil)