goploy/internal/model/user.go

287 lines
7.0 KiB
Go
Raw Normal View History

2022-04-09 21:53:37 +08:00
// Copyright 2022 The Goploy Authors. All rights reserved.
// Use of this source code is governed by a GPLv3-style
// license that can be found in the LICENSE file.
2020-08-04 14:28:25 +08:00
package model
import (
2023-07-14 14:38:03 +08:00
"crypto/rand"
"database/sql"
2020-08-04 14:28:25 +08:00
"errors"
2021-12-14 17:42:12 +08:00
"github.com/zhenorzz/goploy/config"
2020-08-04 14:28:25 +08:00
"time"
sq "github.com/Masterminds/squirrel"
2021-08-15 23:27:22 +08:00
"github.com/golang-jwt/jwt"
2020-08-04 14:28:25 +08:00
"golang.org/x/crypto/bcrypt"
)
const userTable = "`user`"
2022-02-24 09:14:50 +08:00
// user role
const (
SuperManager = 1
GeneralUser = 0
)
2020-08-04 14:28:25 +08:00
type User struct {
ID int64 `json:"id"`
Account string `json:"account"`
Password string `json:"password"`
PasswordUpdateTime sql.NullString `json:"passwordUpdateTime"`
Name string `json:"name"`
Contact string `json:"contact"`
SuperManager int64 `json:"superManager"`
State uint8 `json:"state"`
InsertTime string `json:"insertTime"`
UpdateTime string `json:"updateTime"`
LastLoginTime string `json:"lastLoginTime"`
ApiKey string `json:"apiKey"`
2020-08-04 14:28:25 +08:00
}
type Users []User
func (u User) GetData() (User, error) {
var user User
err := sq.
2020-09-02 17:08:11 +08:00
Select("id, account, password, name, contact, super_manager, state, insert_time, update_time").
2020-08-04 14:28:25 +08:00
From(userTable).
Where(sq.Eq{"id": u.ID}).
RunWith(DB).
QueryRow().
2020-09-02 17:08:11 +08:00
Scan(&user.ID, &user.Account, &user.Password, &user.Name, &user.Contact, &user.SuperManager, &user.State, &user.InsertTime, &user.UpdateTime)
2020-08-04 14:28:25 +08:00
if err != nil {
return user, err
}
return user, nil
}
func (u User) GetDataByAccount() (User, error) {
var user User
err := sq.
Select("id, account, password, password_update_time, name, contact, super_manager, state, insert_time, update_time").
2020-08-04 14:28:25 +08:00
From(userTable).
Where(sq.Eq{"account": u.Account}).
RunWith(DB).
QueryRow().
Scan(&user.ID, &user.Account, &user.Password, &user.PasswordUpdateTime, &user.Name, &user.Contact, &user.SuperManager, &user.State, &user.InsertTime, &user.UpdateTime)
2023-06-21 17:45:59 +08:00
if err != nil {
return user, err
}
return user, nil
}
func (u User) GetDataByContact() (User, error) {
var user User
err := sq.
Select("id, account, password, name, contact, super_manager, state, insert_time, update_time").
From(userTable).
Where(sq.Eq{"contact": u.Contact}).
RunWith(DB).
QueryRow().
Scan(&user.ID, &user.Account, &user.Password, &user.Name, &user.Contact, &user.SuperManager, &user.State, &user.InsertTime, &user.UpdateTime)
2020-08-04 14:28:25 +08:00
if err != nil {
return user, err
}
return user, nil
}
2023-07-14 10:14:48 +08:00
func (u User) GetDataByApiKey() (User, error) {
var user User
err := sq.
Select("id, account, password, name, contact, super_manager, state, insert_time, update_time").
From(userTable).
Where(sq.Eq{"api_key": u.ApiKey}).
RunWith(DB).
QueryRow().
Scan(&user.ID, &user.Account, &user.Password, &user.Name, &user.Contact, &user.SuperManager, &user.State, &user.InsertTime, &user.UpdateTime)
if err != nil {
return user, err
}
return user, nil
}
2023-07-14 14:38:03 +08:00
func (u User) GetApiKey() (apiKey string, err error) {
err = sq.
Select("api_key").
From(userTable).
Where(sq.Eq{"id": u.ID}).
RunWith(DB).
QueryRow().
Scan(&apiKey)
if err != nil {
return apiKey, err
}
return apiKey, nil
}
2022-04-09 11:47:32 +08:00
func (u User) GetList() (Users, error) {
2020-08-04 14:28:25 +08:00
rows, err := sq.
2020-09-02 17:08:11 +08:00
Select("id, account, name, contact, super_manager, insert_time, update_time").
2020-08-04 14:28:25 +08:00
From(userTable).
Where(sq.Eq{"state": Enable}).
OrderBy("id DESC").
RunWith(DB).
Query()
if err != nil {
return nil, err
}
users := Users{}
for rows.Next() {
var user User
2020-09-02 17:08:11 +08:00
if err := rows.Scan(&user.ID, &user.Account, &user.Name, &user.Contact, &user.SuperManager, &user.InsertTime, &user.UpdateTime); err != nil {
2020-08-04 14:28:25 +08:00
return users, err
}
users = append(users, user)
}
return users, nil
}
func (u User) GetTotal() (int64, error) {
var total int64
err := sq.
Select("COUNT(*) AS count").
From(userTable).
Where(sq.Eq{"state": Enable}).
RunWith(DB).
QueryRow().
Scan(&total)
if err != nil {
return 0, err
}
return total, nil
}
func (u User) AddRow() (int64, error) {
if u.Password == "" {
u.Password = u.Account + "!@#"
}
password := []byte(u.Password)
// Hashing the password with the default cost of 10
hashedPassword, err := bcrypt.GenerateFromPassword(password, bcrypt.DefaultCost)
if err != nil {
return 0, err
}
result, err := sq.
Insert(userTable).
2020-09-02 17:08:11 +08:00
Columns("account", "password", "name", "contact", "super_manager").
Values(u.Account, string(hashedPassword), u.Name, u.Contact, u.SuperManager).
2020-08-04 14:28:25 +08:00
RunWith(DB).
Exec()
if err != nil {
return 0, err
}
id, err := result.LastInsertId()
return id, err
}
func (u User) EditRow() error {
builder := sq.
Update(userTable).
SetMap(sq.Eq{
"name": u.Name,
2021-08-15 23:27:22 +08:00
"contact": u.Contact,
2020-08-04 14:28:25 +08:00
"super_manager": u.SuperManager,
}).
Where(sq.Eq{"id": u.ID})
if u.Password != "" {
password := []byte(u.Password)
// Hashing the password with the default cost of 10
hashedPassword, err := bcrypt.GenerateFromPassword(password, bcrypt.DefaultCost)
if err != nil {
return err
}
builder = builder.Set("password", hashedPassword)
}
_, err := builder.RunWith(DB).Exec()
return err
}
func (u User) RemoveRow() error {
_, err := sq.
Update(userTable).
SetMap(sq.Eq{
"state": Disable,
}).
Where(sq.Eq{"id": u.ID}).
RunWith(DB).
Exec()
return err
}
func (u User) UpdatePassword() error {
password := []byte(u.Password)
// Hashing the password with the default cost of 10
hashedPassword, err := bcrypt.GenerateFromPassword(password, bcrypt.DefaultCost)
if err != nil {
return err
}
_, err = sq.
Update(userTable).
SetMap(sq.Eq{
"password": string(hashedPassword),
"password_update_time": u.PasswordUpdateTime,
2020-08-04 14:28:25 +08:00
}).
Where(sq.Eq{"id": u.ID}).
RunWith(DB).
Exec()
return err
}
2020-08-15 13:38:06 +08:00
// UpdateLastLoginTime -
2020-08-04 14:28:25 +08:00
func (u User) UpdateLastLoginTime() error {
_, err := sq.
Update(userTable).
SetMap(sq.Eq{
"last_login_time": u.LastLoginTime,
}).
Where(sq.Eq{"id": u.ID}).
RunWith(DB).
Exec()
return err
}
2023-07-14 10:14:48 +08:00
// Validate user password
2020-08-04 14:28:25 +08:00
func (u User) Validate(inputPassword string) error {
err := bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(inputPassword))
if err != nil {
2023-08-17 09:52:49 +08:00
return errors.New("invalid username or password")
2020-08-04 14:28:25 +08:00
}
return nil
}
func (u User) CreateToken() (string, error) {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"id": u.ID,
"name": u.Name,
"exp": time.Now().Add(time.Hour * 24).Unix(),
"nbf": time.Now().Unix(),
})
2021-12-14 17:42:12 +08:00
tokenString, err := token.SignedString([]byte(config.Toml.JWT.Key))
2020-08-04 14:28:25 +08:00
//Sign and get the complete encoded token as string
return tokenString, err
}
2023-07-14 14:38:03 +08:00
func (u User) CreateApiKey() (string, error) {
const alphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
var bytes = make([]byte, 32)
rand.Read(bytes)
for i, b := range bytes {
bytes[i] = alphanum[b%byte(len(alphanum))]
}
_, err := sq.
Update(userTable).
SetMap(sq.Eq{
"api_key": string(bytes),
}).
Where(sq.Eq{"id": u.ID}).
RunWith(DB).
Exec()
return string(bytes), err
}