aim-oscar-server/models/User.go

91 lines
2.1 KiB
Go
Raw Normal View History

2021-12-16 17:41:17 -05:00
package models
import (
"context"
"database/sql"
2021-12-18 17:10:00 -05:00
"time"
2021-12-16 17:41:17 -05:00
"github.com/pkg/errors"
"github.com/uptrace/bun"
)
2021-12-19 01:14:25 -05:00
type UserStatus int16
const (
2021-12-19 17:17:47 -05:00
UserStatusOnline = 0
UserStatusAway = 1
UserStatusDnd = 2
UserStatusNA = 4
UserStatusOccupied = 0x10
UserStatusFree4Chat = 0x20
UserStatusInvisible = 0x100
2021-12-19 01:14:25 -05:00
)
2021-12-16 17:41:17 -05:00
type User struct {
2021-12-19 17:17:47 -05:00
bun.BaseModel `bun:"table:users"`
UIN int64 `bun:",pk,autoincrement"`
Email string `bun:",unique"`
Username string `bun:",unique"`
Password string
Cipher string
CreatedAt time.Time `bun:",nullzero,notnull,default:current_timestamp"`
UpdatedAt time.Time `bun:",nullzero,notnull,default:current_timestamp"`
Status UserStatus
Profile string
ProfileEncoding string
AwayMessage string
AwayMessageEncoding string
LastActivityAt time.Time `bin:"-"`
2021-12-16 17:41:17 -05:00
}
type userKey string
func (s userKey) String() string {
return "user-" + string(s)
}
var (
currentUser = userKey("user")
)
2021-12-16 17:41:17 -05:00
func UserByUsername(ctx context.Context, db *bun.DB, username string) (*User, error) {
user := new(User)
if err := db.NewSelect().Model(user).Where("username = ?", username).Scan(ctx, user); err != nil {
if err == sql.ErrNoRows {
return nil, nil
}
return nil, errors.Wrap(err, "could not fetch user")
}
return user, nil
}
2021-12-18 21:02:47 -05:00
func UserByUIN(ctx context.Context, db *bun.DB, uin int64) (*User, error) {
user := new(User)
if err := db.NewSelect().Model(user).Where("uin = ?", uin).Scan(ctx, user); err != nil {
if err == sql.ErrNoRows {
return nil, nil
}
return nil, errors.Wrap(err, "could not fetch user")
}
return user, nil
}
func NewContextWithUser(ctx context.Context, user *User) context.Context {
return context.WithValue(ctx, currentUser, user)
}
func UserFromContext(ctx context.Context) *User {
v := ctx.Value(currentUser)
if v == nil {
return nil
}
return v.(*User)
}
2021-12-16 17:41:17 -05:00
func (u *User) Update(ctx context.Context, db *bun.DB) error {
if _, err := db.NewUpdate().Model(u).WherePK("uin").Exec(ctx); err != nil {
return errors.Wrap(err, "could not update user")
}
return nil
}