master
1package main
2
3import (
4 "fmt"
5 "net/http"
6 "os"
7 "time"
8
9 log "github.com/Sirupsen/logrus"
10 "github.com/bryfry/swas/proxyauth"
11 "github.com/codegangsta/cli"
12 "github.com/gorilla/mux"
13)
14
15// Define the command line arguments and help info
16func cliInit() *cli.App {
17 app := cli.NewApp()
18 app.Name = "swas"
19 app.Usage = "Simple Web API Server - Proxy Authentication API endpoint"
20 app.Version = "0.0.1"
21 app.Flags = []cli.Flag{
22 cli.StringFlag{
23 Name: "users, u",
24 Value: "./users.json",
25 Usage: "Specify users json file",
26 },
27 cli.IntFlag{
28 Name: "port, p",
29 Value: 80,
30 Usage: "Specify API Port",
31 },
32 cli.BoolFlag{
33 Name: "verbose",
34 Usage: "Increase verbosity",
35 },
36 }
37 return app
38}
39
40// Open and handle errors associated with creating a new Proxy data model
41func proxyInit(file string) *proxyauth.Proxy {
42 p, err := proxyauth.NewProxy(file)
43 if err != nil {
44 log.WithFields(log.Fields{
45 "file": file,
46 "err": err,
47 }).Fatal("Proxy init failed")
48 }
49 return p
50}
51
52// Define the api handles, expected methods, and content type
53func apiInit(p *proxyauth.Proxy) *mux.Router {
54 r := mux.NewRouter()
55
56 api := r.
57 Methods("POST").
58 Headers("Content-Type", "application/x-www-form-urlencoded").
59 Subrouter()
60
61 api.Handle("/api/2/domains/{domain}/proxyauth", p.Authenticate())
62 return r
63}
64
65// The httpInterceptor pattern is used to intercept all http requests. This
66// enables logging on all requests before they reach the mux router
67func httpInterceptor(router http.Handler) http.Handler {
68 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
69
70 startTime := time.Now()
71 router.ServeHTTP(w, r)
72 elapsedTime := time.Now().Sub(startTime)
73
74 log.WithFields(log.Fields{
75 "time": elapsedTime,
76 }).Debug(r.URL.Path)
77
78 })
79}
80
81func main() {
82
83 app := cliInit()
84
85 app.Action = func(c *cli.Context) {
86
87 if c.Bool("verbose") {
88 log.SetLevel(log.DebugLevel)
89 }
90
91 log.WithFields(log.Fields{"users": c.String("users")}).Info("Proxy Auth Initalizing Users...")
92 proxy := proxyInit(c.String("users"))
93
94 log.WithFields(log.Fields{"port": c.Int("port")}).Info("Proxy Auth API Server Starting...")
95 router := apiInit(proxy)
96 address := fmt.Sprintf(": %d", c.Int("port"))
97
98 // using default router with interceptor pattern (uses api mux)
99 http.Handle("/", httpInterceptor(router))
100 log.Fatal(http.ListenAndServe(address, nil))
101 }
102
103 app.Run(os.Args)
104}