Files
spyda/internal/context.go

123 lines
2.1 KiB
Go

package internal
import (
"html/template"
"net/http"
log "github.com/sirupsen/logrus"
"github.com/vcraescu/go-paginator"
"github.com/justinas/nosurf"
"git.mills.io/prologic/spyda"
"git.mills.io/prologic/spyda/internal/session"
)
type Meta struct {
Title string
Description string
UpdatedAt string
Image string
Author string
URL string
Keywords string
}
type Context struct {
Config string
Debug bool
BaseURL string
InstanceName string
SoftwareVersion string
SearchQuery string
SearchPrompt string
Username string
User *User
Tokens []*Token
Authenticated bool
IsAdmin bool
Error bool
Message string
Theme string
Commit string
Page string
Content template.HTML
Title string
Meta Meta
Results Results
Pager *paginator.Paginator
// Report abuse
ReportURL string
// Reset Password Token
PasswordResetToken string
// CSRF Token
CSRFToken string
}
func NewContext(conf *Config, db Store, req *http.Request) *Context {
ctx := &Context{
Debug: conf.Debug,
BaseURL: conf.BaseURL,
InstanceName: conf.Name,
SoftwareVersion: spyda.FullVersion(),
SearchPrompt: conf.RandomSearchPrompt(),
Commit: spyda.Commit,
Theme: conf.Theme,
Title: "",
Meta: Meta{
Title: DefaultMetaTitle,
Author: DefaultMetaAuthor,
Keywords: DefaultMetaKeywords,
Description: conf.Description,
},
}
ctx.CSRFToken = nosurf.Token(req)
if sess := req.Context().Value(session.SessionKey); sess != nil {
if username, ok := sess.(*session.Session).Get("username"); ok {
ctx.Authenticated = true
ctx.Username = username
}
}
if ctx.Authenticated && ctx.Username != "" {
user, err := db.GetUser(ctx.Username)
if err != nil {
log.WithError(err).Warnf("error loading user object for %s", ctx.Username)
}
ctx.User = user
tokens, err := db.GetUserTokens(user)
if err != nil {
log.WithError(err).Warnf("error loading tokens for %s", ctx.Username)
}
ctx.Tokens = tokens
} else {
ctx.User = &User{}
}
if ctx.Username == conf.AdminUser {
ctx.IsAdmin = true
}
return ctx
}