You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
69 lines
1.6 KiB
69 lines
1.6 KiB
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)
|
|
}
|