view cmd/tokenserver/main.go @ 12:000adddf74c8

Merge vue-cli branch into default * Remove second branch, because we don't need it.
author Bernhard Reiter <bernhard@intevation.de>
date Wed, 20 Jun 2018 16:48:54 +0200
parents 1d1236b72e5e 1597506a2241
children afc0de09231f
line wrap: on
line source

package main

import (
	"flag"
	"fmt"
	"log"
	"net/http"
	"path/filepath"
	"time"

	jwt "github.com/dgrijalva/jwt-go"
)

func token(rw http.ResponseWriter, req *http.Request) {
	user := req.FormValue("user")
	password := req.FormValue("password")

	_ = password

	eol := time.Now().Add(45 * time.Minute)

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
		"user": user,
		"eol":  eol.Unix(),
	})

	signingKey := []byte("very, very secret!")

	tokenString, err := token.SignedString(signingKey)

	if err != nil {
		http.Error(rw, "Signing failed", http.StatusInternalServerError)
		return
	}

	rw.Header().Set("Content-Type", "text/plain")

	fmt.Fprintf(rw, "%s\n", tokenString)
}

func main() {
	port := flag.Int("port", 8000, "port to listen at.")
	host := flag.String("host", "localhost", "host to listen at.")
	flag.Parse()
	p, _ := filepath.Abs("./web")
	mux := http.NewServeMux()
	mux.Handle("/", http.StripPrefix("/", http.FileServer(http.Dir(p))))
	mux.HandleFunc("/api/token", token)
	api := http.NewServeMux()
	api.Handle("/api/", http.StripPrefix("/api", mux))

	addr := fmt.Sprintf("%s:%d", *host, *port)
	log.Fatalln(http.ListenAndServe(addr, api))
}