作者:zaland
项目:skippe
// Creates out basicAuth Filter
// The first params specifies the used htpasswd file
// The second is optional and defines the realm name
func (spec *basicSpec) CreateFilter(config []interface{}) (filters.Filter, error) {
if len(config) == 0 {
return nil, filters.ErrInvalidFilterParameters
}
configFile, ok := config[0].(string)
if !ok {
return nil, filters.ErrInvalidFilterParameters
}
realmName := DefaultRealmName
if len(config) == 2 {
if definedName, ok := config[1].(string); ok {
realmName = definedName
}
}
htpasswd := auth.HtpasswdFileProvider(configFile)
authenticator := auth.NewBasicAuthenticator(realmName, htpasswd)
return &basic{
authenticator: authenticator,
realmDefinition: ForceBasicAuthHeaderValue + `"` + realmName + `"`,
}, nil
}
作者:jacobx
项目:burntsushi-blo
// main sets up the routes (thanks Gorilla!).
func main() {
r := mux.NewRouter()
r.HandleFunc("/", showIndex)
r.HandleFunc("/about", showAbout)
r.HandleFunc("/archives", showArchives)
r.PathPrefix("/static").
Handler(http.StripPrefix("/static",
http.FileServer(http.Dir(staticPath))))
// Password protect data refreshing
authenticator := auth.NewBasicAuthenticator(
"Refresh data", auth.HtpasswdFileProvider(*htpasswd))
r.HandleFunc("/refresh", auth.JustCheck(authenticator, showRefresh))
// These must be last. The first shows blog posts, the second adds comments.
r.HandleFunc("/{postname}", showPost).Methods("GET")
r.HandleFunc("/{postname}", addComment).Methods("POST")
// Captcha!
http.Handle("/captcha/",
captcha.Server(captcha.StdWidth, captcha.StdHeight))
// Okay, let Gorilla do its work.
http.Handle("/", r)
http.ListenAndServe(":8082", nil)
}
作者:alena110
项目:kubernete
func RegisterHandlers(mux httpMux.Mux, containerManager manager.Manager, httpAuthFile, httpAuthRealm, httpDigestFile, httpDigestRealm, prometheusEndpoint string) error {
// Basic health handler.
if err := healthz.RegisterHandler(mux); err != nil {
return fmt.Errorf("failed to register healthz handler: %s", err)
}
// Validation/Debug handler.
mux.HandleFunc(validate.ValidatePage, func(w http.ResponseWriter, r *http.Request) {
err := validate.HandleRequest(w, containerManager)
if err != nil {
fmt.Fprintf(w, "%s", err)
}
})
// Register API handler.
if err := api.RegisterHandlers(mux, containerManager); err != nil {
return fmt.Errorf("failed to register API handlers: %s", err)
}
// Redirect / to containers page.
mux.Handle("/", http.RedirectHandler(pages.ContainersPage, http.StatusTemporaryRedirect))
var authenticated bool = false
// Setup the authenticator object
if httpAuthFile != "" {
glog.Infof("Using auth file %s", httpAuthFile)
secrets := auth.HtpasswdFileProvider(httpAuthFile)
authenticator := auth.NewBasicAuthenticator(httpAuthRealm, secrets)
mux.HandleFunc(static.StaticResource, authenticator.Wrap(staticHandler))
if err := pages.RegisterHandlersBasic(mux, containerManager, authenticator); err != nil {
return fmt.Errorf("failed to register pages auth handlers: %s", err)
}
authenticated = true
}
if httpAuthFile == "" && httpDigestFile != "" {
glog.Infof("Using digest file %s", httpDigestFile)
secrets := auth.HtdigestFileProvider(httpDigestFile)
authenticator := auth.NewDigestAuthenticator(httpDigestRealm, secrets)
mux.HandleFunc(static.StaticResource, authenticator.Wrap(staticHandler))
if err := pages.RegisterHandlersDigest(mux, containerManager, authenticator); err != nil {
return fmt.Errorf("failed to register pages digest handlers: %s", err)
}
authenticated = true
}
// Change handler based on authenticator initalization
if !authenticated {
mux.HandleFunc(static.StaticResource, staticHandlerNoAuth)
if err := pages.RegisterHandlersBasic(mux, containerManager, nil); err != nil {
return fmt.Errorf("failed to register pages handlers: %s", err)
}
}
collector := metrics.NewPrometheusCollector(containerManager)
prometheus.MustRegister(collector)
http.Handle(prometheusEndpoint, prometheus.Handler())
return nil
}
作者:spkan
项目:sysrepor
func main() {
flag.Parse()
if *debugPtr == true {
fmt.Println("Console debug output enabled.")
}
urlport := ":" + strconv.Itoa(*portPtr)
authenticator := auth.NewBasicAuthenticator("sysreport", Secret)
if *authPtr == true {
http.HandleFunc("/", authenticator.Wrap(authRootViewHandler))
http.HandleFunc("/packages", authenticator.Wrap(authPackagesViewHandler))
http.HandleFunc("/facter", authenticator.Wrap(authFacterViewHandler))
http.HandleFunc("/ohai", authenticator.Wrap(authOhaiViewHandler))
} else {
http.HandleFunc("/", rootViewHandler)
http.HandleFunc("/packages", packagesViewHandler)
http.HandleFunc("/facter", facterViewHandler)
http.HandleFunc("/ohai", ohaiViewHandler)
}
if *sslPtr == true {
http.ListenAndServeTLS(urlport, *cpemPtr, *kpemPtr, nil)
} else {
http.ListenAndServe(urlport, nil)
}
}
作者:custodia
项目:lifds-c
func runControlServer() {
authenticator := auth.NewBasicAuthenticator("localhost", Secret)
http.HandleFunc("/server", authenticator.Wrap(ServerActionsHandler))
http.HandleFunc("/server/status", authenticator.Wrap(ServerStatusHandler))
http.Handle("/index.html", authenticator.Wrap(indexHandler))
http.Handle("/", http.FileServer(http.Dir("."+pathSeparator+"html")))
http.ListenAndServe(config["control-panel"]["address"]+":"+config["control-panel"]["port"], nil)
}
作者:jlhonor
项目:honorato.or
func main() {
log.Printf("Init")
dbinit()
defer dbclose()
authenticator := auth.NewBasicAuthenticator("127.0.0.1", Secret)
http.HandleFunc("/", authenticator.Wrap(handle))
log.Printf("Ready")
http.ListenAndServe(":8080", nil)
}
作者:skarneck
项目:gotai
func (mp *MainPage) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if mp.BasicAuth {
staticContentHandler := &Authentication{User: mp.UserName, Password: mp.UserPassword}
authWrapper := httpauth.NewBasicAuthenticator("Gotail", staticContentHandler.Secret)
authWrapper.Wrap(mp.AuthTail).ServeHTTP(w, r)
} else {
mp.Tail(w, r)
}
}
作者:nicklenstra-w
项目:trajector
func middleware(h http.HandlerFunc, middleware ...func(http.HandlerFunc) http.HandlerFunc) http.HandlerFunc {
for _, m := range middleware {
h = m(h)
}
// TODO: Get this to only be setup once.
authenticator := auth.NewBasicAuthenticator(
"trajectory.com", GetSecret(getLoginConfig()))
return auth.JustCheck(authenticator, h)
}
作者:nicklenstra-w
项目:trajector
func setupWeb() {
authenticator := auth.NewBasicAuthenticator(
"trajectory.com", GetSecret(getLoginConfig()))
http.HandleFunc(
"/",
authenticator.Wrap(func(
res http.ResponseWriter, req *auth.AuthenticatedRequest) {
http.FileServer(http.Dir("./web/")).ServeHTTP(res, &req.Request)
}))
}
作者:Pereir
项目:fstor
func StartHTTPServer(port string) {
htpasswd := auth.HtpasswdFileProvider(conf.PasswdFile)
authenticator := auth.NewBasicAuthenticator("Basic realm", htpasswd)
http.HandleFunc(ROUTE_INSERT, authenticator.Wrap(insertHandler))
http.HandleFunc(ROUTE_DELETE, authenticator.Wrap(deleteHandler))
http.HandleFunc(ROUTE_STATIC, authenticator.Wrap(staticHandler))
http.HandleFunc(ROUTE_GET, authenticator.Wrap(getHandler))
http.HandleFunc(ROUTE_LIST, authenticator.Wrap(listHandler))
//http.ListenAndServe(port, nil)
http.ListenAndServeTLS(port, conf.TLSPemFile, conf.TLSKeyFile, nil)
}
作者:brian-brazi
项目:mailexporte
func main() {
flag.Parse()
// seed the RNG, otherwise we would have same randomness on every startup
// which should not, but might in worst case interfere with leftover-mails
// from earlier starts of the binary
rand.Seed(time.Now().Unix())
err := parse_conf(*conf_path)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
wg := new(sync.WaitGroup)
wg.Add(len(globalconf.Servers))
// now fire up the monitoring jobs
for _, c := range globalconf.Servers {
fmt.Println("starting monitoring for config", c["Name"])
go monitor(c, wg)
// keep a timedelta between monitoring jobs to avoid strong interference
time.Sleep(startupOffsetTime)
}
fmt.Println("starting HTTP-endpoint")
if *useAuth {
authenticator := auth.NewBasicAuthenticator("prometheus", Secret)
http.HandleFunc(globalconf.Http_endpoint, auth.JustCheck(authenticator, prometheus.Handler().ServeHTTP))
} else {
http.Handle(globalconf.Http_endpoint, prometheus.Handler())
}
if *useTLS {
err = http.ListenAndServeTLS(":"+globalconf.Http_port, globalconf.Crt_path, globalconf.Key_path, nil)
} else {
err = http.ListenAndServe(":"+globalconf.Http_port, nil)
}
if err != nil {
fmt.Println(err)
}
// wait for goroutines to exit
// otherwise main would terminate and the goroutines monitoring would be killed
wg.Wait()
}
作者:jbuchbinde
项目:haproxy-confi
func main() {
flag.Parse()
PersistenceObj = GetPersistenceLayer(*persistence)
if PersistenceObj == nil {
log.Err("Unable to load persistence plugin " + *persistence)
panic("Dying")
}
var err error
ConfigObj, err = PersistenceObj.GetConfig()
if err != nil {
log.Err("Unable to load config from persistence plugin " + *persistence)
panic("Dying")
}
if ConfigObj.PidFile != *haproxyPidFile {
ConfigObj.PidFile = *haproxyPidFile
}
r := mux.NewRouter()
// Define paths
sub := r.PathPrefix("/api").Subrouter()
// Wire the UI (outside of muxer)
http.Handle("/ui/", http.StripPrefix("/ui/", http.FileServer(http.Dir(*uiLocation))))
// Display handlers
sub.HandleFunc("/config", configHandler).Methods("GET")
sub.HandleFunc("/reload", configReloadHandler).Methods("GET")
sub.HandleFunc("/backend/{backend}", backendHandler).Methods("GET")
sub.HandleFunc("/backend/{backend}", backendAddHandler).Methods("POST")
sub.HandleFunc("/backend/{backend}", backendDeleteHandler).Methods("DELETE")
sub.HandleFunc("/backend/{backend}/server/{server}", backendServerHandler).Methods("GET")
sub.HandleFunc("/backend/{backend}/server/{server}", backendServerAddHandler).Methods("POST")
sub.HandleFunc("/backend/{backend}/server/{server}", backendServerDeleteHandler).Methods("DELETE")
s := &http.Server{
Addr: *bind,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
}
h := auth.HtpasswdFileProvider(*htpasswd)
a := auth.NewBasicAuthenticator("haproxy config", h)
http.Handle("/", a.Wrap(func(w http.ResponseWriter, ar *auth.AuthenticatedRequest) {
r.ServeHTTP(w, &ar.Request)
}))
log.Err(s.ListenAndServe().Error())
}
作者:d-vandyshe
项目:web_access_acs_orio
func main() {
setLogging()
config = readConfig(getPath("conf"))
authenticator := auth.NewBasicAuthenticator(
"example.com",
func(user, realm string) string {
return Secret(config, user, realm)
})
http.HandleFunc("/", authenticator.Wrap(handle))
http.HandleFunc("/last-seen-employees", authenticator.Wrap(showLastSeenEmployees))
http.ListenAndServe(":8080", nil)
}
作者:dafit
项目:buffe
func (h *httpServer) Listen(address string) error {
fs := http.FileServer(http.Dir("web/assets"))
secrets := auth.HtpasswdFileProvider(h.secrets)
authenticator := auth.NewBasicAuthenticator("Basic Realm", secrets)
http.HandleFunc("/", h.Root)
http.Handle("/assets/", http.StripPrefix("/assets/", fs))
http.HandleFunc("/songs", h.Songs)
http.HandleFunc("/song/", h.Song)
http.HandleFunc("/ws", ws.Handle)
http.HandleFunc("/play/", authenticator.Wrap(h.Play))
return http.ListenAndServe(address, nil)
}
作者:n3r0-c
项目:ddeskto
func main() {
pwd, _ := os.Getwd()
//Set config path and type
viper.SetConfigName("config")
viper.AddConfigPath(pwd)
viper.AddConfigPath("/etc/ddesktop/")
viper.SetConfigType("yaml")
//Read config
err := viper.ReadInConfig()
if err != nil {
log.Fatalln(err)
}
log.Println(viper.GetString("container.prefix"))
//Cleanup existing containers
dockerhandler.CleanUp()
//Pull new docker image
if viper.GetBool("container.pull") {
dockerhandler.PullImage()
}
//Get authentication setting
htpasswd := auth.HtpasswdFileProvider(viper.GetString("htpasswd.path"))
authenticator := auth.NewBasicAuthenticator(".ddesktop", htpasswd)
//Start server
log.Printf("Starting server on http://0.0.0.0:" + viper.GetString("server.port.http") + " and https://0.0.0.0:" + viper.GetString("server.port.https") + "...")
http.Handle("/websockify", auth.JustCheck(authenticator, wsproxy.WsProxy()))
http.HandleFunc("/", auth.JustCheck(authenticator, server.Static()))
go func() {
if err := http.ListenAndServeTLS(":"+viper.GetString("server.port.https"), viper.GetString("ssl.cert"), viper.GetString("ssl.key"), nil); err != nil {
log.Fatalln(err)
}
}()
if err := http.ListenAndServe(":"+viper.GetString("server.port.http"), http.HandlerFunc(server.RedirectHttps)); err != nil {
log.Fatalln(err)
}
}
作者:yauhen-
项目:petruch
func main() {
var mongoUrl = flag.String("db", "petrucho-db", "MongoDB URL")
flag.Parse()
ctx := context.Background()
ctx = db.OpenMongoDB(ctx, "main", *mongoUrl)
defer db.Close(ctx)
kami.Context = ctx
secret := func(email, realm string) string {
u := User{}
users := userStorage(ctx)
err := users.Find(bson.M{"email": email, "confirmed": true}).One(&u)
if err != nil {
return ""
}
return u.Password
}
authenticator := auth.NewBasicAuthenticator("Restricted", secret)
kami.Get("/", homeHandler)
kami.Get("/register", registrationForm)
kami.Post("/register", registerUser)
kami.Get("/confirm/:token", confirmRegistration)
kami.Get("/users", viewAllUsers)
kami.Get("/users/:email", viewUser)
kami.Use("/users/:email/edit", func(ctx context.Context, w http.ResponseWriter, r *http.Request) context.Context {
var username string
authenticator.Wrap(func(w http.ResponseWriter, r *auth.AuthenticatedRequest) {
username = r.Username
})(w, r)
if len(username) == 0 {
return nil
}
return context.WithValue(ctx, "auth", username)
})
kami.Get("/users/:email/edit", editProfileForm)
kami.Post("/users/:email/edit", updateProfile)
kami.Serve()
}
作者:ugurata
项目:Echelo
func main() {
folderPath, errpath := osext.ExecutableFolder()
if errpath != nil {
fmt.Printf("Couldn't get cwd. Check permissions!\n")
return
}
if _, err := os.Stat(folderPath + ".htpasswd"); os.IsNotExist(err) {
fmt.Printf(folderPath + ".htpasswd doesn't exist in cwd!\n")
return
}
secrets := auth.HtpasswdFileProvider(folderPath + ".htpasswd")
authenticator := auth.NewBasicAuthenticator("Seyes Echelon", secrets)
http.HandleFunc("/record_log", auth.JustCheck(authenticator, handle))
fmt.Println("Server starting on port " + os.Args[1] + " ....\n")
http.ListenAndServe(":"+os.Args[1], nil)
}
作者:vitormour
项目:Laboratori
func New(runInDebugMode bool, templatesLocation string, usersPasswordFileLocation string, storageFactory model.VFStorageGroup, srvlog *logs.ServerLog) http.Handler {
if defaultRouter != nil {
return defaultRouter
}
serverlog = srvlog
defaultUserAuthenticator = auth.NewBasicAuthenticator("myrealm", auth.HtpasswdFileProvider(usersPasswordFileLocation))
defaultStorageFactory = storageFactory
results.TemplatesDir = templatesLocation
results.DebugMode = runInDebugMode
defaultRouter = mux.NewRouter()
adminRouter := mux.NewRouter()
apiRouter := mux.NewRouter()
handleVFolder(apiRouter)
handleCtrlPanel(adminRouter)
handlePlayground(apiRouter)
defaultRouter.PathPrefix("/api").Handler(
negroni.New(
negroni.HandlerFunc(authorized),
negroni.Wrap(apiRouter),
),
)
defaultRouter.PathPrefix("/admin").Handler(
negroni.New(
negroni.HandlerFunc(authorized),
negroni.HandlerFunc(adminOnly),
negroni.Wrap(adminRouter),
),
)
defaultRouter.PathPrefix("/static").Handler(http.StripPrefix("/static", http.FileServer(http.Dir("./server/static"))))
return defaultRouter
}
作者:yinwer8
项目:haproxyconsol
func main() {
programName := os.Args[0]
absPath, _ := filepath.Abs(programName)
haproxyConsoleRoot = path.Dir(path.Dir(absPath))
port := flag.String("p", "9090", "port to run the web server")
configuration := flag.String("config", "", "path to the app config file")
toolMode := flag.Bool("t", false, "run this program as a tool to export data from database to json or from json to database")
flag.Parse()
configPath := *configuration
if configPath == "" {
defaultConfigPath := haproxyConsoleRoot + "/conf/app_conf.ini"
fmt.Printf("You not set the configPath, so try to use the default config path: %s\n", defaultConfigPath)
if _, e := os.Stat(defaultConfigPath); os.IsNotExist(e) {
fmt.Println("Not Exit default config file")
os.Exit(1)
} else {
configPath = defaultConfigPath
}
}
var err error
logger = getLogger()
appConf, err = config.ParseConfig(configPath)
if err != nil {
fmt.Println(err)
return
}
if *toolMode {
// 数据转换存储方式
err := tools.StorageTransform(appConf)
tools.CheckError(err)
} else {
// 存储连接初始化
db, err = applicationDB.InitStoreConnection(appConf)
if err != nil {
logger.Fatalln(err)
os.Exit(1)
}
defer db.Close()
// 请求路由
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir(haproxyConsoleRoot+"/static/"))))
// basic auth user: admin, passwd: [email protected]
authenticator := auth.NewBasicAuthenticator("HAProxyConsole", auth.HtpasswdFileProvider(haproxyConsoleRoot+"/conf/md5passwd"))
http.HandleFunc("/applyvport", authenticator.Wrap(applyVPort))
http.HandleFunc("/edittask", authenticator.Wrap(editTask))
http.HandleFunc("/listenlist", authenticator.Wrap(getListenList))
http.HandleFunc("/dellistentask", authenticator.Wrap(delListenTask))
http.HandleFunc("/applyconf", authenticator.Wrap(applyConf))
http.HandleFunc("/statspage", statsPage)
http.HandleFunc("/", authenticator.Wrap(getHomePage))
// 启动http服务
err = http.ListenAndServe(":"+*port, nil)
if err != nil {
logger.Fatalln("ListenAndServe: ", err)
}
}
}
作者:vindal
项目:vindal
func NewHttpBasicAuthenticator(htpasswdFile string) *HttpBasicAuthenticator {
return &HttpBasicAuthenticator{
//secretFunc: httpauth.HtpasswdFileProvider(htpasswdFile),
basicAuth: httpauth.NewBasicAuthenticator("vindalu", httpauth.HtpasswdFileProvider(htpasswdFile)),
}
}