weiro/models/users.go

46 lines
924 B
Go

package models
import (
"time"
"golang.org/x/crypto/bcrypt"
)
type User struct {
ID int64
Username string
PasswordHashed []byte
TimeZone string
}
func (u *User) SetPassword(pwd string) {
bcrypted, _ := bcrypt.GenerateFromPassword([]byte(pwd), bcrypt.DefaultCost)
u.PasswordHashed = bcrypted
}
func (u User) CheckPassword(pwd string) bool {
err := bcrypt.CompareHashAndPassword(u.PasswordHashed, []byte(pwd))
return err == nil
}
func (u User) FormatTime(t time.Time) string {
if loc := getLocation(u.TimeZone); loc != nil {
return t.In(loc).Format("2006-01-02 15:04:05")
}
return t.Format("2006-01-02 15:04:05")
}
var loadedLocation = map[string]*time.Location{}
func getLocation(tz string) *time.Location {
if loc, ok := loadedLocation[tz]; ok {
return loc
}
loc, err := time.LoadLocation(tz)
if err != nil {
loc = time.Local
}
loadedLocation[tz] = loc
return loc
}