Browse Source

Backport GoPX migration to GORM

master
Dashie der otter 1 year ago
parent
commit
18a3627913
Signed by: Dashie <dashie@sigpipe.me> GPG Key ID: C2D57B325840B755
14 changed files with 196 additions and 235 deletions
  1. 20
    19
      Gopkg.lock
  2. 0
    24
      Gopkg.toml
  3. 1
    1
      cmd/web.go
  4. 1
    2
      conf/app.ini
  5. 4
    2
      context/context.go
  6. 1
    1
      models/errors/user.go
  7. 40
    66
      models/models.go
  8. 1
    5
      models/models_sqlite.go
  9. 111
    102
      models/user.go
  10. 4
    4
      routers/user/auth.go
  11. 1
    1
      routers/user/setting.go
  12. 6
    6
      stuff/auth/auth.go
  13. 1
    1
      stuff/mailer/mail.go
  14. 5
    1
      stuff/template/template.go

+ 20
- 19
Gopkg.lock View File

@@ -88,24 +88,6 @@
revision = "a0583e0143b1624142adab07e0e97fe106d99561"
version = "v1.3"

[[projects]]
name = "github.com/go-xorm/builder"
packages = ["."]
revision = "a9b7ffcca3f0c6445c4e3b1bf72c01578817a6c3"
version = "v0.1.0"

[[projects]]
name = "github.com/go-xorm/core"
packages = ["."]
revision = "f43c33d9a48db006417a7ac4c16b08897e3e1458"
version = "v0.5.8"

[[projects]]
name = "github.com/go-xorm/xorm"
packages = ["."]
revision = "fc1b13e0d8e240788213230aa5747eb557f80f41"
version = "v0.6.6"

[[projects]]
name = "github.com/gogits/cron"
packages = ["."]
@@ -124,6 +106,24 @@
packages = ["."]
revision = "64a82a6d140778896f13303121a49d8cb8007034"

[[projects]]
name = "github.com/jinzhu/gorm"
packages = [
".",
"dialects/mssql",
"dialects/mysql",
"dialects/postgres",
"dialects/sqlite"
]
revision = "6ed508ec6a4ecb3531899a69cbc746ccf65a4166"
version = "v1.9.1"

[[projects]]
branch = "master"
name = "github.com/jinzhu/inflection"
packages = ["."]
revision = "04140366298a54a039076d798123ffa108fff46c"

[[projects]]
name = "github.com/jtolds/gls"
packages = ["."]
@@ -135,6 +135,7 @@
name = "github.com/lib/pq"
packages = [
".",
"hstore",
"oid"
]
revision = "d34b9ff171c21ad295489235aec8b6626023cd04"
@@ -287,6 +288,6 @@
[solve-meta]
analyzer-name = "dep"
analyzer-version = 1
inputs-digest = "99819157a3b8f3a5cd71cf759d8b24cc4d89703c9cb72b4afac3b5db41f71b12"
inputs-digest = "fe7d05c1bc31d42dbef4597c69e4bd8f54c6aa81548cc15292a0f2696ae94cc8"
solver-name = "gps-cdcl"
solver-version = 1

+ 0
- 24
Gopkg.toml View File

@@ -29,10 +29,6 @@
name = "github.com/Unknwon/com"
branch = "master"

[[constraint]]
branch = "master"
name = "github.com/denisenkom/go-mssqldb"

[[constraint]]
branch = "master"
name = "github.com/getsentry/raven-go"
@@ -61,18 +57,6 @@
branch = "master"
name = "github.com/go-macaron/toolbox"

[[constraint]]
name = "github.com/go-sql-driver/mysql"
version = "1.3.0"

[[constraint]]
name = "github.com/go-xorm/core"
version = "0.5.8"

[[constraint]]
name = "github.com/go-xorm/xorm"
version = "0.6.6"

[[constraint]]
name = "github.com/gogits/cron"
version = "1.0.0"
@@ -81,14 +65,6 @@
branch = "master"
name = "github.com/jaytaylor/html2text"

[[constraint]]
branch = "master"
name = "github.com/lib/pq"

[[constraint]]
name = "github.com/mattn/go-sqlite3"
version = "1.6.0"

[[constraint]]
branch = "master"
name = "github.com/microcosm-cc/bluemonday"

+ 1
- 1
cmd/web.go View File

@@ -60,7 +60,7 @@ func newMacaron() *macaron.Macaron {
},
))

funcMap := template.NewFuncMap()
funcMap := template.NewFuncMap(m)
m.Use(macaron.Renderer(macaron.RenderOptions{
Directory: path.Join(setting.StaticRootPath, "templates"),
Funcs: funcMap,

+ 1
- 2
conf/app.ini View File

@@ -1,6 +1,5 @@
APP_NAME = myapp
CAN_REGISTER = true
ANONYMOUS_CREATE = true
; Either "dev", "prod" or "test"
RUN_MODE = dev

@@ -66,7 +65,7 @@ LEVEL =
; Webhook URL
URL =

[log.xorm]
[log.gorm]
; Enable file rotation
ROTATE = true
; Rotate every day

+ 4
- 2
context/context.go View File

@@ -27,7 +27,7 @@ type Context struct {
Flash *session.Flash
Session session.Store

User *models.User // logged in user
User models.User // logged in user

IsLogged bool
IsBasicAuth bool
@@ -186,7 +186,9 @@ func Contexter() macaron.Handler {
// Get user from session if logined.
ctx.User, ctx.IsBasicAuth = auth.SignedInUser(ctx.Context, ctx.Session)

if ctx.User != nil {
log.Info("user ID %d", ctx.User.ID)

if ctx.User.ID > 0 {
ctx.IsLogged = true
ctx.Data["IsLogged"] = ctx.IsLogged
ctx.Data["UserIsAdmin"] = ctx.User.IsAdmin

+ 1
- 1
models/errors/user.go View File

@@ -22,7 +22,7 @@ func (err EmptyName) Error() string {

// UserNotExist struct
type UserNotExist struct {
UserID int64
UserID uint
Name string
}


+ 40
- 66
models/models.go View File

@@ -1,45 +1,28 @@
package models

import (
"database/sql"
"dev.sigpipe.me/dashie/myapp/setting"
"errors"
"fmt"
// mssql
_ "github.com/denisenkom/go-mssqldb"
// mysql
_ "github.com/go-sql-driver/mysql"
"github.com/go-xorm/core"
"github.com/go-xorm/xorm"
// Postgresql
_ "github.com/lib/pq"
"github.com/jinzhu/gorm"
log "gopkg.in/clog.v1"
"net/url"
"os"
"path"
"strings"
// mysql
_ "github.com/jinzhu/gorm/dialects/mysql"
// postgresql
_ "github.com/jinzhu/gorm/dialects/postgres"
// sqlite
_ "github.com/jinzhu/gorm/dialects/sqlite"
// mssql
_ "github.com/jinzhu/gorm/dialects/mssql"
)

// Engine represents a XORM engine or session.
type Engine interface {
Delete(interface{}) (int64, error)
Exec(string, ...interface{}) (sql.Result, error)
Find(interface{}, ...interface{}) error
Get(interface{}) (bool, error)
Id(interface{}) *xorm.Session
In(string, ...interface{}) *xorm.Session
Insert(...interface{}) (int64, error)
InsertOne(interface{}) (int64, error)
Iterate(interface{}, xorm.IterFunc) error
Sql(string, ...interface{}) *xorm.Session
Table(interface{}) *xorm.Session
Where(interface{}, ...interface{}) *xorm.Session
}

// Vars
var (
x *xorm.Engine
tables []interface{}
db *gorm.DB
HasEngine bool

DbCfg struct {
@@ -49,16 +32,6 @@ var (
EnableSQLite3 bool
)

func init() {
tables = append(tables,
new(User))

gonicNames := []string{"SSL"}
for _, name := range gonicNames {
core.LintGonicMapper[name] = true
}
}

// LoadConfigs to init db
func LoadConfigs() {
sec := setting.Cfg.Section("database")
@@ -112,7 +85,7 @@ func parseMSSQLHostPort(info string) (string, string) {
return host, port
}

func getEngine() (*xorm.Engine, error) {
func getEngine() (*gorm.DB, error) {
connStr := ""
var Param = "?"
if strings.Contains(DbCfg.Name, Param) {
@@ -120,6 +93,7 @@ func getEngine() (*xorm.Engine, error) {
}
switch DbCfg.Type {
case "mysql":
// "user:password@/dbname?charset=utf8&parseTime=True&loc=Local"
if DbCfg.Host[0] == '/' { // looks like a unix socket
connStr = fmt.Sprintf("%s:%s@unix(%s)/%s%scharset=utf8&parseTime=true",
DbCfg.User, DbCfg.Passwd, DbCfg.Host, DbCfg.Name, Param)
@@ -128,6 +102,7 @@ func getEngine() (*xorm.Engine, error) {
DbCfg.User, DbCfg.Passwd, DbCfg.Host, DbCfg.Name, Param)
}
case "postgres":
// "host=myhost port=myport user=gorm dbname=gorm password=mypassword"
host, port := parsePostgreSQLHostPort(DbCfg.Host)
if host[0] == '/' { // looks like a unix socket
connStr = fmt.Sprintf("postgres://%s:%s@:%s/%s%ssslmode=%s&host=%s",
@@ -137,6 +112,7 @@ func getEngine() (*xorm.Engine, error) {
url.QueryEscape(DbCfg.User), url.QueryEscape(DbCfg.Passwd), host, port, DbCfg.Name, Param, DbCfg.SSLMode)
}
case "mssql":
// "sqlserver://username:password@localhost:1433?database=dbname"
host, port := parseMSSQLHostPort(DbCfg.Host)
connStr = fmt.Sprintf("server=%s; port=%s; database=%s; user id=%s; password=%s;", host, port, DbCfg.Name, DbCfg.User, DbCfg.Passwd)
case "sqlite3":
@@ -150,45 +126,47 @@ func getEngine() (*xorm.Engine, error) {
default:
return nil, fmt.Errorf("unknown database type: %s", DbCfg.Type)
}
return xorm.NewEngine(DbCfg.Type, connStr)
return gorm.Open(DbCfg.Type, connStr)
}

// NewTestEngine to test
func NewTestEngine(x *xorm.Engine) (err error) {
x, err = getEngine()
func NewTestEngine(db *gorm.DB) (err error) {
db, err = getEngine()
if err != nil {
return fmt.Errorf("connect to database: %v", err)
}

x.SetMapper(core.GonicMapper{})
return x.StoreEngine("InnoDB").Sync2(tables...)
return err
}

// SetEngine to use
func SetEngine() (err error) {
x, err = getEngine()
db, err = getEngine()
if err != nil {
return fmt.Errorf("fail to connect to database: %v", err)
}

x.SetMapper(core.GonicMapper{})

// WARNING: for serv command, MUST remove the output to os.stdout,
// so use log file to instead print to stdout.
sec := setting.Cfg.Section("log.xorm")
logger, err := log.NewFileWriter(path.Join(setting.LogRootPath, "xorm.log"),
log.FileRotationConfig{
Rotate: sec.Key("ROTATE").MustBool(true),
Daily: sec.Key("ROTATE_DAILY").MustBool(true),
MaxSize: sec.Key("MAX_SIZE").MustInt64(100) * 1024 * 1024,
MaxDays: sec.Key("MAX_DAYS").MustInt64(3),
})
if err != nil {
return fmt.Errorf("fail to create 'xorm.log': %v", err)
}

x.SetLogger(xorm.NewSimpleLogger3(logger, xorm.DEFAULT_LOG_PREFIX, xorm.DEFAULT_LOG_FLAG, core.LOG_DEBUG))
x.ShowSQL(true)
//sec := setting.Cfg.Section("log.gorm")
//logger, err := log.New(log.FILE, log.FileConfig {
// Level: log.TRACE,
// BufferSize: 100,
// Filename: path.Join(setting.LogRootPath, "gorm.log"),
// FileRotationConfig: log.FileRotationConfig {
// Rotate: sec.Key("ROTATE").MustBool(true),
// Daily: sec.Key("ROTATE_DAILY").MustBool(true),
// MaxSize: sec.Key("MAX_SIZE").MustInt64(100) * 1024 * 1024,
// MaxDays: sec.Key("MAX_DAYS").MustInt64(3),
// },
// })
//if err != nil {
// return fmt.Errorf("fail to create 'gorm.log': %v", err)
//}

db.LogMode(true)
// TODO logger with clog
//db.SetLogger(log.New(os.Stdout, "\r\n", 0))
return nil
}

@@ -198,18 +176,14 @@ func NewEngine() (err error) {
return err
}

// TODO: here do migrations if any

if err = x.StoreEngine("InnoDB").Sync2(tables...); err != nil {
return fmt.Errorf("sync database struct error: %v", err)
}
db.AutoMigrate(&User{})

return nil
}

// Ping pong
func Ping() error {
return x.Ping()
return db.DB().Ping()
}

// InitDb from config

+ 1
- 5
models/models_sqlite.go View File

@@ -2,10 +2,6 @@

package models

import (
_ "github.com/mattn/go-sqlite3"
)

func init() {
EnableSQLite3 = true
}
}

+ 111
- 102
models/user.go View File

@@ -9,114 +9,98 @@ import (
"encoding/hex"
"fmt"
"github.com/Unknwon/com"
"github.com/jinzhu/gorm"
"golang.org/x/crypto/pbkdf2"
log "gopkg.in/clog.v1"
"strings"
"time"
"unicode/utf8"
)

// User struct
type User struct {
ID int64 `xorm:"pk autoincr"`
UserName string `xorm:"UNIQUE NOT NULL"`
LowerName string `xorm:"UNIQUE NOT NULL"`
Email string `xorm:"NOT NULL"`
gorm.Model
UserName string `gorm:"UNIQUE;NOT NULL"`
LowerName string `gorm:"UNIQUE;NOT NULL"`
Email string `gorm:"NOT NULL"`

Password string `xorm:"NOT NULL"`
Rands string `xorm:"VARCHAR(10)"`
Salt string `xorm:"VARCHAR(10)"`
Password string `gorm:"NOT NULL"`
Rands string `gorm:"Size:10"`
Salt string `gorm:"Size:10"`

// Permissions
IsAdmin bool `xorm:"DEFAULT 0"`
IsActive bool `xorm:"DEFAULT 0"`

Created time.Time `xorm:"-"`
CreatedUnix int64
Updated time.Time `xorm:"-"`
UpdatedUnix int64
}

// BeforeInsert hooks
func (user *User) BeforeInsert() {
user.CreatedUnix = time.Now().Unix()
user.UpdatedUnix = user.CreatedUnix
IsAdmin bool `gorm:"DEFAULT:0"`
IsActive bool `gorm:"DEFAULT:0"`
}

// BeforeUpdate hooks
func (user *User) BeforeUpdate() {
user.UpdatedUnix = time.Now().Unix()
}

func countUsers(e Engine) int64 {
count, _ := x.Count(new(User))
return count
func countUsers(db *gorm.DB) (count int64) {
db.Model(&User{}).Select("id").Count(&count)
return
}

// CountUsers returns number of users.
func CountUsers() int64 {
return countUsers(x)
return countUsers(db)
}

func getUserByID(e Engine, id int64) (*User, error) {
u := new(User)
has, err := e.Id(id).Get(u)
if err != nil {
return nil, err
} else if !has {
return nil, errors.UserNotExist{id, ""}
func getUserByID(id uint) (user User, err error) {
err = db.Where("id = ?", id).First(&user).Error
if gorm.IsRecordNotFoundError(err) || user.ID == 0 {
return user, errors.UserNotExist{UserID: id, Name: ""}
} else if err != nil {
return user, err
}
return u, nil
return
}

// GetUserByID returns the user object by given ID if exists.
func GetUserByID(id int64) (*User, error) {
return getUserByID(x, id)
func GetUserByID(id uint) (User, error) {
return getUserByID(id)
}

// GetUserByName returns user by given name.
func GetUserByName(name string) (*User, error) {
func GetUserByName(name string) (user User, err error) {
if len(name) == 0 {
return nil, errors.UserNotExist{0, name}
return user, errors.UserNotExist{UserID: 0, Name: name}
}
u := &User{LowerName: strings.ToLower(name)}
has, err := x.Get(u)
if err != nil {
return nil, err
} else if !has {
return nil, errors.UserNotExist{0, name}
err = db.Where("lower_name = ?", strings.ToLower(name)).First(&user).Error
if gorm.IsRecordNotFoundError(err) || user.ID == 0 {
return user, errors.UserNotExist{UserID: 0, Name: name}
} else if err != nil {
return user, err
}
return u, nil
return
}

// GetUserByEmail returns the user object by given e-mail if exists.
func GetUserByEmail(email string) (*User, error) {
func GetUserByEmail(email string) (user User, err error) {
if len(email) == 0 {
return nil, errors.UserNotExist{0, "email"}
return user, errors.UserNotExist{UserID: 0, Name: email}
}

email = strings.ToLower(email)
user := &User{Email: email}
has, err := x.Get(user)
if err != nil {
return nil, err
}
if has {
return user, nil
err = db.Where("email = ?", strings.ToLower(email)).First(&user).Error
if gorm.IsRecordNotFoundError(err) || user.ID == 0 {
return user, errors.UserNotExist{UserID: 0, Name: email}
} else if err != nil {
return user, err
}

return nil, errors.UserNotExist{0, email}
return
}

// IsUserExist checks if given user name exist,
// the user name should be noncased unique.
// If uid is presented, then check will rule out that one,
// it is used when update a user name in settings page.
func IsUserExist(uid int64, name string) (bool, error) {
func IsUserExist(uid int64, name string) (exist bool, err error) {
if len(name) == 0 {
return false, nil
}
return x.Where("id != ?", uid).Get(&User{LowerName: strings.ToLower(name)})
user := User{}
err = db.Where("id != ?", uid).Where(&User{LowerName: strings.ToLower(name)}).First(&user).Error
if gorm.IsRecordNotFoundError(err) || user.ID == 0 {
return false, nil
} else if err != nil {
return false, nil
}
return true, nil
}

var (
@@ -173,105 +157,130 @@ func GetUserSalt() (string, error) {
}

// CreateUser and do some validation
func CreateUser(u *User) (err error) {
if err = IsUsableUsername(u.UserName); err != nil {
func CreateUser(user *User) (err error) {
if err = IsUsableUsername(user.UserName); err != nil {
return err
}

isExist, err := IsUserExist(0, u.UserName)
isExist, err := IsUserExist(0, user.UserName)
if err != nil {
return err
} else if isExist {
return ErrUserAlreadyExist{u.UserName}
return ErrUserAlreadyExist{user.UserName}
}

u.Email = strings.ToLower(u.Email)
u.LowerName = strings.ToLower(u.UserName)
user.Email = strings.ToLower(user.Email)
user.LowerName = strings.ToLower(user.UserName)

if u.Rands, err = GetUserSalt(); err != nil {
if user.Rands, err = GetUserSalt(); err != nil {
return err
}
if u.Salt, err = GetUserSalt(); err != nil {
if user.Salt, err = GetUserSalt(); err != nil {
return err
}
user.EncodePasswd()

tx := db.Begin()
defer func() {
if r := recover(); r != nil {
tx.Rollback()
}
}()

if tx.Error != nil {
return err
}
u.EncodePasswd()

sess := x.NewSession()
defer sess.Close()
if err = sess.Begin(); err != nil {
if err := tx.Create(user).Error; err != nil {
tx.Rollback()
return err
}

if _, err = sess.Insert(u); err != nil {
if err := tx.Commit().Error; err != nil {
return err
}

return sess.Commit()
return err
}

// Update an user
func updateUser(e Engine, u *User) error {
u.LowerName = strings.ToLower(u.UserName)
u.Email = strings.ToLower(u.Email)
_, err := e.Id(u.ID).AllCols().Update(u)
func updateUser(db *gorm.DB, user *User) (err error) {
tx := db.Begin()
defer func() {
if r := recover(); r != nil {
tx.Rollback()
}
}()

if tx.Error != nil {
return err
}

if err := tx.Save(user).Error; err != nil {
tx.Rollback()
return err
}

if err := tx.Commit().Error; err != nil {
return err
}

return err
}

// UpdateUser with datas
func UpdateUser(u *User) error {
return updateUser(x, u)
return updateUser(db, u)
}

// UserLogin validates user name and password.
func UserLogin(username, password string) (*User, error) {
var user *User
func UserLogin(username, password string) (user *User, err error) {
if strings.Contains(username, "@") {
user = &User{Email: strings.ToLower(username)}
} else {
user = &User{LowerName: strings.ToLower(username)}
}

hasUser, err := x.Get(user)
if err != nil {
err = db.Where(user).First(&user).Error
if gorm.IsRecordNotFoundError(err) {
return nil, errors.UserNotExist{UserID: user.ID, Name: user.UserName}
} else if err != nil {
return nil, err
}

if hasUser {
if user.ValidatePassword(password) {
return user, nil
}

return nil, errors.UserNotExist{user.ID, user.UserName}
if user.ValidatePassword(password) {
return user, nil
}

return nil, errors.UserNotExist{user.ID, user.UserName}
return nil, errors.UserNotExist{UserID: user.ID, Name: user.UserName}

}

// get user by verify code
func getVerifyUser(code string) (user *User) {
func getVerifyUser(code string) (user User) {
if len(code) <= tool.TimeLimitCodeLength {
return nil
return user
}

// use tail hex username query user
hexStr := code[tool.TimeLimitCodeLength:]
if b, err := hex.DecodeString(hexStr); err == nil {
if user, err = GetUserByName(string(b)); user != nil {
if user, err = GetUserByName(string(b)); user.ID > 0 {
return user
} else if !errors.IsUserNotExist(err) {
log.Error(2, "GetUserByName: %v", err)
}
}

return nil
return user
}

// VerifyUserActiveCode when active account
func VerifyUserActiveCode(code string) (user *User) {
func VerifyUserActiveCode(code string) (user User) {
// HARDCODED
minutes := 180

if user = getVerifyUser(code); user != nil {
if user = getVerifyUser(code); user.ID > 0 {
// time limit code
prefix := code[:tool.TimeLimitCodeLength]
data := com.ToStr(user.ID) + user.Email + user.LowerName + user.Password + user.Rands
@@ -280,7 +289,7 @@ func VerifyUserActiveCode(code string) (user *User) {
return user
}
}
return nil
return user
}

// GenerateEmailActivateCode generates an activate code based on user information and given e-mail.
@@ -304,7 +313,7 @@ type mailerUser struct {
}

// ID id
func (mUser mailerUser) ID() int64 {
func (mUser mailerUser) ID() uint {
return mUser.user.ID
}


+ 4
- 4
routers/user/auth.go View File

@@ -206,7 +206,7 @@ func RegisterPost(ctx *context.Context, f form.Register) {
}
return
}
log.Trace("Account created: %s", u.UserName)
log.Trace("Account created: %d/%s", u.ID, u.UserName)

// Auto set Admin if first user
if models.CountUsers() == 1 {
@@ -258,7 +258,7 @@ func ResetPasswdPost(ctx *context.Context) {
}
ctx.Data["Code"] = code

if u := models.VerifyUserActiveCode(code); u != nil {
if u := models.VerifyUserActiveCode(code); u.ID > 0 {
// Validate password length.
passwd := ctx.Query("password")
if len(passwd) < 6 {
@@ -279,7 +279,7 @@ func ResetPasswdPost(ctx *context.Context) {
return
}
u.EncodePasswd()
if err := models.UpdateUser(u); err != nil {
if err := models.UpdateUser(&u); err != nil {
ctx.Handle(500, "UpdateUser", err)
return
}
@@ -342,7 +342,7 @@ func ForgotPasswdPost(ctx *context.Context) {
return
}

mailer.SendResetPasswordMail(ctx.Context, models.NewMailerUser(u))
mailer.SendResetPasswordMail(ctx.Context, models.NewMailerUser(&u))
if err = ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil {
log.Error(4, "Set cache(MailResendLimit) fail: %v", err)
}

+ 1
- 1
routers/user/setting.go View File

@@ -30,7 +30,7 @@ func SettingsPost(ctx *context.Context, f form.UpdateSettingsProfile) {
}

ctx.User.Email = f.Email
if err := models.UpdateUser(ctx.User); err != nil {
if err := models.UpdateUser(&ctx.User); err != nil {
ctx.ServerError("UpdateUser", err)
return
}

+ 6
- 6
stuff/auth/auth.go View File

@@ -20,7 +20,7 @@ func IsAPIPath(url string) bool {
}

// SignedInID returns the id of signed in user.
func SignedInID(ctx *macaron.Context, sess session.Store) int64 {
func SignedInID(ctx *macaron.Context, sess session.Store) uint {
if !models.HasEngine {
return 0
}
@@ -29,7 +29,7 @@ func SignedInID(ctx *macaron.Context, sess session.Store) int64 {
if uid == nil {
return 0
}
if id, ok := uid.(int64); ok {
if id, ok := uid.(uint); ok {
if _, err := models.GetUserByID(id); err != nil {
if !errors.IsUserNotExist(err) {
log.Error(2, "GetUserByID: %v", err)
@@ -43,21 +43,21 @@ func SignedInID(ctx *macaron.Context, sess session.Store) int64 {

// SignedInUser returns the user object of signed user.
// It returns a bool value to indicate whether user uses basic auth or not.
func SignedInUser(ctx *macaron.Context, sess session.Store) (*models.User, bool) {
func SignedInUser(ctx *macaron.Context, sess session.Store) (user models.User, basicAuth bool) {
if !models.HasEngine {
return nil, false
return user, false
}

uid := SignedInID(ctx, sess)

if uid <= 0 {
return nil, false
return user, false
}

u, err := models.GetUserByID(uid)
if err != nil {
log.Error(4, "GetUserById: %v", err)
return nil, false
return u, false
}
return u, false
}

+ 1
- 1
stuff/mailer/mail.go View File

@@ -53,7 +53,7 @@ func SendTestMail(email string) error {

// User is email user
type User interface {
ID() int64
ID() uint
DisplayName() string
Email() string
GenerateActivateCode() string

+ 5
- 1
stuff/template/template.go View File

@@ -8,6 +8,7 @@ import (
"dev.sigpipe.me/dashie/myapp/stuff/tool"
"fmt"
"github.com/microcosm-cc/bluemonday"
"gopkg.in/macaron.v1"
"html/template"
"mime"
"path/filepath"
@@ -17,7 +18,7 @@ import (
)

// NewFuncMap initialize the Functions Map
func NewFuncMap() []template.FuncMap {
func NewFuncMap(m *macaron.Macaron) []template.FuncMap {
return []template.FuncMap{map[string]interface{}{
"GoVer": func() string {
return strings.Title(runtime.Version())
@@ -97,6 +98,9 @@ func NewFuncMap() []template.FuncMap {
"IsPdf": func(mime string) bool {
return strings.EqualFold(mime, "application/pdf")
},
"URLFor": func(name string, pairs ...string) string {
return fmt.Sprintf("%s%s", strings.TrimSuffix(setting.AppURL, "/"), m.URLFor(name, pairs...))
},
}}
}


Loading…
Cancel
Save