Esempio n. 1
0
func (s *Server) indexPage(w http.ResponseWriter, r *http.Request) {

	var dynamicContentURL string
	if s.Config.IsDev() {
		dynamicContentURL = s.Config.DynamicContentURL
	} else {
		dynamicContentURL = s.Config.StaticURL
	}
	user, err := s.getUserFromCookie(r)
	if err == nil {
		if user.Bookmarks, err = s.DB.Bookmarks.SelectByUserID(user.ID); err != nil {
			s.abort(w, r, err)
			return
		}
		if user.Subscriptions, err = s.DB.Subscriptions.SelectByUserID(user.ID); err != nil {
			s.abort(w, r, err)
			return
		}
	}
	csrfToken := nosurf.Token(r)
	ctx := map[string]interface{}{
		"env":               s.Config.Env,
		"dynamicContentURL": dynamicContentURL,
		"staticURL":         s.Config.StaticURL,
		"googleAnalyticsID": s.Config.GoogleAnalyticsID,
		"csrfToken":         csrfToken,
		"user":              user,
		"timestamp":         time.Now().Unix(),
	}
	s.Render.HTML(w, http.StatusOK, "index", ctx)
}
Esempio n. 2
0
func indexPage(s *Server, w http.ResponseWriter, r *http.Request) error {

	var (
		dynamicContentURL string
		err               error
	)

	if s.Config.IsDev() {
		dynamicContentURL = s.Config.DynamicContentURL
	} else {
		dynamicContentURL = s.Config.StaticURL
	}
	user, ok := getUser(r)
	if ok {
		if user.Bookmarks, err = s.DB.Bookmarks.SelectByUserID(user.ID); err != nil {
			return err
		}
		if user.Subscriptions, err = s.DB.Subscriptions.SelectByUserID(user.ID); err != nil {
			return err
		}
	}
	csrfToken := nosurf.Token(r)
	ctx := map[string]interface{}{
		"env":               s.Config.Env,
		"dynamicContentURL": dynamicContentURL,
		"staticURL":         s.Config.StaticURL,
		"googleAnalyticsID": s.Config.GoogleAnalyticsID,
		"csrfToken":         csrfToken,
		"user":              user,
		"timestamp":         time.Now().Unix(),
	}
	return s.Render.HTML(w, http.StatusOK, "index", ctx)
}
Esempio n. 3
0
// Login is a page with a login form and an alternative to the login API,
// this route handles both GET and POST requests.
func Login(c *gin.Context) {
	session := sessions.Default(c)
	defer session.Save()

	// returnURL can come from GET or POST or use default.
	returnURL := c.DefaultQuery("return_url", c.DefaultPostForm("return_url", "/"))

	if c.Request.Method == "POST" {
		var schema LoginSchema
		if c.Bind(&schema) == nil {
			// Fetch the user matching this username.
			user := GetUserByUsername(schema.Username)

			// If the user exists, the ID is > 0, check the password.
			if user.ID > 0 && user.CheckPassword(schema.Password) {
				session.Set("userID", user.ID)
				c.Redirect(http.StatusFound, returnURL)
				return
			}
			session.AddFlash("Invalid username or password")
		}
	}

	c.HTML(200, "login.html", pongo2.Context{
		"title":      "Login",
		"messages":   session.Flashes(),
		"csrf_token": nosurf.Token(c.Request),
		"return_url": returnURL,
	})
}
Esempio n. 4
0
File: web.go Progetto: natmeox/mess
func WebSignIn(w http.ResponseWriter, r *http.Request) {
	acc := AccountForRequest(w, r)
	if acc != nil {
		http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
		return
	}

	if r.Method == "POST" {
		loginname := r.PostFormValue("name")
		password := r.PostFormValue("password")

		acc = Accounts.AccountForLogin(loginname, password)
		if acc != nil {
			SetAccountForRequest(w, r, acc)

			nextUrl := r.FormValue("next")
			if nextUrl == "" {
				nextUrl = "/"
			}
			http.Redirect(w, r, nextUrl, http.StatusTemporaryRedirect)
			return
		}
	}

	RenderTemplate(w, r, "signin.html", map[string]interface{}{
		"CsrfToken": nosurf.Token(r),
		"Title":     "Sign in",
	})
}
Esempio n. 5
0
func Edit(w http.ResponseWriter, r *http.Request, fileId string, gv *global_vars.GlobalVars, currentUser *models.User) {
	if currentUser == nil {
		http.Redirect(w, r, "/answers", http.StatusFound)
		return
	}

	var rec models.Answer

	funcMap := template.FuncMap{
		"tagsString": func(tags []string) string {
			return strings.Join(tags, " ")
		}}

	err := gv.MyDB.Find("answers", &rec, fileId)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	templateData := TemplateData{CurrentUser: currentUser, Rec: &rec, CsrfToken: nosurf.Token(r)}

	lp := path.Join("templates", "layouts", "layout.html")
	fp := path.Join("templates", "answers", "edit.html")

	tmpl := template.New("edt").Funcs(funcMap)

	tmpl, err = tmpl.ParseFiles(lp, fp)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	err = tmpl.ExecuteTemplate(w, "layout", templateData)
}
Esempio n. 6
0
// 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: nosurf.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, 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.Save(r, w)
			http.Redirect(w, r, "/", 302)
		} else {
			Flash(w, r, "danger", "Invalid Username/Password")
			http.Redirect(w, r, "/login", 302)
		}
	}
}
Esempio n. 7
0
// LoginHandler writes out login template
func LoginHandler(r *http.Request, w http.ResponseWriter) {
	context := map[string]interface{}{
		"title":      "Access magnet",
		"csrf_token": nosurf.Token(r),
	}
	w.Write([]byte(mustache.RenderFileInLayout("templates/login.mustache", "templates/base.mustache", context)))
}
Esempio n. 8
0
File: users.go Progetto: Leko/godemo
func (u *users) Register(c *gin.Context) {
	csrfToken := nosurf.Token(c.Request)
	c.HTML(http.StatusOK, "user_form.tpl", gin.H{
		"new":       true,
		"csrfToken": csrfToken,
	})
}
Esempio n. 9
0
// 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
		}{Title: "Dashboard", User: ctx.Get(r, "user").(models.User), Token: nosurf.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
		} else if err != nil {
			msg.Message = "Unknown Error Occured"
			msg.Success = false
			JSONResponse(w, msg, http.StatusBadRequest)
			return
		}
		JSONResponse(w, msg, http.StatusOK)
	}
}
Esempio n. 10
0
File: web.go Progetto: natmeox/mess
func RenderTemplate(w http.ResponseWriter, r *http.Request, templateName string, templateContext map[string]interface{}) {
	var paletteItems []*Thing
	for i := 0; i < 10; i++ {
		thing := World.ThingForId(ThingId(i))
		if thing != nil {
			paletteItems = append(paletteItems, thing)
		}
	}

	context := map[string]interface{}{
		"CsrfToken": nosurf.Token(r),
		"Config": map[string]interface{}{
			"Debug":       Config.Debug,
			"ServiceName": Config.ServiceName,
			"HostName":    Config.HostName,
		},
		"Account":      context.Get(r, ContextKeyAccount), // could be nil
		"PaletteItems": paletteItems,
	}
	// If e.g. Account was provided by the caller, it overrides our default one.
	for k, v := range templateContext {
		context[k] = v
	}

	template := getTemplate(templateName)
	err := template.Execute(w, context)
	if err != nil {
		log.Println("Error executing index.html template:", err.Error())
	}
}
Esempio n. 11
0
func setupAuthboss() {
	ab.Storer = database
	ab.OAuth2Storer = database
	ab.MountPath = "/v1/auth"
	// ab.ViewsPath = "views"
	// ab.RootURL = `http://localhost:3000`

	// ab.LayoutDataMaker = layoutData

	ab.OAuth2Providers = map[string]authboss.OAuth2Provider{
		"google": authboss.OAuth2Provider{
			OAuth2Config: &oauth2.Config{
				ClientID:     ``,
				ClientSecret: ``,
				Scopes:       []string{`profile`, `email`},
				Endpoint:     google.Endpoint,
			},
			Callback: aboauth.Google,
		},
	}

	// b, err := ioutil.ReadFile(filepath.Join("views", "layout.html.tpl"))
	// if err != nil {
	// 	panic(err)
	// }
	// ab.Layout = template.Must(template.New("layout").Funcs(funcs).Parse(string(b)))

	ab.XSRFName = "csrf_token"
	ab.XSRFMaker = func(_ http.ResponseWriter, r *http.Request) string {
		return nosurf.Token(r)
	}

	ab.CookieStoreMaker = NewCookieStorer
	ab.SessionStoreMaker = NewSessionStorer

	ab.Mailer = authboss.LogMailer(os.Stdout)

	ab.Policies = []authboss.Validator{
		authboss.Rules{
			FieldName:       "email",
			Required:        true,
			AllowWhitespace: false,
		},
		authboss.Rules{
			FieldName:       "password",
			Required:        true,
			MinLength:       4,
			MaxLength:       8,
			AllowWhitespace: false,
		},
	}

	if err := ab.Init(); err != nil {
		log.Fatal(err)
	}

	beego.Handler("/auth", ab.NewRouter())
}
Esempio n. 12
0
File: csrf.go Progetto: isikfsc/otp
func myFunc(w http.ResponseWriter, r *http.Request) {
	context := make(map[string]string)
	context["token"] = nosurf.Token(r)
	if r.Method == "POST" {
		context["name"] = r.FormValue("name")
	}

	templ.Execute(w, context)
}
Esempio n. 13
0
// 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: nosurf.Token(r)}
	getTemplate(w, "dashboard").ExecuteTemplate(w, "base", params)
}
Esempio n. 14
0
func New(w http.ResponseWriter, r *http.Request, throwaway string, gv *global_vars.GlobalVars, currentUser *models.User) {
	if currentUser == nil {
		http.Redirect(w, r, "/answers", http.StatusFound)
		return
	}

	templateData := TemplateData{CurrentUser: currentUser, CsrfToken: nosurf.Token(r)}

	renderTemplate(w, "new", &templateData)
}
Esempio n. 15
0
// LandingPages handles the default path and template execution
func LandingPages(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: "Dashboard", User: ctx.Get(r, "user").(models.User), Token: nosurf.Token(r)}
	getTemplate(w, "landing_pages").ExecuteTemplate(w, "base", params)
}
Esempio n. 16
0
func Index(w http.ResponseWriter, r *http.Request) {
	context := map[string]string{
		"token": nosurf.Token(r),
	}
	if r.Method == "POST" {
		context["name"] = r.FormValue("name")
	}

	templ.Execute(w, context)
}
Esempio n. 17
0
func myHandler(ctx *web.Context) {
	templateCtx := make(map[string]string)
	templateCtx["token"] = nosurf.Token(ctx.Request)

	if ctx.Request.Method == "POST" {
		templateCtx["name"] = ctx.Params["name"]
	}

	templ.Execute(ctx, templateCtx)
}
Esempio n. 18
0
// CampaignID handles the default path and template execution
func CampaignID(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: "Campaign Results", User: ctx.Get(r, "user").(models.User), Token: nosurf.Token(r)}
	getTemplate(w, "campaign_results").ExecuteTemplate(w, "base", params)
}
Esempio n. 19
0
func mustRender(w http.ResponseWriter, r *http.Request, name string, data authboss.HTMLData) {
	data.MergeKV("csrf_token", nosurf.Token(r))
	err := templates.Render(w, name, data)
	if err == nil {
		return
	}

	w.Header().Set("Content-Type", "text/plain")
	w.WriteHeader(http.StatusInternalServerError)
	fmt.Fprintln(w, "Error occurred rendering template:", err)
}
Esempio n. 20
0
// 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: nosurf.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")
		templates.Delims(templateDelims[0], templateDelims[1])
		_, 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)
		} else {
			// Check the error
			m := ""
			if err == models.ErrUsernameTaken {
				m = "Username already taken"
			} else {
				m = "Unknown error - please try again"
				Logger.Println(err)
			}
			session.AddFlash(models.Flash{
				Type:    "danger",
				Message: m,
			})
			session.Save(r, w)
			http.Redirect(w, r, "/register", 302)
		}

	}
}
Esempio n. 21
0
// IndexHandler writes out templates
func IndexHandler(req *http.Request, w http.ResponseWriter, cs *sessions.CookieStore, connection *Connection) {
	username, userID := GetUserData(cs, req)
	context := map[string]interface{}{
		"title":      "Magnet",
		"csrf_token": nosurf.Token(req),
		"bookmarks":  GetBookmarks(0, connection, userID),
		"tags":       GetTags(connection, userID),
		"username":   username,
	}

	context["load_more"] = len(context["bookmarks"].([]Bookmark)) == 50

	w.Write([]byte(mustache.RenderFileInLayout("templates/home.mustache", "templates/base.mustache", context)))
}
Esempio n. 22
0
func (b *bbs) show(w http.ResponseWriter, r *http.Request) {
	db, err := sql.Open("mysql", b.Dsn)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	defer db.Close()

	sql := `SELECT m.message message, m.created_at created_at, u.name name
	FROM messages m INNER JOIN users u
	ON m.user_id = u.id ORDER BY m.created_at`
	rows, err := db.Query(sql)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	messages := []*model.Messages{}
	for rows.Next() {
		m := &model.Messages{}
		if err := rows.Scan(&m.Message, &m.CreatedAt, &m.UserName); err != nil {
			break
		}
		messages = append(messages, m)
	}
	if err := rows.Err(); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	t, err := template.ParseFiles("views/bbs.html")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	sess, _ := b.CookieStore.Get(r, "user")
	name := sess.Values["name"].(string)
	e := embed{
		Name:      name,
		Messages:  messages,
		CsrfToken: nosurf.Token(r),
	}

	if err := t.Execute(w, e); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
}
Esempio n. 23
0
func Delete(w http.ResponseWriter, r *http.Request, fileId string, gv *global_vars.GlobalVars, currentUser *models.User) {
	if currentUser == nil {
		http.Redirect(w, r, "/answers", http.StatusFound)
		return
	}

	var rec models.Answer

	err := gv.MyDB.Find("answers", &rec, fileId)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	templateData := TemplateData{CurrentUser: currentUser, Rec: &rec, CsrfToken: nosurf.Token(r)}
	renderTemplate(w, "delete", &templateData)
}
Esempio n. 24
0
func Edit(w http.ResponseWriter, r *http.Request, fileId string, gv *global_vars.GlobalVars, currentUser *models.User) {
	var rec models.User

	if (currentUser == nil) || (currentUser.Level != "admin") {
		http.Redirect(w, r, "/", http.StatusFound)
		return
	}

	err := gv.MyDB.Find("users", &rec, fileId)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	templateData := TemplateData{CurrentUser: currentUser, Rec: &rec, CsrfToken: nosurf.Token(r)}

	renderTemplate(w, "edit", &templateData)
}
Esempio n. 25
0
func ChangePasswordHandler(app *Application) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		user := context.Get(r, "user").(*ipa.UserRecord)
		if user == nil {
			logrus.Error("changepw handler: user not found in request context")
			errorHandler(app, w, http.StatusInternalServerError)
			return
		}

		message := ""
		completed := false

		if r.Method == "POST" {
			err := changePassword(app, user, r)
			if err != nil {
				message = err.Error()
				completed = false
			} else {
				completed = true
				if len(user.Email) > 0 {
					err = app.SendEmail(string(user.Email), fmt.Sprintf("[%s] Your password change confirmation", viper.GetString("email_prefix")), "reset-password-confirm.txt", nil)
					if err != nil {
						logrus.WithFields(logrus.Fields{
							"uid":   user.Uid,
							"error": err,
						}).Error("failed to send reset confirmation email to user")
					}
				} else {
					logrus.WithFields(logrus.Fields{
						"uid": user.Uid,
					}).Error("changepw: user missing email address")
				}
			}
		}

		vars := map[string]interface{}{
			"token":     nosurf.Token(r),
			"completed": completed,
			"user":      user,
			"message":   message}

		renderTemplate(w, app.templates["change-password.html"], vars)
	})
}
Esempio n. 26
0
// CsrfMiddleware adds CSRF support via nosurf.
func CsrfMiddleware(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
	var token string
	var passed bool

	// nosurf disposes of the token as soon as it calls the http.Handler you provide...
	// in order to use it as negroni middleware, pull out token and dispose of it ourselves
	csrfHandler := nosurf.NewPure(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
		token = nosurf.Token(r)
		passed = true
	}))
	csrfHandler.ServeHTTP(w, r)

	// csrf passed
	if passed {
		context.Set(r, "csrf_token", token)
		next(w, r)
		context.Delete(r, "csrf_token")
	}
}
Esempio n. 27
0
func indexPage(c *gin.Context) {

	cfg := getConfig(c)

	var staticHost string

	if cfg.Options.Env == "dev" {
		staticHost = cfg.Options.DevServerURL
	}

	csrfToken := nosurf.Token(c.Request)

	data := gin.H{
		"staticHost": staticHost,
		"env":        cfg.Options.Env,
		"csrfToken":  csrfToken,
	}
	c.HTML(http.StatusOK, "index.tmpl", data)
}
Esempio n. 28
0
func UpdateSecurityQuestionHandler(app *Application) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		user := context.Get(r, "user").(*ipa.UserRecord)
		if user == nil {
			logrus.Error("securityquestion handler: user not found in request context")
			errorHandler(app, w, http.StatusInternalServerError)
			return
		}

		questions, err := model.FetchQuestions(app.db)
		if err != nil {
			logrus.WithFields(logrus.Fields{
				"error": err.Error(),
			}).Error("Failed to fetch questions from database")
			errorHandler(app, w, http.StatusInternalServerError)
			return
		}

		message := ""
		completed := false

		if r.Method == "POST" {
			err := updateSecurityQuestion(app, questions, user, r)
			if err != nil {
				message = err.Error()
				completed = false
			} else {
				completed = true
			}
		}

		vars := map[string]interface{}{
			"token":     nosurf.Token(r),
			"completed": completed,
			"user":      user,
			"questions": questions,
			"message":   message}

		renderTemplate(w, app.templates["update-security-question.html"], vars)
	})
}
Esempio n. 29
0
func ForgotPasswordHandler(app *Application) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		message := ""
		completed := false

		if r.Method == "POST" {
			err := forgotPassword(app, r)
			if err != nil {
				message = err.Error()
				completed = false
			} else {
				completed = true
			}
		}

		vars := map[string]interface{}{
			"token":     nosurf.Token(r),
			"completed": completed,
			"message":   message}

		renderTemplate(w, app.templates["forgot-password.html"], vars)
	})
}
Esempio n. 30
0
func startHandler(w http.ResponseWriter, r *http.Request) {

	setSecurityHeaders(w, r)
	dontCache(w, r)

	//WuSign verification, worked perfectly
	//if r.URL.Path == "/devhub.club.html" {
	//w.Header().Set("Content-Type", "text/html")
	//w.WriteHeader(200)
	//fmt.Fprintf(w, "%s\n", "prorvAbpuYvE33xSQKcsHOziQLWadN2XXol8kL6wjtU=")
	//return
	//}

	data := struct {
		Token string
	}{
		nosurf.Token(r),
	}

	if err := templateStart.Execute(w, data); err != nil {
		log.Println(err)
	}
}