100 lines
2.3 KiB
Go
100 lines
2.3 KiB
Go
package models
|
|
|
|
import (
|
|
"fmt"
|
|
"log"
|
|
"main/configs"
|
|
"net/http"
|
|
"strconv"
|
|
"time"
|
|
)
|
|
|
|
type Account struct {
|
|
ID int `json:"id"`
|
|
Name string `json:"name"`
|
|
Email string `json:"email"`
|
|
Admin bool `json:"admin"`
|
|
SessionID string `json:"session_id"`
|
|
CreatedAt time.Time `json:"created_at"`
|
|
UpdatedAt time.Time `json:"updated_at"`
|
|
LikeList interface{} `json:"likes" gorm:"-"`
|
|
}
|
|
|
|
// 将字符串数组转换为整数数组
|
|
func toInt(list []string) (result []int) {
|
|
for _, v := range list {
|
|
i, err := strconv.Atoi(v)
|
|
if err != nil {
|
|
log.Println(err)
|
|
continue
|
|
}
|
|
result = append(result, i)
|
|
}
|
|
// 如果沒有喜歡的圖片, 則返回空數組
|
|
if len(result) == 0 {
|
|
result = []int{}
|
|
}
|
|
return
|
|
}
|
|
|
|
// 獲取當前賬戶的喜歡列表
|
|
func (account *Account) ReadLikeList() {
|
|
log.Println("ReadLikeList: account.ID = ", account.ID)
|
|
is, err := LikeImage.GetA(fmt.Sprintf("%d", account.ID))
|
|
if err != nil {
|
|
log.Println(err)
|
|
return
|
|
}
|
|
ms, err := LikeModel.GetA(fmt.Sprintf("%d", account.ID))
|
|
if err != nil {
|
|
log.Println(err)
|
|
return
|
|
}
|
|
account.LikeList = map[string]interface{}{
|
|
"images": toInt(is),
|
|
"models": toInt(ms),
|
|
}
|
|
}
|
|
|
|
// 獲取當前賬戶信息
|
|
func AccountRead(w http.ResponseWriter, r *http.Request, cb func(account *Account)) {
|
|
|
|
// 獲取Cookie
|
|
cookie, err := r.Cookie("session_id")
|
|
if err != nil {
|
|
w.WriteHeader(http.StatusUnauthorized)
|
|
w.Write([]byte("401 - 未登錄, 請登錄後再進行操作"))
|
|
return
|
|
}
|
|
|
|
// 獲取會話
|
|
session := Session{ID: cookie.Value}
|
|
if err := configs.ORMDB().Take(&session).Error; err != nil {
|
|
http.SetCookie(w, &http.Cookie{Name: "session_id", Value: "", Path: "/", MaxAge: -1})
|
|
w.WriteHeader(http.StatusUnauthorized)
|
|
w.Write([]byte("401 - 會話已過期, 請重新登錄"))
|
|
return
|
|
}
|
|
|
|
// 獲取當前用戶
|
|
user := User{ID: session.UserID}
|
|
if err := configs.ORMDB().Take(&user).Error; err != nil {
|
|
http.SetCookie(w, &http.Cookie{Name: "session_id", Value: "", Path: "/", MaxAge: -1})
|
|
w.WriteHeader(http.StatusUnauthorized)
|
|
w.Write([]byte("401 - 用戶不存在, 請重新登錄"))
|
|
return
|
|
}
|
|
|
|
var account Account
|
|
account.ID = user.ID
|
|
account.Name = user.Name
|
|
account.Email = user.Email
|
|
account.Admin = user.Admin
|
|
account.SessionID = session.ID
|
|
account.CreatedAt = user.CreatedAt
|
|
account.UpdatedAt = user.UpdatedAt
|
|
|
|
cb(&account)
|
|
|
|
}
|