本文整理汇总了Golang中github.com/justinas/nosurf.Token函数的典型用法代码示例。如果您正苦于以下问题:Golang Token函数的具体用法?Golang Token怎么用?Golang Token使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Token函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)
}
开发者ID:thesoftwarefactoryuk,项目名称:podbaby,代码行数:31,代码来源:pages.go
示例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)
}
开发者ID:szwork2013,项目名称:podbaby,代码行数:33,代码来源:pages.go
示例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,
})
}
开发者ID:robvdl,项目名称:gcms,代码行数:32,代码来源:routes.go
示例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",
})
}
开发者ID:natmeox,项目名称:mess,代码行数:29,代码来源:web.go
示例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)
}
开发者ID:anukat2015,项目名称:pythia,代码行数:34,代码来源:answers_handler.go
示例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)
}
}
}
开发者ID:666jfox777,项目名称:gophish,代码行数:36,代码来源:route.go
示例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)))
}
开发者ID:NovemberFoxtrot,项目名称:magnet,代码行数:8,代码来源:handler.go
示例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,
})
}
开发者ID:Leko,项目名称:godemo,代码行数:7,代码来源:users.go
示例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)
}
}
开发者ID:666jfox777,项目名称:gophish,代码行数:28,代码来源:route.go
示例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())
}
}
开发者ID:natmeox,项目名称:mess,代码行数:30,代码来源:web.go
示例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())
}
开发者ID:Genffy,项目名称:api.genffy.com,代码行数:58,代码来源:auth.go
示例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)
}
开发者ID:isikfsc,项目名称:otp,代码行数:9,代码来源:csrf.go
示例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)
}
开发者ID:666jfox777,项目名称:gophish,代码行数:10,代码来源:route.go
示例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)
}
开发者ID:anukat2015,项目名称:pythia,代码行数:10,代码来源:answers_handler.go
示例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)
}
开发者ID:666jfox777,项目名称:gophish,代码行数:11,代码来源:route.go
示例16: Index
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)
}
开发者ID:marswang,项目名称:nosurf,代码行数:10,代码来源:advanced.go
示例17: myHandler
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)
}
开发者ID:marswang,项目名称:nosurf,代码行数:10,代码来源:web.go
示例18: CampaignID
// 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)
}
开发者ID:StrangeUSB,项目名称:gophish,代码行数:11,代码来源:route.go
示例19: mustRender
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)
}
开发者ID:wangyu0305,项目名称:authboss-sample,代码行数:11,代码来源:blog.go
示例20: Register
// 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)
}
}
}
开发者ID:tohitsugu,项目名称:gophish,代码行数:52,代码来源:route.go
注:本文中的github.com/justinas/nosurf.Token函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论