增加密码修改、会话退出和登录记录接口

This commit is contained in:
xhgit committed 2026-11-16 07:06:40 +08:00
1 parent 225ce96844
commit e05c930a9d
9 files changed
+319 -2

No files matched your search

+110
View File
@@ -0,0 +1,110 @@
package account
import (
"context"
"errors"
"time"
"github.com/jackc/pgx/v5"
)
var ErrPassword = errors.New("incorrect current password")
func lockSession(ctx context.Context, tx pgx.Tx, user, token string) error {
if _, err := tx.Exec(ctx, "SELECT id FROM users WHERE id=$1 FOR UPDATE", user); err != nil {
return err
}
digest, err := SessionDigest(token)
if err != nil {
return err
}
var device string
err = tx.QueryRow(ctx, `SELECT d.id FROM sessions s JOIN devices d ON d.id=s.device_id
WHERE s.token_hash=$1 AND d.user_id=$2 AND d.revoked_at IS NULL AND s.expires_at>now()
FOR UPDATE OF d,s`, digest[:], user).Scan(&device)
if errors.Is(err, pgx.ErrNoRows) {
return ErrCredentials
}
return err
}
func (s *Store) ChangePassword(ctx context.Context, user, token, current, next string) error {
var previousHash string
if err := s.db.QueryRow(ctx, "SELECT password_hash FROM users WHERE id=$1", user).Scan(&previousHash); err != nil {
return err
}
if !VerifyPassword(current, previousHash) {
return ErrPassword
}
nextHash := PasswordHash(next)
tx, err := s.db.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(ctx)
if err = lockSession(ctx, tx, user, token); err != nil {
return err
}
tag, err := tx.Exec(ctx, "UPDATE users SET password_hash=$1 WHERE id=$2 AND password_hash=$3", nextHash, user, previousHash)
if err != nil {
return err
}
if tag.RowsAffected() != 1 {
return ErrPassword
}
if _, err = tx.Exec(ctx, "DELETE FROM sessions WHERE device_id IN (SELECT id FROM devices WHERE user_id=$1)", user); err != nil {
return err
}
return tx.Commit(ctx)
}
func (s *Store) LogoutOthers(ctx context.Context, user, token string) error {
tx, err := s.db.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(ctx)
if err = lockSession(ctx, tx, user, token); err != nil {
return err
}
digest, _ := SessionDigest(token)
if _, err = tx.Exec(ctx, `DELETE FROM sessions WHERE token_hash<>$2 AND device_id IN
(SELECT id FROM devices WHERE user_id=$1)`, user, digest[:]); err != nil {
return err
}
return tx.Commit(ctx)
}
func (s *Store) RenameDevice(ctx context.Context, user, device, name string) error {
tag, err := s.db.Exec(ctx, "UPDATE devices SET name=$3,name_custom=true WHERE user_id=$1 AND id=$2 AND revoked_at IS NULL", user, device, name)
if err == nil && tag.RowsAffected() != 1 {
return pgx.ErrNoRows
}
return err
}
type LoginRecord struct {
ID string `json:"id"`
DeviceName string `json:"deviceName"`
Platform string `json:"platform"`
CreatedAt time.Time `json:"createdAt"`
CurrentDevice bool `json:"currentDevice"`
}
func (s *Store) LoginHistory(ctx context.Context, user, device string) ([]LoginRecord, error) {
rows, err := s.db.Query(ctx, `SELECT id::text,device_name,platform,created_at,device_id=$2
FROM login_history WHERE user_id=$1 ORDER BY id DESC LIMIT 50`, user, device)
if err != nil {
return nil, err
}
defer rows.Close()
items := make([]LoginRecord, 0)
for rows.Next() {
var item LoginRecord
if err := rows.Scan(&item.ID, &item.DeviceName, &item.Platform, &item.CreatedAt, &item.CurrentDevice); err != nil {
return nil, err
}
items = append(items, item)
}
return items, rows.Err()
}
+16 -1
View File
@@ -87,12 +87,19 @@ func (s *Store) Open(ctx context.Context, register bool, username, password, nam
return Auth{}, err
}
}
var currentHash string
if err = tx.QueryRow(ctx, "SELECT password_hash FROM users WHERE id=$1 FOR UPDATE", result.User.ID).Scan(&currentHash); err != nil {
return Auth{}, err
}
if currentHash != hash {
return Auth{}, ErrCredentials
}
row := tx.QueryRow(ctx, `
INSERT INTO devices(user_id, public_key, name, platform)
VALUES ($1,$2,$3,$4)
ON CONFLICT (user_id, public_key) DO UPDATE
SET last_active_at=now(), name=EXCLUDED.name
SET last_active_at=now(), name=CASE WHEN devices.name_custom THEN devices.name ELSE EXCLUDED.name END
WHERE devices.revoked_at IS NULL AND devices.platform=EXCLUDED.platform
RETURNING id, name, platform, created_at, last_active_at, revoked_at
`, result.User.ID, publicKey, name, platform)
@@ -107,6 +114,14 @@ func (s *Store) Open(ctx context.Context, register bool, username, password, nam
if _, err = tx.Exec(ctx, "INSERT INTO sessions VALUES ($1,$2,$3)", digest[:], result.Device.ID, time.Now().Add(s.ttl)); err != nil {
return Auth{}, err
}
if _, err = tx.Exec(ctx, `INSERT INTO login_history(user_id,device_id,device_name,platform) VALUES ($1,$2,$3,$4)`,
result.User.ID, result.Device.ID, result.Device.Name, result.Device.Platform); err != nil {
return Auth{}, err
}
if _, err = tx.Exec(ctx, `DELETE FROM login_history WHERE user_id=$1 AND id NOT IN
(SELECT id FROM login_history WHERE user_id=$1 ORDER BY id DESC LIMIT 50)`, result.User.ID); err != nil {
return Auth{}, err
}
result.Device.SignedIn = true
return result, tx.Commit(ctx)
}
@@ -0,0 +1,11 @@
ALTER TABLE devices ADD COLUMN name_custom boolean NOT NULL DEFAULT false;
CREATE TABLE login_history (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
device_id uuid NOT NULL REFERENCES devices(id) ON DELETE CASCADE,
device_name text NOT NULL,
platform text NOT NULL CHECK (platform IN ('web','windows')),
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX login_history_user ON login_history(user_id,id DESC);
+4 -1
View File
@@ -49,6 +49,9 @@ var contactMuteMigration string
//go:embed 014_private_conversations.sql
var privateConversationsMigration string
//go:embed 015_login_history.sql
var loginHistoryMigration string
func Migrate(ctx context.Context, pool *pgxpool.Pool) error {
tx, err := pool.Begin(ctx)
if err != nil {
@@ -64,7 +67,7 @@ func Migrate(ctx context.Context, pool *pgxpool.Pool) error {
for index, migration := range []string{
identityMigration, contactsMigration, deliveryMigration, keyPackagesMigration, mlsCredentialsMigration,
attachmentsMigration, groupsMigration, groupTransportMigration, groupAttachmentsMigration, groupPreferencesMigration,
groupSeenMigration, groupInviteLinkMigration, contactMuteMigration, privateConversationsMigration,
groupSeenMigration, groupInviteLinkMigration, contactMuteMigration, privateConversationsMigration, loginHistoryMigration,
} {
version := index + 1
var applied bool
@@ -0,0 +1,92 @@
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)
}
+4
View File
@@ -44,6 +44,10 @@ func New(accounts *account.Store, contactStore *contacts.Store, envelopeStore *d
mux.HandleFunc("POST /api/v1/auth/logout", a.authorized(a.logout))
mux.HandleFunc("GET /api/v1/me", a.authorized(a.me))
mux.HandleFunc("GET /api/v1/devices", a.authorized(a.devices))
mux.HandleFunc("POST /api/v1/devices/{id}", a.authorized(a.renameDevice))
mux.HandleFunc("POST /api/v1/auth/password", a.authorized(a.changePassword))
mux.HandleFunc("POST /api/v1/auth/logout-others", a.authorized(a.logoutOthers))
mux.HandleFunc("GET /api/v1/auth/history", a.authorized(a.loginHistory))
mux.HandleFunc("DELETE /api/v1/devices/{id}", a.authorized(a.revoke))
mux.HandleFunc("POST /api/v1/realtime/ticket", a.authorized(a.ticket))
mux.HandleFunc("GET /api/v1/realtime", a.realtime)