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 (auth *AuthHTTP) createRoles() { var err error roles := make(map[string]httpauth.Role) roles["user"] = 30 roles["admin"] = 80 auth.aaa, err = httpauth.NewAuthorizer(auth.backend, []byte("topsecretkey"), "user", roles) if err != nil { log.Printf("Error creating roles: %s", err) } }
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 os.Mkdir(backendfile, 0755) defer os.Remove(backendfile) // create the backend backend, err = httpauth.NewLeveldbAuthBackend(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 username := "******" defaultUser := httpauth.UserData{Username: username, Role: "admin"} err = backend.SaveUser(defaultUser) if err != nil { panic(err) } // Update user with a password and email address err = aaa.Update(nil, nil, username, "adminadmin", "*****@*****.**") 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() { var err error // Setup the main db. var db *sql.DB err = pinger.CreatePingerLog("", false) if err != nil { fatalError("Failed to initialize logging:", err) } startLog("Starting go-ping-sites version " + version + ", website on port " + config.Settings.Website.HTTPPort + "...") db, err = database.InitializeDB("go-ping-sites.db", "db-seed.toml") if err != nil { fatalError("Failed to initialize database:", err) } defer db.Close() // Validate the required config for the website. _, err = govalidator.ValidateStruct(config.Settings.Website) if err != nil { fatalError("Error in config.toml configuration:", err) } // Setup the auth // create the authorization backend authBackend, err = createAuthBackendFile() if err != nil { fatalError("Failed to create Auth Backend: ", err) } cookieKey := []byte(config.Settings.Website.CookieKey) secureCookie := config.Settings.Website.SecureHTTPS roles = getRoles() authorizer, err = httpauth.NewAuthorizer(authBackend, cookieKey, "user", roles) createDefaultUser() // Start the Pinger p := pinger.NewPinger(db, pinger.GetSites, pinger.RequestURL, notifier.SendEmail, notifier.SendSms) p.Start() // Start the web server. templates := controllers.PopulateTemplates("templates") controllers.Register(db, authorizer, authBackend, roles, templates, p, version, cookieKey, secureCookie) err = http.ListenAndServe(":"+config.Settings.Website.HTTPPort, nil) // set listen port if err != nil { fatalError("ListenAndServe: ", err) } }
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) }
func main() { var err error // create the backend backend, err = httpauth.NewSqlAuthBackend("mysql", backenddb) if err != nil { panic(err) } defer backend.Close() game = make(map[string]*Buscaminas) players = make(map[int][2]string) connPlayer = make(map[string]*connection) notifications = make(map[string][]int) notif = make(map[int]*Notification) privateGame = make(map[int]bool) // 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) } // Handles mux = make(map[string]map[string]func(http.ResponseWriter, *http.Request)) // addRoute(route, handleFunction, methods) mux.addRoute("/", handleHome, []string{"GET", "POST"}) mux.addRoute("/login", getLogin, []string{"GET"}) mux.addRoute("/login", postLogin, []string{"POST"}) mux.addRoute("/register", postRegister, []string{"POST"}) mux.addRoute("/logout", handleLogout, []string{"GET", "POST"}) mux.addRoute("/lobby", handleLobby, []string{"GET", "POST"}) mux.addRoute("/lobby/games", handleLobbyGames, []string{"GET", "POST"}) mux.addRoute("/lobby/players", handleLobbyPlayers, []string{"GET", "POST"}) mux.addRoute("/lobby/challenge", handleLobbyChallenge, []string{"GET", "POST"}) mux.addRoute("/game", handleGame, []string{"GET", "POST"}) mux.addRoute("/game/init", handleGameInit, []string{"GET", "POST"}) mux.addRoute("/game/move", handleGameMove, []string{"GET", "POST"}) mux.addRoute("/game/data", handleGameData, []string{"GET", "POST"}) mux.addRoute("/game/joinGame", handleGameJoinGame, []string{"GET", "POST"}) mux.addRoute("/game/exit", handleGameExit, []string{"GET", "POST"}) mux.addRoute("/misc/notification/get", handleNotificationGet, []string{"GET", "POST"}) mux.addRoute("/misc/notification/reject/game", handleNotificationRejectGame, []string{"GET", "POST"}) mux.addRoute("/misc/notification/seen", handleNotificationSeen, []string{"GET", "POST"}) hub := newHub() go hub.run() filehttp.Handle("/", http.FileServer(http.Dir("../"))) // files wshttp.Handle("/ws", wsHandler{h: hub}) // websocket fmt.Printf("Server running on port %d\n", port) var mh *myHandler go CleanLoggedUsers() http.ListenAndServe(fmt.Sprintf(":%d", port), mh) }
func main() { var err error // create the backend backend, err = httpauth.NewSqlAuthBackend("mysql", backenddb) if err != nil { panic(err) } defer backend.Close() games = make(map[string]*buscaminas2p.Buscaminas) players = make(map[int][2]string) // 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) } // Handles mux = make(map[string]map[string]func(http.ResponseWriter, *http.Request)) // addRoute(route, handleFunction, methods) mux.addRoute("/", handleHome, []string{"GET", "POST"}) mux.addRoute("/login", getLogin, []string{"GET"}) mux.addRoute("/login", postLogin, []string{"POST"}) mux.addRoute("/register", postRegister, []string{"POST"}) mux.addRoute("/logout", handleLogout, []string{"GET", "POST"}) mux.addRoute("/lobby", handleLobby, []string{"GET", "POST"}) mux.addRoute("/lobby/games", handleLobbyGames, []string{"GET", "POST"}) mux.addRoute("/lobby/players", handleLobbyPlayers, []string{"GET", "POST"}) mux.addRoute("/game", handleGame, []string{"GET", "POST"}) mux.addRoute("/game/move", handleGameMove, []string{"GET", "POST"}) mux.addRoute("/game/data", handleGameData, []string{"GET", "POST"}) mux.addRoute("/game/joinGame", handleGameJoinGame, []string{"GET", "POST"}) mux.addRoute("/game/exit", handleGameExit, []string{"GET", "POST"}) mux.addRoute("/game/chat", handleGameChat, []string{"GET", "POST"}) filehttp.Handle("/", http.FileServer(http.Dir("../"))) fmt.Printf("Server running on port %d\n", port) var mh *myHandler go CleanLoggedUsers() http.ListenAndServe(fmt.Sprintf(":%d", port), mh) }