52 lines
1.1 KiB
Go
52 lines
1.1 KiB
Go
package models
|
|
|
|
import (
|
|
"net/http"
|
|
)
|
|
|
|
type Account struct {
|
|
ID int `json:"id"`
|
|
Name string `json:"name"`
|
|
Email string `json:"email"`
|
|
SessionID string `json:"session_id"`
|
|
CreatedAt string `json:"created_at"`
|
|
UpdatedAt string `json:"updated_at"`
|
|
}
|
|
|
|
func AccountRead(w http.ResponseWriter, r *http.Request, cb func(account *Account)) {
|
|
// 從Cookie中獲取session_id
|
|
cookie, err := r.Cookie("session_id")
|
|
if err != nil {
|
|
w.WriteHeader(http.StatusUnauthorized)
|
|
w.Write([]byte("401 - 未登錄"))
|
|
return
|
|
}
|
|
|
|
// 獲取當前session
|
|
session := Session{ID: cookie.Value}
|
|
if err := session.Get(); err != nil {
|
|
w.WriteHeader(http.StatusUnauthorized)
|
|
w.Write([]byte("401 - 會話已過期"))
|
|
return
|
|
}
|
|
|
|
// 獲取當前用戶
|
|
user := User{ID: session.UserID}
|
|
if err := user.Get(); err != nil {
|
|
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.SessionID = session.ID
|
|
account.CreatedAt = user.CreatedAt
|
|
account.UpdatedAt = user.UpdatedAt
|
|
|
|
cb(&account)
|
|
|
|
}
|