statping/users.go

92 lines
2.0 KiB
Go
Raw Normal View History

2018-06-10 01:31:13 +00:00
package main
import (
"golang.org/x/crypto/bcrypt"
2018-06-23 08:42:50 +00:00
"net/http"
2018-06-15 04:30:10 +00:00
"time"
2018-06-10 01:31:13 +00:00
)
type User struct {
2018-06-15 04:30:10 +00:00
Id int64 `db:"id,omitempty" json:"id"`
Username string `db:"username" json:"username"`
Password string `db:"password" json:"-"`
Email string `db:"email" json:"-"`
ApiKey string `db:"api_key" json:"api_key"`
ApiSecret string `db:"api_secret" json:"-"`
2018-06-23 05:59:29 +00:00
Admin bool `db:"administrator" json:"admin"`
2018-06-15 04:30:10 +00:00
CreatedAt time.Time `db:"created_at" json:"created_at"`
2018-06-10 01:31:13 +00:00
}
2018-06-23 08:42:50 +00:00
func SessionUser(r *http.Request) *User {
session, _ := store.Get(r, cookieKey)
if session == nil {
return nil
}
uuid := session.Values["user_id"]
var user *User
col := dbSession.Collection("users")
res := col.Find("id", uuid)
res.One(&user)
return user
}
2018-06-15 04:30:10 +00:00
func SelectUser(id int64) (*User, error) {
2018-06-10 01:31:13 +00:00
var user User
2018-06-15 04:30:10 +00:00
col := dbSession.Collection("users")
res := col.Find("id", id)
err := res.One(&user)
return &user, err
2018-06-10 01:31:13 +00:00
}
2018-06-15 04:30:10 +00:00
func SelectUsername(username string) (*User, error) {
var user User
col := dbSession.Collection("users")
res := col.Find("username", username)
err := res.One(&user)
return &user, err
}
2018-06-19 04:48:25 +00:00
func (u *User) Delete() error {
col := dbSession.Collection("users")
user := col.Find("id", u.Id)
return user.Delete()
}
2018-06-15 04:30:10 +00:00
func (u *User) Create() (int64, error) {
u.CreatedAt = time.Now()
2018-06-23 08:42:50 +00:00
u.Password = HashPassword(u.Password)
2018-06-15 04:30:10 +00:00
u.ApiKey = NewSHA1Hash(5)
u.ApiSecret = NewSHA1Hash(10)
col := dbSession.Collection("users")
uuid, err := col.Insert(u)
if uuid == nil {
return 0, err
}
2018-06-19 04:48:25 +00:00
OnNewUser(u)
2018-06-15 04:30:10 +00:00
return uuid.(int64), err
2018-06-10 01:31:13 +00:00
}
2018-06-15 04:30:10 +00:00
func SelectAllUsers() ([]User, error) {
2018-06-10 01:31:13 +00:00
var users []User
2018-06-15 04:30:10 +00:00
col := dbSession.Collection("users").Find()
err := col.All(&users)
return users, err
2018-06-10 01:31:13 +00:00
}
2018-06-15 04:30:10 +00:00
func AuthUser(username, password string) (*User, bool) {
2018-06-10 01:31:13 +00:00
var auth bool
2018-06-15 04:30:10 +00:00
user, err := SelectUsername(username)
if err != nil {
return nil, false
}
2018-06-10 01:31:13 +00:00
if CheckHash(password, user.Password) {
auth = true
}
return user, auth
}
func CheckHash(password, hash string) bool {
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
return err == nil
}