parent
769d6437cb
commit
ad71836b7f
@ -0,0 +1,68 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"log"
|
||||
"encoding/json"
|
||||
// "errors"
|
||||
// "os"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/gorilla/schema"
|
||||
"github.com/creack/ehttp"
|
||||
// "github.com/auth0/go-jwt-middleware"
|
||||
"github.com/dgrijalva/jwt-go"
|
||||
)
|
||||
|
||||
type User struct {
|
||||
Name string
|
||||
Pass string
|
||||
Email string
|
||||
}
|
||||
|
||||
var users []User
|
||||
func getToken(w http.ResponseWriter, r *http.Request) error {
|
||||
decoder := schema.NewDecoder()
|
||||
err := r.ParseForm()
|
||||
if err != nil {
|
||||
return ehttp.NewErrorf(http.StatusInternalServerError, "could not parse form")
|
||||
}
|
||||
|
||||
var input User
|
||||
err = decoder.Decode(&input, r.PostForm)
|
||||
if err != nil {
|
||||
return ehttp.NewErrorf(http.StatusInternalServerError, "could not decode user from form")
|
||||
}
|
||||
|
||||
log.Println("name:", input.Name, "pass:", input.Pass)
|
||||
for _, user := range users {
|
||||
if user.Name == input.Name && user.Pass == input.Pass {
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
|
||||
"name":user.Name,
|
||||
})
|
||||
tokenString, err := token.SignedString([]byte("TODO"))
|
||||
if err != nil {
|
||||
return ehttp.NewErrorf(http.StatusForbidden, "could not construct token")
|
||||
}
|
||||
|
||||
log.Println("authenticated user", user.Name, "with token", tokenString)
|
||||
jsonOut, _ := json.Marshal(map[string]string{"token": tokenString})
|
||||
fmt.Fprint(w, string(jsonOut))
|
||||
return nil
|
||||
}
|
||||
}
|
||||
log.Println("getToken user not found")
|
||||
return ehttp.NewErrorf(http.StatusForbidden, "Cannot find user or password")
|
||||
}
|
||||
|
||||
|
||||
func main() {
|
||||
users = []User{ {Name:"foo",Pass:"bar"}, {Name:"baz",Pass:"bla"}}
|
||||
|
||||
r := mux.NewRouter()
|
||||
r.Handle("/getToken", ehttp.HandlerFunc(getToken))
|
||||
|
||||
http.Handle("/", r)
|
||||
http.ListenAndServe(":8000", nil)
|
||||
}
|
||||
Loading…
Reference in new issue