2020-03-31 07:38:45 -06:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"database/sql"
|
2020-04-02 06:28:40 -06:00
|
|
|
"fmt"
|
2020-03-31 07:38:45 -06:00
|
|
|
"log"
|
|
|
|
"net/http"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
_ "github.com/lib/pq"
|
|
|
|
"suah.dev/cromp/db"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
pd, err = sql.Open("postgres", "host=localhost dbname=qbit sslmode=disable password=''")
|
|
|
|
ctx, cancel = context.WithCancel(context.Background())
|
|
|
|
base = db.New(pd)
|
|
|
|
)
|
|
|
|
|
|
|
|
func logger(f http.HandlerFunc) http.HandlerFunc {
|
|
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
log.Printf("%s\n", r.URL.Path)
|
|
|
|
f(w, r)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-04-02 06:28:40 -06:00
|
|
|
func getUser(r *http.Request) (*db.User, error) {
|
|
|
|
token := r.Header.Get("X-Access-Token")
|
|
|
|
if token == "" {
|
|
|
|
log.Printf("checkAuth: %s received empty token\n", r.URL.Path)
|
|
|
|
return nil, fmt.Errorf("Unauthorized")
|
|
|
|
}
|
|
|
|
|
2020-04-05 09:33:04 -06:00
|
|
|
user, err := base.GetUserByToken(ctx, token)
|
2020-04-02 06:28:40 -06:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return &user, nil
|
|
|
|
}
|
|
|
|
|
2020-03-31 07:38:45 -06:00
|
|
|
func checkAuth(f http.HandlerFunc) http.HandlerFunc {
|
|
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
2020-04-02 06:28:40 -06:00
|
|
|
user, err := getUser(r)
|
|
|
|
if err != nil {
|
|
|
|
http.Error(w, "Invalid User", http.StatusUnauthorized)
|
2020-03-31 07:38:45 -06:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2020-04-02 06:28:40 -06:00
|
|
|
if time.Now().Before(user.TokenExpires) {
|
|
|
|
log.Printf("checkAuth: %s received valid token\n", r.URL.Path)
|
|
|
|
f(w, r)
|
2020-03-31 07:38:45 -06:00
|
|
|
} else {
|
2020-04-02 06:28:40 -06:00
|
|
|
log.Printf("checkAuth: %s received expired token\n", r.URL.Path)
|
|
|
|
http.Error(w, "Token Expired", http.StatusUnauthorized)
|
|
|
|
return
|
2020-03-31 07:38:45 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func main() {
|
|
|
|
|
|
|
|
defer cancel() // cancel when we are finished consuming integers
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
defer pd.Close()
|
|
|
|
|
|
|
|
http.HandleFunc("/user/new", logger(NewUser))
|
|
|
|
http.HandleFunc("/user/auth", logger(Auth))
|
|
|
|
|
|
|
|
http.HandleFunc("/entries/add", checkAuth(logger(AddEntry)))
|
2020-04-02 06:28:40 -06:00
|
|
|
http.HandleFunc("/entries/list", checkAuth(logger(ListEntries)))
|
2020-03-31 07:38:45 -06:00
|
|
|
http.HandleFunc("/entries/delete", checkAuth(logger(Entries)))
|
|
|
|
http.HandleFunc("/entries/get", checkAuth(logger(Entries)))
|
|
|
|
http.HandleFunc("/entries/update", checkAuth(logger(Entries)))
|
|
|
|
http.HandleFunc("/entries/similar", checkAuth(logger(SimilarEntries)))
|
|
|
|
|
|
|
|
log.Fatalln(http.ListenAndServe(":8080", nil))
|
|
|
|
}
|