本文整理汇总了Golang中github.com/justinas/nosurf.Token函数的典型用法代码示例。如果您正苦于以下问题:Golang Token函数的具体用法?Golang Token怎么用?Golang Token使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Token函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: indexPage
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)
}
示例2: indexPage
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)
}
示例3: Login
// 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,
})
}
示例4: WebSignIn
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",
})
}
示例5: Edit
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)
}
示例6: Login
// 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)
}
}
}
示例7: LoginHandler
// 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)))
}
示例8: Register
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,
})
}
示例9: Settings
// 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)
}
}
示例10: RenderTemplate
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())
}
}
示例11: setupAuthboss
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())
}
示例12: myFunc
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)
}
示例13: Base
// 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)
}
示例14: New
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)
}
示例15: LandingPages
// 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)
}