Files
mengpost/mengpost-backend/models/oauth_pending.go

48 lines
1.3 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package models
import (
"database/sql"
"errors"
"mengpost-backend/database"
)
// ErrOAuthPendingNotFound state 不存在或尚未完成微软回调.
var ErrOAuthPendingNotFound = errors.New("oauth state 无效或已过期")
func InsertOAuthPendingState(state string) error {
_, err := database.DB.Exec(`INSERT INTO oauth_microsoft_pending(state) VALUES(?)`, state)
return err
}
func UpdateOAuthPendingTokens(state, refresh, email string) error {
res, err := database.DB.Exec(
`UPDATE oauth_microsoft_pending SET refresh_token=?, email=? WHERE state=?`,
refresh, email, state,
)
if err != nil {
return err
}
n, _ := res.RowsAffected()
if n == 0 {
return ErrOAuthPendingNotFound
}
return nil
}
// TakeOAuthPending 取出并删除 pending用于完成账户创建.
func TakeOAuthPending(state string) (refresh, email string, err error) {
row := database.DB.QueryRow(
`SELECT refresh_token, email FROM oauth_microsoft_pending WHERE state=? AND refresh_token IS NOT NULL AND email IS NOT NULL`,
state,
)
if err := row.Scan(&refresh, &email); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return "", "", ErrOAuthPendingNotFound
}
return "", "", err
}
_, _ = database.DB.Exec(`DELETE FROM oauth_microsoft_pending WHERE state=?`, state)
return refresh, email, nil
}