1
0
Fork 0
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.

97 lines
2.4 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"
"github.com/asaskevich/govalidator"
)
type User struct {
Name string `valid:"alphanum,required"`
Pass string `valid:"required,runelength(8|999)"`
Email string `valid:"email"`
}
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 register(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")
}
res, err := govalidator.ValidateStruct(input)
if err != nil || res != true {
log.Println("user",input,"was invalid because", err)
return ehttp.NewErrorf(http.StatusBadRequest, "Could not validate your data")
}
users = append(users, input)
log.Println("registered user", input)
return nil
}
func main() {
users = []User{ {Name:"foo",Pass:"bar"}, {Name:"baz",Pass:"bla"}}
r := mux.NewRouter()
r.Handle("/getToken", ehttp.HandlerFunc(getToken))
r.Handle("/register", ehttp.HandlerFunc(register))
http.Handle("/", r)
http.ListenAndServe(":8000", nil)
}