func initAuth() { var err error // authFile must exist in site home. // could intruduce a way to dynamically create one or just default install it backend, err = httpauth.NewGobFileAuthBackend(authFile) if err != nil { panic(err) } // create some default roles roles = make(map[string]httpauth.Role) roles["user"] = 30 roles["admin"] = 80 aaa, err = httpauth.NewAuthorizer(backend, []byte("cookie-encryption-key"), "user", roles) // create a default user hash, err := bcrypt.GenerateFromPassword([]byte("adminadmin"), bcrypt.DefaultCost) if err != nil { panic(err) } defaultUser := httpauth.UserData{Username: "******", Email: "admin@localhost", Hash: hash, Role: "admin"} err = backend.SaveUser(defaultUser) if err != nil { panic(err) } }
func SetupAuth(pwfile string) *mux.Router { backendfile = pwfile os.Create(backendfile) backend_, err := httpauth.NewGobFileAuthBackend(backendfile) if err != nil { log.Fatal(err.Error()) } backend = backend_ roles = make(map[string]httpauth.Role) roles["user"] = 30 roles["admin"] = 80 aaa, err = httpauth.NewAuthorizer(backend, []byte("cookie-encryption-key"), "user", roles) if err != nil { log.Fatal(err.Error()) } router := mux.NewRouter() route := router.PathPrefix("/auth") r := route.Subrouter().StrictSlash(true) r.HandleFunc("/login", handleLogin).Methods("POST") r.HandleFunc("/logout", handleLogout) return router }
func main() { backend = httpauth.NewGobFileAuthBackend("auth.gob") aaa = httpauth.NewAuthorizer(backend, []byte("cookie-encryption-key")) // set up routers and route handlers r := mux.NewRouter() r.HandleFunc("/login", getLogin).Methods("GET") r.HandleFunc("/register", postRegister).Methods("POST") r.HandleFunc("/login", postLogin).Methods("POST") r.HandleFunc("/change", postChange).Methods("POST") r.HandleFunc("/", handlePage).Methods("GET") // authorized page r.HandleFunc("/logout", handleLogout) http.Handle("/", r) http.ListenAndServe(":8080", nil) }
func main() { var err error // create the backend storage, remove when all done os.Create(backendfile) defer os.Remove(backendfile) // create the backend backend, err = httpauth.NewGobFileAuthBackend(backendfile) if err != nil { panic(err) } // create some default roles roles = make(map[string]httpauth.Role) roles["user"] = 30 roles["admin"] = 80 aaa, err = httpauth.NewAuthorizer(backend, []byte("cookie-encryption-key"), "user", roles) // create a default user hash, err := bcrypt.GenerateFromPassword([]byte("adminadmin"), bcrypt.DefaultCost) if err != nil { panic(err) } defaultUser := httpauth.UserData{Username: "******", Email: "admin@localhost", Hash: hash, Role: "admin"} err = backend.SaveUser(defaultUser) if err != nil { panic(err) } // set up routers and route handlers r := mux.NewRouter() r.HandleFunc("/login", getLogin).Methods("GET") r.HandleFunc("/register", postRegister).Methods("POST") r.HandleFunc("/login", postLogin).Methods("POST") r.HandleFunc("/admin", handleAdmin).Methods("GET") r.HandleFunc("/add_user", postAddUser).Methods("POST") r.HandleFunc("/change", postChange).Methods("POST") r.HandleFunc("/", handlePage).Methods("GET") // authorized page r.HandleFunc("/logout", handleLogout) http.Handle("/", r) fmt.Printf("Server running on port %d\n", port) http.ListenAndServe(fmt.Sprintf(":%d", port), nil) }
func main() { configFile := flag.String("c", "gong.conf", "") flag.Usage = func() { fmt.Println("Usage: gong [-c gong.conf] [-l logfile]") os.Exit(1) } flag.Parse() var err error config, err := loadConfig(*configFile) if err != nil { log.Fatal(err) } // Parse templates. HTML = html.Must(html.ParseGlob(config.TemplatesDir + "/*.html")) TEXT = text.Must(text.ParseGlob(config.TemplatesDir + "/*.txt")) // Set up databases. db, err := sql.Open("mysql", config.DB.MySQL) if err != nil { log.Fatal(err) } // Set GOMAXPROCS and show server info. var cpuinfo string if n := runtime.NumCPU(); n > 1 { runtime.GOMAXPROCS(n) cpuinfo = fmt.Sprintf("%d CPUs", n) } else { cpuinfo = "1 CPU" } log.Printf("%s %s (%s)", APPNAME, VERSION, cpuinfo) // Initialize auth os.Create(backendfile) defer os.Remove(backendfile) // create the backend backend, err = httpauth.NewGobFileAuthBackend(backendfile) if err != nil { log.Println(err) } // create some default roles roles = make(map[string]httpauth.Role) roles["user"] = 30 roles["admin"] = 80 aaa, err = httpauth.NewAuthorizer(backend, []byte("cookie-encryption-key"), "user", roles) // create a default user hash, err := bcrypt.GenerateFromPassword([]byte("adminadmin"), bcrypt.DefaultCost) if err != nil { log.Println(err) } defaultUser := httpauth.UserData{Username: "******", Email: "admin@localhost", Hash: hash, Role: "admin"} err = backend.SaveUser(defaultUser) if err != nil { log.Println(err) } // Start HTTP server. s := new(httpServer) s.init(config, db) go s.ListenAndServe() go s.ListenAndServeTLS() // Sleep forever. select {} }
/** * This is the standard main function */ func main() { SetLoggerLevel(conf.LoggerLevel) var logger = NewPrefixed("main#main") confFilePath := "" baseName := filepath.Base(os.Args[0]) jsonConfFileName := baseName + ".json" dirName, err := filepath.Abs(filepath.Dir(os.Args[0])) if err != nil { logger.Fatal("%v", err) } if len(os.Args) > 1 { confFilePath = os.Args[1] } jsonConfFile, err := os.Open(confFilePath) if err != nil { logger.Debug("Can't find json conf file : %v", confFilePath) confFilePath, err = filepath.Abs(dirName + "/../conf/" + jsonConfFileName) } jsonConfFile, err = os.Open(confFilePath) if err != nil { logger.Debug("Can't find json conf file : %v", confFilePath) confFilePath = "/etc/" + jsonConfFileName } jsonConfFile, err = os.Open(confFilePath) if err != nil { logger.Fatal("Can't find json conf file : %v", confFilePath) } decoder := json.NewDecoder(jsonConfFile) err = decoder.Decode(&conf) if err != nil { fmt.Println("error:", err) } logger.Info("%v", conf) if conf.CACertPath == "" { logger.Warn("CA certificate path is not set: X509 credentials refused") } if conf.CertPath == "" { logger.Fatal("server certificate path is not set") } if conf.KeyPath == "" { logger.Fatal("server key path is not set") } oauthConfigurationChannels = make(map[string]chan *oauth2.Config) hostName := GetLocalHostName() for _, s := range conf.OAuthServers { if len(s.Name) < 1 || len(s.Clientid) < 1 || len(s.Clientsecret) < 1 || len(s.RedirectUrl) < 1 || len(s.AuthUrl) < 1 || len(s.TokenUrl) < 1 { logger.Warn("Ignoring %v : incorrect configuration", s.Name) continue } // // start OAuth config manager // logger.Info("s.Name = %v", s.Name) oauthConfigurationChannels[s.Name] = make(chan *oauth2.Config) go OAuthConfigurationManager( s.Clientid, s.Clientsecret, s.RedirectUrl, s.AuthUrl, s.TokenUrl, oauthConfigurationChannels[s.Name]) } // // start CA cert pool manager // var caCertPool *x509.CertPool caChannel = nil caCertPool = nil if conf.CACertPath != "" { caChannel = make(chan *x509.CertPool) go CaCertPoolManager(conf.CACertPath, caChannel) // // get CA cert pool // caCertPool := <-caChannel logger.Debug("CA pool length = %v", len(caCertPool.Subjects())) } // // Retrieve certificate // cert, err := TLSCerficateFromPEMs(conf.CertPath, conf.KeyPath) if err != nil { logger.Fatal(err.Error()) } logger.Debug("serverCert.Subject = %v", cert.Leaf.Subject) logger.Debug("serverCert.Issuer = %v", cert.Leaf.Issuer) // // Verify cert against known CA // if caCertPool != nil { vOpts := x509.VerifyOptions{Roots: caCertPool} _, err = cert.Leaf.Verify(vOpts) if err != nil { logger.Warn("failed to parse server certificate: " + err.Error()) } } tlsConfig := TLSConfig(cert, caCertPool) os.Create(backendfile) defer os.Remove(backendfile) backend, err = httpauth.NewGobFileAuthBackend(backendfile) if err != nil { logger.Fatal("can't create backend %v", err) } // create some default roles roles = make(map[string]httpauth.Role) roles["user"] = 30 roles["admin"] = 80 httpAuthorizer, err = httpauth.NewAuthorizer(backend, []byte("cookie-encryption-key"), "user", roles) // set up routers and route handlers r := mux.NewRouter() // r.HandleFunc("/", handlePage).Methods("GET") // authorized page r.HandleFunc("/logout", handleLogout) r.HandleFunc(ROOTURL, X509Authenticator) r.HandleFunc(OAUTHURL, OAuthenticationPage) for _, s := range conf.OAuthServers { r.HandleFunc(OAUTHURL+s.Name, OAuthAuthenticator) } r.HandleFunc(APPSURL, handlePage) r.HandleFunc(JWTURL, JWTAuthenticator) server := http.Server{Addr: hostName + ":" + conf.PortNumber, TLSConfig: tlsConfig, Handler: r} // start https logger.Info("Listening HTTPS : " + hostName + ":" + conf.PortNumber) server.ListenAndServeTLS(conf.CertPath, conf.KeyPath) }