Files

93 lines
2.8 KiB
Go

package httpapi
import (
"errors"
"net/http"
"strings"
"unicode"
"unicode/utf8"
"github.com/jackc/pgx/v5"
"xhchat/server/internal/account"
)
func (a *API) changePassword(w http.ResponseWriter, r *http.Request, token string, identity account.Identity) {
var input struct {
CurrentPassword string `json:"currentPassword"`
NewPassword string `json:"newPassword"`
}
if !parse(w, r, &input) {
return
}
if len(input.CurrentPassword) > 256 || input.CurrentPassword == "" || len(input.NewPassword) > 256 || utf8.RuneCountInString(input.NewPassword) < 12 {
problem(w, 400, "invalid_password", "新密码须至少 12 个字符且最多 256 字节")
return
}
if !a.limit(w, r, "change-password:"+identity.User.ID, 6) {
return
}
select {
case a.hashSlots <- struct{}{}:
defer func() { <-a.hashSlots }()
default:
problem(w, 429, "busy", "密码服务繁忙,请稍后重试")
return
}
err := a.accounts.ChangePassword(r.Context(), identity.User.ID, token, input.CurrentPassword, input.NewPassword)
if errors.Is(err, account.ErrPassword) {
problem(w, 403, "incorrect_password", "当前密码不正确")
return
}
accountSettingResult(w, err)
}
func accountSettingResult(w http.ResponseWriter, err error) {
switch {
case errors.Is(err, account.ErrCredentials):
problem(w, 401, "unauthorized", "登录会话已失效")
case errors.Is(err, pgx.ErrNoRows):
problem(w, 404, "device_not_found", "找不到有效设备")
case err != nil:
unavailable(w, err)
default:
w.WriteHeader(204)
}
}
func (a *API) logoutOthers(w http.ResponseWriter, r *http.Request, token string, identity account.Identity) {
if !a.limit(w, r, "logout-others:"+identity.User.ID, 12) {
return
}
accountSettingResult(w, a.accounts.LogoutOthers(r.Context(), identity.User.ID, token))
}
func (a *API) renameDevice(w http.ResponseWriter, r *http.Request, _ string, identity account.Identity) {
var input struct {
Name string `json:"name"`
}
if !parse(w, r, &input) {
return
}
input.Name = strings.TrimSpace(input.Name)
if !uuidPattern.MatchString(r.PathValue("id")) || input.Name == "" || utf8.RuneCountInString(input.Name) > 64 || strings.ContainsFunc(input.Name, unicode.IsControl) {
problem(w, 400, "invalid_device", "请检查设备名称,最多 64 个字符")
return
}
if !a.limit(w, r, "rename-device:"+identity.User.ID, 30) {
return
}
accountSettingResult(w, a.accounts.RenameDevice(r.Context(), identity.User.ID, r.PathValue("id"), input.Name))
}
func (a *API) loginHistory(w http.ResponseWriter, r *http.Request, _ string, identity account.Identity) {
if !a.limit(w, r, "login-history:"+identity.User.ID, 60) {
return
}
items, err := a.accounts.LoginHistory(r.Context(), identity.User.ID, identity.Device.ID)
if err != nil {
unavailable(w, err)
return
}
respond(w, 200, items)
}