Beispiel #1
0
func dirList(ci inject.CopyInject, logger termlog.Logger, w http.ResponseWriter, name string, f http.File, templates *template.Template) {
	w.Header().Set("Cache-Control", "no-store, must-revalidate")
	files, err := f.Readdir(0)
	if err != nil {
		logger.Shout("Error reading directory for listing: %s", err)
		return
	}
	data := dirData{Name: name, Files: files}
	buff := bytes.NewBuffer(make([]byte, 0, 0))
	err = templates.Lookup("dirlist.html").Execute(buff, data)
	length := buff.Len()
	if err != nil {
		logger.Shout("Error producing directory listing: %s", err)
	}
	inj, err := ci.Sniff(buff)
	if err != nil {
		logger.Shout("Failed to inject in dir listing: %s", err)
		return
	}
	w.Header().Set(
		"Content-Length", fmt.Sprintf("%d", length+inj.Extra()),
	)
	_, err = inj.Copy(w)
	if err != nil {
		logger.Shout("Failed to inject in dir listing: %s", err)
		return
	}
}
Beispiel #2
0
func (context *Context) Execute(name string, result interface{}) {
	var tmpl *template.Template
	var cacheKey string

	if context.Action == "" {
		context.Action = name
	}

	if context.Resource != nil {
		cacheKey = path.Join(context.resourcePath(), name)
	} else {
		cacheKey = name
	}

	if t, ok := templates[cacheKey]; !ok || true {
		var err error
		tmpl = template.New("layout.tmpl").Funcs(context.FuncMap())
		if tmpl, err = context.FindTemplate(tmpl, "layout.tmpl"); err == nil {
			for _, name := range []string{"header", "footer"} {
				if tmpl.Lookup(name) == nil {
					tmpl, _ = context.FindTemplate(tmpl, name+".tmpl")
				}
			}
		}
	} else {
		tmpl = t
	}

	context.Content = context.Render(name, result)
	if err := tmpl.Execute(context.Writer, context); err != nil {
		fmt.Println(err)
	}
}
Beispiel #3
0
func (r *TemplateRender) initTemplates(t *template.Template, tmps []string, exclude *[]string) error {
	firstLevel := 0 == len(*exclude)
	for tkey, tpl := range r.prepareTemplates(tmps...) {
		if nil == t.Lookup(tkey) {
			if data, err := ioutil.ReadFile(tpl); nil == err {
				tmps := templatesRegex.FindAllStringSubmatch(string(data), -1)

				ntemplates := []string{}
				if nil != tmps && len(tmps) > 0 {
					for _, it := range tmps {
						if sIndexOf(it[1], *exclude) < 0 {
							*exclude = append(*exclude, it[1])
							ntemplates = append(ntemplates, it[1])
						}
					}
				}

				// Prepare new templates
				if len(ntemplates) > 0 {
					if err = r.initTemplates(t, ntemplates, exclude); nil != err {
						return err
					}
				}

				if _, err = t.New(tkey).Parse(string(data)); nil != err {
					return err
				}
			} else if firstLevel {
				return err
			}
		}
	}
	return nil
}
Beispiel #4
0
func findTemplate(name string, tpls *template.Template) (*template.Template, error) {
	tpl := tpls.Lookup(name)
	if tpl == nil {
		return nil, fmt.Errorf("unable to find template: %q", name)
	}
	return tpl, nil
}
Beispiel #5
0
func notFound(ci inject.CopyInject, templates *template.Template, w http.ResponseWriter) error {
	err := ci.ServeTemplate(http.StatusNotFound, w, templates.Lookup("404.html"), nil)
	if err != nil {
		return err
	}
	return nil
}
Beispiel #6
0
func readtemplates(dir string, titles map[Language]string) (err error) {
	var templates *template.Template
	templates, err = template.New("base").Funcs(tmplFuncs).ParseGlob(dir + "/*.tmpl")
	if err != nil {
		return
	}
	var d *os.File
	d, err = os.Open(dir)
	if err != nil {
		return
	}
	var v []os.FileInfo
	v, err = d.Readdir(0)
	if err != nil {
		return
	}
	for _, fi := range v {
		if fi.IsDir() {
			var t *template.Template
			t, err = templates.Clone()
			if err != nil {
				return
			}
			subdir := dir + "/" + fi.Name()
			_, err = t.ParseGlob(subdir + "/*.tmpl")
			if err != nil {
				return
			}
			th := t.Lookup("home")
			ti := t.Lookup("info")
			if th == nil {
				return fmt.Errorf(`Template "home" is missing in %s`, subdir)
			}
			if ti == nil {
				return fmt.Errorf(`Template "info" is missing in %s`, subdir)
			}
			title, ok := "", false
			if title, ok = titles[Language(fi.Name())]; !ok {
				if title, ok = titles[defaultlang]; !ok {
					title = "Uploader"
				}
			}
			langtmpl[Language(fi.Name())] = &tmpl{title, th, ti}
		}
	}
	defaulttmpl = langtmpl[defaultlang]
	if defaulttmpl == nil {
		fmt.Errorf("missing " + string(defaultlang) + " template")
	}
	languages = make([]Language, 0, len(langtmpl))
	languages = append(languages, defaultlang)
	for k := range langtmpl {
		if k != defaultlang {
			languages = append(languages, k)
		}
	}
	return
}
Beispiel #7
0
// HandleNotFound handles pages not found. In particular, this handler is used
// when we have no matching route for a request. This also means it's not
// useful to inject the livereload paraphernalia here.
func HandleNotFound(templates *template.Template) httpctx.Handler {
	return httpctx.HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusNotFound)
		err := templates.Lookup("404.html").Execute(w, nil)
		if err != nil {
			logger := termlog.FromContext(ctx)
			logger.Shout("Could not execute template: %s", err)
		}
	})
}
Beispiel #8
0
func (f *RestHtmlFormattor) getMethodTemplate(m *template.Template, rest *RestContext) *template.Template {
	t := m.Lookup(rest.Method + f.dotsuffix)
	var err error
	if t == nil {
		t, err = m.New(rest.Method + f.dotsuffix).ParseFiles(filepath.Join(document_root, rest.Url, rest.Method+f.dotsuffix))
		if err != nil {
			fmt.Println("ERROR template.ParseFile: %v", err)
		}
	}
	return t
}
Beispiel #9
0
func dirList(ci inject.CopyInject, logger termlog.Logger, w http.ResponseWriter, name string, f http.File, templates *template.Template) {
	w.Header().Set("Cache-Control", "no-store, must-revalidate")
	files, err := f.Readdir(0)
	if err != nil {
		logger.Shout("Error reading directory for listing: %s", err)
		return
	}
	data := dirData{Name: name, Files: files}
	err = ci.ServeTemplate(http.StatusOK, w, templates.Lookup("dirlist.html"), data)
	if err != nil {
		logger.Shout("Failed to generate dir listing: %s", err)
	}
}
Beispiel #10
0
func (p *Page) Render(outdir string, templates *template.Template) error {
	tpl := templates.Lookup(p.Template)
	if tpl == nil {
		return fmt.Errorf("page: template %q not found", p.Template)
	}
	if err := os.MkdirAll(filepath.Join(outdir, filepath.Dir(p.Filename)), 0755); err != nil {
		return err
	}
	f, err := os.Create(filepath.Join(outdir, p.Filename))
	if err != nil {
		return err
	}
	defer f.Close()
	return tpl.Execute(f, p)
}
Beispiel #11
0
func (cfg *LocalConnectorConfig) Connector(ns url.URL, lf oidc.LoginFunc, tpls *template.Template) (Connector, error) {
	tpl := tpls.Lookup(LoginPageTemplateName)
	if tpl == nil {
		return nil, fmt.Errorf("unable to find necessary HTML template")
	}

	idpc := &LocalConnector{
		id:        cfg.ID,
		namespace: ns,
		loginFunc: lf,
		loginTpl:  tpl,
	}

	return idpc, nil
}
Beispiel #12
0
func optionalTemplate(t *template.Template) func(string, ...interface{}) (template.HTML, error) {
	return func(name string, data ...interface{}) (template.HTML, error) {
		var tm = t.Lookup(name)
		if tm != nil {
			var b bytes.Buffer
			err := tm.ExecuteTemplate(&b, name, data)
			if err != nil {
				return template.HTML(""), err
			}
			return template.HTML(b.String()), nil
		} else {
			return template.HTML(""), nil
		}
	}
}
Beispiel #13
0
func (context *Context) Execute(name string, result interface{}) {
	var tmpl *template.Template
	var cacheKey string

	if name == "show" && !context.Resource.isSetShowAttrs {
		name = "edit"
	}

	if context.Action == "" {
		context.Action = name
	}

	if context.Resource != nil {
		cacheKey = path.Join(context.resourcePath(), name)
	} else {
		cacheKey = name
	}

	if t, ok := templates[cacheKey]; !ok || true {
		if file, err := context.FindTemplate("layout.tmpl"); err == nil {
			if tmpl, err = template.New(filepath.Base(file)).Funcs(context.FuncMap()).ParseFiles(file); err == nil {
				for _, name := range []string{"header", "footer"} {
					if tmpl.Lookup(name) == nil {
						if file, err := context.FindTemplate(name + ".tmpl"); err == nil {
							tmpl.ParseFiles(file)
						}
					} else {
						utils.ExitWithMsg(err)
					}
				}
			} else {
				utils.ExitWithMsg(err)
			}
		}
	} else {
		tmpl = t
	}

	context.Result = result
	context.Content = context.Render(name, result)
	if err := tmpl.Execute(context.Writer, context); err != nil {
		utils.ExitWithMsg(err)
	}
}
Beispiel #14
0
func executeTpl(ctx echo.Context, tpl *template.Template, data map[string]interface{}) error {
	objLog := logic.GetLogger(ctx)

	// 如果没有定义css和js模板,则定义之
	if jsTpl := tpl.Lookup("js"); jsTpl == nil {
		tpl.Parse(`{{define "js"}}{{end}}`)
	}
	if jsTpl := tpl.Lookup("css"); jsTpl == nil {
		tpl.Parse(`{{define "css"}}{{end}}`)
	}

	// 当前用户信息
	curUser, ok := ctx.Get("user").(*model.Me)
	if ok {
		data["me"] = curUser
	} else {
		data["me"] = map[string]interface{}{}
	}

	// websocket主机
	if global.OnlineEnv() {
		data["wshost"] = config.ConfigFile.MustValue("global", "domain")
	} else {
		data["wshost"] = global.App.Host + ":" + global.App.Port
	}
	global.App.SetUptime()
	data["app"] = global.App

	data["online_users"] = map[string]int{"online": logic.Book.Len(), "maxonline": logic.MaxOnlineNum()}

	buf := new(bytes.Buffer)
	err := tpl.Execute(buf, data)
	if err != nil {
		objLog.Errorln("excute template error:", err)
		return err
	}

	return ctx.HTML(http.StatusOK, buf.String())
}
Beispiel #15
0
func get(driver *Template, name string) *Template {

	var contents string
	var t *template.Template
	var err error

	pth := "resources/template/" + name + ".tmpl"
	partials := filepath.Join(filepath.Dir(pth), "partials", "_*.tmpl")

	contents, err = load(pth)
	if err != nil {
		return &Template{nil, err}
	}

	if driver != nil {
		t, err = driver.Clone()
		if err != nil {
			return &Template{nil, err}
		}

		_, err = t.Parse(contents)
		for _, name := range blocknames {
			if found := t.Lookup(name); found == nil {
				t.Parse("{{ define `" + name + "`}}{{ end }}")
			}
		}

		t.ParseGlob(partials)

	} else {
		t = template.New(name)
		if err != nil {
			return &Template{nil, err}
		}
		t, err = t.Funcs(funcMap).Parse(contents)
	}
	return &Template{t, err}
}
Beispiel #16
0
func (vc *viewContainer) getTemplateDeep(file, viewExt, parent string, t *template.Template) (*template.Template, [][]string, error) {
	var fileAbsPath string
	if filepath.HasPrefix(file, "../") {
		fileAbsPath = filepath.Join(vc.viewDir, filepath.Dir(parent), file)
	} else {
		fileAbsPath = filepath.Join(vc.viewDir, file)
	}
	if e := IsFile(fileAbsPath); !e {
		return nil, [][]string{}, errNotFoundTpl(file)
	}
	data, err := ioutil.ReadFile(fileAbsPath)
	if err != nil {
		return nil, [][]string{}, err
	}
	t, err = t.New(file).Parse(string(data))
	if err != nil {
		return nil, [][]string{}, err
	}
	reg := regexp.MustCompile("{{" + "[ ]*template[ ]+\"([^\"]+)\"")
	allSub := reg.FindAllStringSubmatch(byte2Str(data), -1)
	for _, m := range allSub {
		if len(m) == 2 {
			look := t.Lookup(m[1])
			if look != nil {
				continue
			}
			if !strings.HasSuffix(strings.ToLower(m[1]), viewExt) {
				continue
			}
			t, _, err = vc.getTemplateDeep(m[1], viewExt, file, t)
			if err != nil {
				return nil, [][]string{}, err
			}
		}
	}
	return t, allSub, nil
}
Beispiel #17
0
func getTplDeep(root, file, parent string, t *template.Template) (*template.Template, [][]string, error) {
	var fileAbsPath string
	if filepath.HasPrefix(file, "../") {
		fileAbsPath = filepath.Join(root, filepath.Dir(parent), file)
	} else {
		fileAbsPath = filepath.Join(root, file)
	}
	if e := utils.FileExists(fileAbsPath); !e {
		panic("can't find template file:" + file)
	}
	data, err := ioutil.ReadFile(fileAbsPath)
	if err != nil {
		return nil, [][]string{}, err
	}
	t, err = t.New(file).Parse(string(data))
	if err != nil {
		return nil, [][]string{}, err
	}
	reg := regexp.MustCompile(BConfig.WebConfig.TemplateLeft + "[ ]*template[ ]+\"([^\"]+)\"")
	allSub := reg.FindAllStringSubmatch(string(data), -1)
	for _, m := range allSub {
		if len(m) == 2 {
			tl := t.Lookup(m[1])
			if tl != nil {
				continue
			}
			if !HasTemplateExt(m[1]) {
				continue
			}
			t, _, err = getTplDeep(root, m[1], file, t)
			if err != nil {
				return nil, [][]string{}, err
			}
		}
	}
	return t, allSub, nil
}
Beispiel #18
0
//Register mounts an entry point at / on the supplied http mux.
//staticFiles is the directory that contains the CSS and .js files
//If no mux is supplied, it will be mounted by the default http.Handler
func Register(t *template.Template, staticFiles string, mux *http.ServeMux) {
	if mux == nil {
		mux = http.DefaultServeMux
	}

	//Instantiate our controllers
	indexController := indexController{template: t.Lookup("index.html")}
	settingsController := settingsController{template: t.Lookup("settings.html")}
	chatController := chatController{template: t.Lookup("chat.html")}
	accountsController := accountsController{template: t.Lookup("register.html")}

	//Associate routes with our controllers
	mux.Handle("/", indexController)
	mux.Handle("/settings/", settingsController)
	mux.Handle("/chat/", chatController)
	mux.Handle("/register/", accountsController)
	mux.Handle("/login", accountsController)
	mux.Handle("/logout", accountsController)

	mux.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir(staticFiles))))
	mux.Handle("/chat/socket", websocket.Handler(webSocketHandler))

}
Beispiel #19
0
func StartWeb() {
	store = sessions.NewCookieStore([]byte(Config.CookieSecret))

	staticServer := http.FileServer(http.Dir("./static"))
	http.Handle("/static/", http.StripPrefix("/static/", staticServer))

	var templates *template.Template
	ParseTemplates := func() *template.Template {
		tmpls := template.New("")
		err := filepath.Walk("./template", func(path string, info os.FileInfo, err error) error {
			if err != nil || info.IsDir() || !strings.HasSuffix(path, ".html") {
				return err
			}

			relativePath, err := filepath.Rel("./template", path)
			if err != nil {
				return err
			}

			subtmpl, err := template.ParseFiles(path)
			if err != nil {
				return err
			}

			_, err = tmpls.AddParseTree(relativePath, subtmpl.Tree)
			return err
		})
		if err != nil {
			log.Fatalln("Couldn't load HTML templates:", err.Error())
		}
		return tmpls
	}
	LookupTemplate := func(name string) *template.Template {
		tmpl := templates.Lookup(name)
		if tmpl == nil {
			log.Fatalln("Couldn't find HTML template", name)
		}
		return tmpl
	}

	// If in Debug mode, re-parse templates with each request.
	if Config.Debug {
		getTemplate = func(name string) *template.Template {
			templates = ParseTemplates()
			return LookupTemplate(name)
		}
	} else {
		getTemplate = LookupTemplate
	}

	http.HandleFunc("/signin", WebSignIn)
	http.HandleFunc("/signout", WebSignOut)

	webThingHandler := RequireAccountFunc(WebThing)
	http.Handle("/thing/", webThingHandler)
	http.Handle("/player/", webThingHandler)
	http.Handle("/place/", webThingHandler)
	http.Handle("/action/", webThingHandler)
	http.Handle("/program/", webThingHandler)

	webThingMux = http.NewServeMux()
	webThingMux.HandleFunc("/", WebThingEdit)
	webThingMux.HandleFunc("/table", WebThingTable)
	webThingMux.HandleFunc("/program", WebThingProgram)
	webThingMux.HandleFunc("/access", WebThingAccess)

	http.Handle("/create-thing", RequireAccountFunc(WebCreateThing))

	indexHandler := RequireAccountFunc(WebIndex)
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		if r.URL.String() != "/" {
			http.NotFound(w, r)
			return
		}
		indexHandler.ServeHTTP(w, r)
	})

	log.Println("Listening for web requests at address", Config.WebAddress)
	webHandler := context.ClearHandler(nosurf.New(http.DefaultServeMux))
	http.ListenAndServe(Config.WebAddress, webHandler)
}
// Register the handlers for a given route.
func Register(db *sql.DB, authorizer httpauth.Authorizer, authBackend httpauth.AuthBackend,
	roles map[string]httpauth.Role, templates *template.Template, pinger *pinger.Pinger,
	version string, cookieKey []byte, secureCookie bool) {

	// setup CSRF protection for the post requests.
	CSRF := csrf.Protect(cookieKey, csrf.Secure(secureCookie))
	router := mux.NewRouter()

	hc := new(homeController)
	hc.template = templates.Lookup("home.gohtml")
	hc.authorizer = authorizer
	hc.DB = db
	router.Handle("/", authorizeRole(appHandler(hc.get), authorizer, "user"))

	rc := new(reportsController)
	rc.template = templates.Lookup("reports.gohtml")
	rc.authorizer = authorizer
	rc.DB = db
	router.Handle("/reports", authorizeRole(appHandler(rc.get), authorizer, "user"))

	pc := new(profileController)
	pc.template = templates.Lookup("profile.gohtml")
	pc.authorizer = authorizer
	pc.authBackend = authBackend
	pc.DB = db
	router.Handle("/profile", authorizeRole(appHandler(pc.get), authorizer, "user")).Methods("GET")
	router.Handle("/profile", authorizeRole(appHandler(pc.post), authorizer, "user")).Methods("POST")

	ac := new(aboutController)
	ac.template = templates.Lookup("about.gohtml")
	ac.authorizer = authorizer
	ac.version = version
	router.HandleFunc("/about", ac.get)

	lc := new(loginController)
	lc.template = templates.Lookup("login.gohtml")
	lc.authorizer = authorizer
	router.HandleFunc("/login", lc.get).Methods("GET")
	router.HandleFunc("/login", lc.post).Methods("POST")

	loc := new(logoutController)
	loc.authorizer = authorizer
	router.HandleFunc("/logout", loc.get)

	sc := new(settingsController)
	sc.template = templates.Lookup("settings.gohtml")
	sc.authorizer = authorizer
	sc.DB = db
	router.Handle("/settings", authorizeRole(appHandler(sc.get), authorizer, "admin"))

	//settingsSub is a subrouter "/settings"
	settingsSub := router.PathPrefix("/settings").Subrouter()

	// /settings/users
	uc := new(usersController)
	uc.getTemplate = templates.Lookup("users.gohtml")
	uc.editTemplate = templates.Lookup("user_edit.gohtml")
	uc.newTemplate = templates.Lookup("user_new.gohtml")
	uc.deleteTemplate = templates.Lookup("user_delete.gohtml")
	uc.authorizer = authorizer
	uc.authBackend = authBackend
	uc.roles = roles
	settingsSub.Handle("/users", authorizeRole(appHandler(uc.get), authorizer, "admin"))
	settingsSub.Handle("/users/{username}/edit", authorizeRole(appHandler(uc.editGet), authorizer, "admin")).Methods("GET")
	settingsSub.Handle("/users/{username}/edit", authorizeRole(appHandler(uc.editPost), authorizer, "admin")).Methods("POST")
	settingsSub.Handle("/users/{username}/delete", authorizeRole(appHandler(uc.deleteGet), authorizer, "admin")).Methods("GET")
	settingsSub.Handle("/users/{username}/delete", authorizeRole(appHandler(uc.deletePost), authorizer, "admin")).Methods("POST")
	settingsSub.Handle("/users/new", authorizeRole(appHandler(uc.newGet), authorizer, "admin")).Methods("GET")
	settingsSub.Handle("/users/new", authorizeRole(appHandler(uc.newPost), authorizer, "admin")).Methods("POST")

	// /settings/contacts
	cc := new(contactsController)
	cc.getTemplate = templates.Lookup("contacts.gohtml")
	cc.editTemplate = templates.Lookup("contact_edit.gohtml")
	cc.newTemplate = templates.Lookup("contact_new.gohtml")
	cc.deleteTemplate = templates.Lookup("contact_delete.gohtml")
	cc.authorizer = authorizer
	cc.pinger = pinger
	cc.DB = db
	settingsSub.Handle("/contacts", authorizeRole(appHandler(cc.get), authorizer, "admin"))
	settingsSub.Handle("/contacts/{contactID}/edit", authorizeRole(appHandler(cc.editGet), authorizer, "admin")).Methods("GET")
	settingsSub.Handle("/contacts/{contactID}/edit", authorizeRole(appHandler(cc.editPost), authorizer, "admin")).Methods("POST")
	settingsSub.Handle("/contacts/{contactID}/delete", authorizeRole(appHandler(cc.deleteGet), authorizer, "admin")).Methods("GET")
	settingsSub.Handle("/contacts/{contactID}/delete", authorizeRole(appHandler(cc.deletePost), authorizer, "admin")).Methods("POST")
	settingsSub.Handle("/contacts/new", authorizeRole(appHandler(cc.newGet), authorizer, "admin")).Methods("GET")
	settingsSub.Handle("/contacts/new", authorizeRole(appHandler(cc.newPost), authorizer, "admin")).Methods("POST")

	// /settings/sites
	stc := new(sitesController)
	stc.detailsTemplate = templates.Lookup("site_details.gohtml")
	stc.editTemplate = templates.Lookup("site_edit.gohtml")
	stc.newTemplate = templates.Lookup("site_new.gohtml")
	stc.changeContactsTemplate = templates.Lookup("site_change_contacts.gohtml")
	stc.authorizer = authorizer
	stc.pinger = pinger
	stc.DB = db
	// Site list is handled on main settings page so not required here.
	settingsSub.Handle("/sites/new", authorizeRole(appHandler(stc.newGet), authorizer, "admin")).Methods("GET")
	settingsSub.Handle("/sites/new", authorizeRole(appHandler(stc.newPost), authorizer, "admin")).Methods("POST")
	settingsSub.Handle("/sites/{siteID}", authorizeRole(appHandler(stc.getDetails), authorizer, "admin"))
	settingsSub.Handle("/sites/{siteID}/edit", authorizeRole(appHandler(stc.editGet), authorizer, "admin")).Methods("GET")
	settingsSub.Handle("/sites/{siteID}/edit", authorizeRole(appHandler(stc.editPost), authorizer, "admin")).Methods("POST")

	// Wrap the router in the CSRF protection.
	http.Handle("/", CSRF(router))

	http.HandleFunc("/img/", serveResource)
	http.HandleFunc("/css/", serveResource)
	http.HandleFunc("/js/", serveResource)
	http.HandleFunc("/fonts/", serveResource)
}
Beispiel #21
0
func (cfg *LDAPConnectorConfig) Connector(ns url.URL, lf oidc.LoginFunc, tpls *template.Template) (Connector, error) {
	ns.Path = path.Join(ns.Path, httpPathCallback)
	tpl := tpls.Lookup(LDAPLoginPageTemplateName)
	if tpl == nil {
		return nil, fmt.Errorf("unable to find necessary HTML template")
	}

	if cfg.UseTLS && cfg.UseSSL {
		return nil, fmt.Errorf("Invalid configuration. useTLS and useSSL are mutual exclusive.")
	}

	if len(cfg.CertFile) > 0 && len(cfg.KeyFile) == 0 {
		return nil, fmt.Errorf("Invalid configuration. Both certFile and keyFile must be specified.")
	}

	// Set default values
	if cfg.NameAttribute == "" {
		cfg.NameAttribute = "cn"
	}
	if cfg.EmailAttribute == "" {
		cfg.EmailAttribute = "mail"
	}
	if cfg.MaxIdleConn > 0 {
		cfg.MaxIdleConn = 5
	}
	if cfg.BindTemplate == "" {
		cfg.BindTemplate = "uid=%u,%b"
	} else if cfg.SearchBeforeAuth {
		log.Warningf("bindTemplate not used when searchBeforeAuth specified.")
	}
	searchScope := ldap.ScopeWholeSubtree
	if cfg.SearchScope != "" {
		switch {
		case strings.EqualFold(cfg.SearchScope, "BASE"):
			searchScope = ldap.ScopeBaseObject
		case strings.EqualFold(cfg.SearchScope, "ONE"):
			searchScope = ldap.ScopeSingleLevel
		case strings.EqualFold(cfg.SearchScope, "SUB"):
			searchScope = ldap.ScopeWholeSubtree
		default:
			return nil, fmt.Errorf("Invalid value for searchScope: '%v'. Must be one of 'base', 'one' or 'sub'.", cfg.SearchScope)
		}
	}

	if cfg.Host == "" {
		if cfg.ServerHost == "" {
			return nil, errors.New("no host provided")
		}
		// For backward compatibility construct host form old fields.
		cfg.Host = fmt.Sprintf("%s:%d", cfg.ServerHost, cfg.ServerPort)
	}

	host, _, err := net.SplitHostPort(cfg.Host)
	if err != nil {
		return nil, fmt.Errorf("host is not of form 'host:port': %v", err)
	}

	tlsConfig := &tls.Config{ServerName: host}

	if (cfg.UseTLS || cfg.UseSSL) && len(cfg.CaFile) > 0 {
		buf, err := ioutil.ReadFile(cfg.CaFile)
		if err != nil {
			return nil, err
		}

		rootCertPool := x509.NewCertPool()
		ok := rootCertPool.AppendCertsFromPEM(buf)
		if ok {
			tlsConfig.RootCAs = rootCertPool
		} else {
			return nil, fmt.Errorf("%v: Unable to parse certificate data.", cfg.CaFile)
		}
	}

	if (cfg.UseTLS || cfg.UseSSL) && len(cfg.CertFile) > 0 && len(cfg.KeyFile) > 0 {
		cert, err := tls.LoadX509KeyPair(cfg.CertFile, cfg.KeyFile)
		if err != nil {
			return nil, err
		}
		tlsConfig.Certificates = []tls.Certificate{cert}
	}

	idpc := &LDAPConnector{
		id:               cfg.ID,
		namespace:        ns,
		loginFunc:        lf,
		loginTpl:         tpl,
		baseDN:           cfg.BaseDN,
		nameAttribute:    cfg.NameAttribute,
		emailAttribute:   cfg.EmailAttribute,
		searchBeforeAuth: cfg.SearchBeforeAuth,
		searchFilter:     cfg.SearchFilter,
		searchScope:      searchScope,
		searchBindDN:     cfg.SearchBindDN,
		searchBindPw:     cfg.SearchBindPw,
		bindTemplate:     cfg.BindTemplate,
		ldapPool: &LDAPPool{
			MaxIdleConn:    cfg.MaxIdleConn,
			PoolCheckTimer: defaultPoolCheckTimer,
			Host:           cfg.Host,
			UseTLS:         cfg.UseTLS,
			UseSSL:         cfg.UseSSL,
			TLSConfig:      tlsConfig,
		},
	}

	return idpc, nil
}
Beispiel #22
0
func (cfg *LDAPConnectorConfig) Connector(ns url.URL, lf oidc.LoginFunc, tpls *template.Template) (Connector, error) {
	ns.Path = path.Join(ns.Path, httpPathCallback)
	tpl := tpls.Lookup(LDAPLoginPageTemplateName)
	if tpl == nil {
		return nil, fmt.Errorf("unable to find necessary HTML template")
	}

	// defaults
	const defaultNameAttribute = "cn"
	const defaultEmailAttribute = "mail"
	const defaultBindTemplate = "uid=%u,%b"
	const defaultSearchScope = ldap.ScopeWholeSubtree

	if cfg.UseTLS && cfg.UseSSL {
		return nil, fmt.Errorf("Invalid configuration. useTLS and useSSL are mutual exclusive.")
	}

	if len(cfg.CertFile) > 0 && len(cfg.KeyFile) == 0 {
		return nil, fmt.Errorf("Invalid configuration. Both certFile and keyFile must be specified.")
	}

	nameAttribute := defaultNameAttribute
	if len(cfg.NameAttribute) > 0 {
		nameAttribute = cfg.NameAttribute
	}

	emailAttribute := defaultEmailAttribute
	if len(cfg.EmailAttribute) > 0 {
		emailAttribute = cfg.EmailAttribute
	}

	bindTemplate := defaultBindTemplate
	if len(cfg.BindTemplate) > 0 {
		if cfg.SearchBeforeAuth {
			log.Warningf("bindTemplate not used when searchBeforeAuth specified.")
		}
		bindTemplate = cfg.BindTemplate
	}

	searchScope := defaultSearchScope
	if len(cfg.SearchScope) > 0 {
		switch {
		case strings.EqualFold(cfg.SearchScope, "BASE"):
			searchScope = ldap.ScopeBaseObject
		case strings.EqualFold(cfg.SearchScope, "ONE"):
			searchScope = ldap.ScopeSingleLevel
		case strings.EqualFold(cfg.SearchScope, "SUB"):
			searchScope = ldap.ScopeWholeSubtree
		default:
			return nil, fmt.Errorf("Invalid value for searchScope: '%v'. Must be one of 'base', 'one' or 'sub'.", cfg.SearchScope)
		}
	}

	if cfg.Timeout != 0 {
		ldap.DefaultTimeout = cfg.Timeout * time.Millisecond
	}

	tlsConfig := &tls.Config{
		ServerName:         cfg.ServerHost,
		InsecureSkipVerify: cfg.SkipCertVerification,
	}

	if (cfg.UseTLS || cfg.UseSSL) && len(cfg.CaFile) > 0 {
		buf, err := ioutil.ReadFile(cfg.CaFile)
		if err != nil {
			return nil, err
		}

		rootCertPool := x509.NewCertPool()
		ok := rootCertPool.AppendCertsFromPEM(buf)
		if ok {
			tlsConfig.RootCAs = rootCertPool
		} else {
			return nil, fmt.Errorf("%v: Unable to parse certificate data.", cfg.CaFile)
		}
	}

	if (cfg.UseTLS || cfg.UseSSL) && len(cfg.CertFile) > 0 && len(cfg.KeyFile) > 0 {
		cert, err := tls.LoadX509KeyPair(cfg.CertFile, cfg.KeyFile)
		if err != nil {
			return nil, err
		}
		tlsConfig.Certificates = []tls.Certificate{cert}
	}

	idp := &LDAPIdentityProvider{
		serverHost:       cfg.ServerHost,
		serverPort:       cfg.ServerPort,
		useTLS:           cfg.UseTLS,
		useSSL:           cfg.UseSSL,
		baseDN:           cfg.BaseDN,
		nameAttribute:    nameAttribute,
		emailAttribute:   emailAttribute,
		searchBeforeAuth: cfg.SearchBeforeAuth,
		searchFilter:     cfg.SearchFilter,
		searchScope:      searchScope,
		searchBindDN:     cfg.SearchBindDN,
		searchBindPw:     cfg.SearchBindPw,
		bindTemplate:     bindTemplate,
		tlsConfig:        tlsConfig,
	}

	idpc := &LDAPConnector{
		id:                   cfg.ID,
		idp:                  idp,
		namespace:            ns,
		trustedEmailProvider: cfg.TrustedEmailProvider,
		loginFunc:            lf,
		loginTpl:             tpl,
	}

	return idpc, nil
}
Beispiel #23
0
func Register(templates *template.Template) {
	//	http.HandleFunc("/", Helloworld)
	//HOME
	hc := new(homeController)
	hc.template = templates.Lookup("home.html")
	http.HandleFunc("/", hc.get)

	//THREAD VIEW
	tc := new(threadController)
	tc.template = templates.Lookup("thread.html")
	http.HandleFunc("/view/", tc.get)

	//EDIT AND SAVE MAIN
	emc := new(editMainController)
	emc.template = templates.Lookup("editMain.html")
	http.HandleFunc("/edit/topic/", emc.handle)

	//EDIT AND SAVE REPLY
	erc := new(editReplyController)
	erc.template = templates.Lookup("editReply.html")
	http.HandleFunc("/edit/reply/", erc.handle)

	//Delete main, it's the same as to delete thread
	dt := new(deleteController)
	http.HandleFunc("/delete/", dt.delete)

	//Register user and edit profile info
	euc := new(editUserController)
	euc.template = templates.Lookup("register.html")
	http.HandleFunc("/edit/user/", euc.handle)

	//Login Controller
	lc := new(loginController)
	lc.template = templates.Lookup("login.html")
	http.HandleFunc("/login/", lc.handle)
	//Logout Controller
	loc := new(logoutController)
	http.HandleFunc("/logout/", loc.get)
}
func SetTemplateCache(tc *template.Template) {
	login.loginTemplate = tc.Lookup("login.html")

	parts.autoMakeTemplate = tc.Lookup("make.html")
	parts.autoModelTemplate = tc.Lookup("model.html")
	parts.autoYearTemplate = tc.Lookup("year.html")
	parts.autoEngineTemplate = tc.Lookup("engine.html")
	parts.searchResultTemplate = tc.Lookup("search_results.html")
	parts.partTemplate = tc.Lookup("part.html")
	parts.searchResultPartialTemplate = tc.Lookup("_result.html")

	checkout.template = tc.Lookup("checkout.html")

	admin.loginTemplate = tc.Lookup("admin_login.html")
	admin.menuTemplate = tc.Lookup("admin_menu.html")
	admin.createEmpTemplate = tc.Lookup("admin_create_emp.html")
	admin.viewEmpTemplate = tc.Lookup("admin_employee.html")
}
Beispiel #25
0
func Register(templates *template.Template) {

	router := mux.NewRouter()

	hc := new(homeController)
	hc.template = templates.Lookup("home.html")
	hc.loginTemplate = templates.Lookup("login.html")
	router.HandleFunc("/home", hc.get)
	router.HandleFunc("/login", hc.login)

	cc := new(categoriesController)
	cc.template = templates.Lookup("categories.html")
	router.HandleFunc("/categories", cc.get)

	categoryController := new(categoryController)
	categoryController.template = templates.Lookup("products.html")
	router.HandleFunc("/categories/{id}", categoryController.get)

	productController := new(productController)
	productController.template = templates.Lookup("product.html")
	router.HandleFunc("/product/{id}", productController.get)

	profileController := new(profileController)
	profileController.template = templates.Lookup("profile.html")
	router.HandleFunc("/profile", profileController.handle)

	standLocatorController := new(standLocatorController)
	standLocatorController.template = templates.Lookup("stand_locator.html")
	router.HandleFunc("/stand-locator", standLocatorController.get)
	router.HandleFunc("/api/stand-locator", standLocatorController.apiSearch)

	http.Handle("/", router)

	http.HandleFunc("/img/", serveResource)
	http.HandleFunc("/css/", serveResource)
}