// Login handles the authentication flow for a user. If credentials are valid, // a session is created func Login(w http.ResponseWriter, r *http.Request) { params := struct { User models.User Title string Flashes []interface{} Token string }{Title: "Login", Token: csrf.Token(r)} session := ctx.Get(r, "session").(*sessions.Session) switch { case r.Method == "GET": params.Flashes = session.Flashes() session.Save(r, w) templates := template.New("template") _, err := templates.ParseFiles("templates/login.html", "templates/flashes.html") if err != nil { Logger.Println(err) } template.Must(templates, err).ExecuteTemplate(w, "base", params) case r.Method == "POST": //Attempt to login succ, u, err := auth.Login(r) if err != nil { Logger.Println(err) } //If we've logged in, save the session and redirect to the dashboard if succ { session.Values["id"] = u.Id session.Save(r, w) http.Redirect(w, r, "/", 302) } else { Flash(w, r, "danger", "Invalid Username/Password") http.Redirect(w, r, "/login", 302) } } }
// ---Show Movies and ajax operation func getMovies(w http.ResponseWriter, req *http.Request) { w.Header().Add("Content Type", "text/html") t, _ := template.New("html").Parse(htmlTemplate) params := map[string]interface{}{"CsrfToken": csrf.Token(req)} t.Execute(w, params) }
// Base handles the default path and template execution func Base(w http.ResponseWriter, r *http.Request) { params := struct { User models.User Title string Flashes []interface{} Token string }{Title: "Dashboard", User: ctx.Get(r, "user").(models.User), Token: csrf.Token(r)} getTemplate(w, "dashboard").ExecuteTemplate(w, "base", params) }
// SendingProfiles handles the default path and template execution func SendingProfiles(w http.ResponseWriter, r *http.Request) { // Example of using session - will be removed. params := struct { User models.User Title string Flashes []interface{} Token string }{Title: "Sending Profiles", User: ctx.Get(r, "user").(models.User), Token: csrf.Token(r)} getTemplate(w, "sending_profiles").ExecuteTemplate(w, "base", params) }
func indexHandler(w http.ResponseWriter, r *http.Request) { data := map[string]interface{}{ "token": csrf.Token(r), } w.Header().Set("X-Frame-Options", "SAMEORIGIN") w.Header().Set("X-Xss-Protection", "1; mode=block") w.Header().Set("X-Content-Type-Options", "nosniff") // Temp disable until serving site over https // w.Header().Set("Content-Security-Policy", "script-src 'self' cdnjs.cloudflare.com") temps.ExecuteTemplate(w, "index.html", data) }
func (s *Server) render(w http.ResponseWriter, r *http.Request, name string) { ctx := NewContext(r, w) tmpl := s.tmpl if tmpl == nil { t, err := s.loadTemplates() if err != nil { panic(err) } tmpl = t } data := renderData{ Title: ctx.Title(), ActiveTab: ctx.ActiveTab(), Breadcrumb: ctx.Breadcrumb(), User: ctx.User(), CSRFToken: csrf.Token(r), CSRFField: csrf.TemplateField(r), MapboxAccessToken: s.config.Server.MapboxAccessToken, Version: tracklog.Version, Data: ctx.Data(), } if s.config.Server.Development { data.Runtime = fmt.Sprintf("%.0fms", time.Now().Sub(ctx.Start()).Seconds()*1000) } if ctx.NoLayout() { if err := tmpl.ExecuteTemplate(w, name+".html", data); err != nil { panic(err) } return } buf := new(bytes.Buffer) if err := tmpl.ExecuteTemplate(buf, name+".html", data); err != nil { panic(err) } data.Content = template.HTML(buf.String()) w.Header().Set("Content-Type", "text/html; charset=utf-8") if err := tmpl.ExecuteTemplate(w, "layout.html", data); err != nil { panic(err) } }
// Register creates a new user func Register(w http.ResponseWriter, r *http.Request) { // If it is a post request, attempt to register the account // Now that we are all registered, we can log the user in params := struct { Title string Flashes []interface{} User models.User Token string }{Title: "Register", Token: csrf.Token(r)} session := ctx.Get(r, "session").(*sessions.Session) switch { case r.Method == "GET": params.Flashes = session.Flashes() session.Save(r, w) templates := template.New("template") _, err := templates.ParseFiles("templates/register.html", "templates/flashes.html") if err != nil { Logger.Println(err) } template.Must(templates, err).ExecuteTemplate(w, "base", params) case r.Method == "POST": //Attempt to register succ, err := auth.Register(r) //If we've registered, redirect to the login page if succ { session.AddFlash(models.Flash{ Type: "success", Message: "Registration successful!.", }) session.Save(r, w) http.Redirect(w, r, "/login", 302) return } // Check the error m := err.Error() Logger.Println(err) session.AddFlash(models.Flash{ Type: "danger", Message: m, }) session.Save(r, w) http.Redirect(w, r, "/register", 302) return } }
func (self httpModUI) ServeModPage(wr http.ResponseWriter, r *http.Request) { if self.checkSession(r) { wr.Header().Set("X-CSRF-Token", csrf.Token(r)) // we are logged in url := r.URL.String() if strings.HasSuffix(url, "/mod/feeds") { // serve feeds page self.writeTemplate(wr, r, "modfeed.mustache") } else { // serve mod page self.writeTemplate(wr, r, "modpage.mustache") } } else { // we are not logged in // serve login page self.writeTemplate(wr, r, "modlogin.mustache") } if r.Body != nil { r.Body.Close() } }
func init() { Auth.MountPath = "/auth" Auth.XSRFName = "gorilla.csrf.Token" Auth.XSRFMaker = func(_ http.ResponseWriter, r *http.Request) string { return csrf.Token(r) } Auth.CookieStoreMaker = NewCookieStorer Auth.SessionStoreMaker = NewSessionStorer Auth.BCryptCost = bcrypt.DefaultCost Auth.LogWriter = os.Stdout Auth.Storer = &AuthStorer{} Auth.ViewsPath = "app/views/auth" Auth.LayoutPath = config.Root + "/app/views/layouts/application.tmpl" Auth.LayoutFuncMaker = layoutFunc Auth.LayoutDataMaker = layoutData Auth.Mailer = authboss.SMTPMailer(config.Config.SMTP.HostWithPort(), smtp.PlainAuth("", config.Config.SMTP.User, config.Config.SMTP.Password, config.Config.SMTP.Host)) Auth.EmailFrom = "Qor Example" Auth.RootURL = config.Config.SMTP.Site Auth.Policies = []authboss.Validator{ authboss.Rules{ FieldName: "email", Required: true, AllowWhitespace: false, MustMatch: regexp.MustCompile(`^[a-z0-9._%+\-]+@[a-z0-9.\-]+\.[a-z]{2,4}$`), MatchError: "Please input a valid email address", }, authboss.Rules{ FieldName: "password", Required: true, MinLength: 4, MaxLength: 8, AllowWhitespace: false, }, } if err := Auth.Init(); err != nil { panic(err) } }
func csrfWrapper(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("X-CSRF-Token", csrf.Token(r)) h.ServeHTTP(w, r) }) }
func getCsrfToken(w http.ResponseWriter, req *http.Request) { w.Header().Set("X-CSRF-Token", csrf.Token(req)) }
// Settings handles the changing of settings func Settings(w http.ResponseWriter, r *http.Request) { switch { case r.Method == "GET": params := struct { User models.User Title string Flashes []interface{} Token string Version string }{Title: "Settings", Version: config.Version, User: ctx.Get(r, "user").(models.User), Token: csrf.Token(r)} getTemplate(w, "settings").ExecuteTemplate(w, "base", params) case r.Method == "POST": err := auth.ChangePassword(r) msg := models.Response{Success: true, Message: "Settings Updated Successfully"} if err == auth.ErrInvalidPassword { msg.Message = "Invalid Password" msg.Success = false JSONResponse(w, msg, http.StatusBadRequest) return } if err != nil { msg.Message = err.Error() msg.Success = false JSONResponse(w, msg, http.StatusBadRequest) return } JSONResponse(w, msg, http.StatusOK) } }
func headReview(w http.ResponseWriter, req *http.Request) { w.Header().Set("X-CSRF-Token", csrf.Token(req)) }
// Index serves index.html func (c *Context) Index(w web.ResponseWriter, r *web.Request) { c.templates.ExecuteTemplate(w, "index.html", map[string]interface{}{ "csrfToken": csrf.Token(r.Request), }) }