Skip to content

Commit

Permalink
add: get/update user endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
claustra01 committed Apr 13, 2024
1 parent 4a6545e commit 930d0fe
Show file tree
Hide file tree
Showing 3 changed files with 91 additions and 0 deletions.
47 changes: 47 additions & 0 deletions bot/handler/token.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package handler

import (
"encoding/json"
"io/ioutil"
"net/http"

"github.com/claustra01/calendeye/db"
)

type TokenResponseBody struct {
RefreshToken string `json:"refresh_token"`
}

func UpdateRefreshToken(w http.ResponseWriter, req *http.Request) {
defer func() { _ = req.Body.Close() }()

id := req.URL.Query().Get("id")
body, err := ioutil.ReadAll(req.Body)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(err.Error()))
return
}

var token TokenResponseBody
err = json.Unmarshal(body, &token)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(err.Error()))
return
}

err = db.UpdateRefreshToken(id, token.RefreshToken)
if err == db.ErrNoRecord {
w.WriteHeader(http.StatusNotFound)
w.Write([]byte(err.Error()))
return
} else if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(err.Error()))
return
}

w.WriteHeader(http.StatusOK)
w.Write([]byte("Refresh token updated"))
}
40 changes: 40 additions & 0 deletions bot/handler/user.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package handler

import (
"encoding/json"
"net/http"

"github.com/claustra01/calendeye/db"
)

func GetUser(w http.ResponseWriter, req *http.Request) {
defer func() { _ = req.Body.Close() }()

id := req.URL.Query().Get("id")
if id == "" {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("id is required"))
return
}

user, err := db.GetUser(id)
if err == db.ErrNoRecord {
w.WriteHeader(http.StatusNotFound)
w.Write([]byte(err.Error()))
return
} else if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(err.Error()))
return
}

jsonUser, err := json.Marshal(user)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(err.Error()))
return
}

w.WriteHeader(http.StatusOK)
w.Write([]byte(jsonUser))
}
4 changes: 4 additions & 0 deletions bot/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,10 @@ func main() {
handler.Callback(w, req, bot, channelSecret)
})

// Setup HTTP Server for get/update user information
http.HandleFunc("/user", handler.GetUser)
http.HandleFunc("/token", handler.UpdateRefreshToken)

// This is just sample code.
// For actual use, you must support HTTPS by using `ListenAndServeTLS`, a reverse proxy or something else.
port := os.Getenv("PORT")
Expand Down

0 comments on commit 930d0fe

Please sign in to comment.