Compare commits
7 Commits
0f1c8e327e
...
develop
| Author | SHA1 | Date | |
|---|---|---|---|
|
67e22eb793
|
|||
|
aaedddfd2f
|
|||
|
f8a3d0ca45
|
|||
|
6a9c013799
|
|||
|
70846e0d1e
|
|||
|
0710ffce72
|
|||
|
9e840901d1
|
@@ -27,6 +27,12 @@ email:
|
||||
security:
|
||||
insecure_skip_verify:
|
||||
from:
|
||||
auth:
|
||||
oauth2:
|
||||
tenant_id:
|
||||
client_id:
|
||||
client_secret:
|
||||
scope:
|
||||
secrets:
|
||||
turnstile_secret: example
|
||||
client_secret_key: aes_32_byte_string
|
||||
|
||||
@@ -40,14 +40,23 @@ type search struct {
|
||||
ApiKey string `yaml:"api_key"`
|
||||
}
|
||||
|
||||
type _email_oauth2 struct {
|
||||
Tenantid string `yaml:"tenant_id"`
|
||||
ClientId string `yaml:"client_id"`
|
||||
ClientSecret string `yaml:"client_secret"`
|
||||
Scope string `yaml:"scope"`
|
||||
}
|
||||
|
||||
type email struct {
|
||||
Host string `yaml:"host"`
|
||||
Port string `yaml:"port"`
|
||||
Username string `yaml:"username"`
|
||||
Password string `yaml:"password"`
|
||||
Security string `yaml:"security"`
|
||||
InsecureSkipVerify bool `yaml:"insecure_skip_verify"`
|
||||
From string `yaml:"from"`
|
||||
Host string `yaml:"host"`
|
||||
Port string `yaml:"port"`
|
||||
Username string `yaml:"username"`
|
||||
Password string `yaml:"password"`
|
||||
Security string `yaml:"security"`
|
||||
InsecureSkipVerify bool `yaml:"insecure_skip_verify"`
|
||||
From string `yaml:"from"`
|
||||
Auth string `yaml:"auth"`
|
||||
Oauth2 _email_oauth2 `yaml:"oauth2"`
|
||||
}
|
||||
|
||||
type secrets struct {
|
||||
|
||||
40
data/user.go
40
data/user.go
@@ -7,32 +7,28 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// Permission Level
|
||||
// Banned User: 0
|
||||
// Normal User: 10
|
||||
// Admin User: 20
|
||||
// Super User: 30
|
||||
|
||||
type User struct {
|
||||
Id uint `json:"id" gorm:"primarykey;autoincrement"`
|
||||
UUID uuid.UUID `json:"uuid" gorm:"type:uuid;uniqueindex;not null"`
|
||||
UserId uuid.UUID `json:"user_id" gorm:"type:uuid;uniqueindex;not null"`
|
||||
Email string `json:"email" gorm:"type:varchar(255);uniqueindex;not null"`
|
||||
Nickname string `json:"nickname"`
|
||||
Subtitle string `json:"subtitle"`
|
||||
Avatar string `json:"avatar"`
|
||||
Username string `json:"username" gorm:"type:varchar(255);uniqueindex;not null"`
|
||||
Nickname string `json:"nickname" gorm:"type:text"`
|
||||
Subtitle string `json:"subtitle" gorm:"type:text"`
|
||||
Avatar string `json:"avatar" gorm:"type:text"`
|
||||
Bio string `json:"bio" gorm:"type:text"`
|
||||
PermissionLevel uint `json:"permission_level" gorm:"default:10;not null"`
|
||||
AllowPublic bool `json:"allow_public" gorm:"default:false;not null"`
|
||||
}
|
||||
|
||||
type UserSearchDoc struct {
|
||||
UserId string `json:"user_id"`
|
||||
Email string `json:"email"`
|
||||
Type string `json:"type"`
|
||||
Nickname string `json:"nickname"`
|
||||
Subtitle string `json:"subtitle"`
|
||||
Avatar string `json:"avatar"`
|
||||
PermissionLevel uint `json:"permission_level"`
|
||||
UserId string `json:"user_id"`
|
||||
Email string `json:"email"`
|
||||
Username string `json:"username"`
|
||||
Type string `json:"type"`
|
||||
Nickname string `json:"nickname"`
|
||||
Subtitle string `json:"subtitle"`
|
||||
Avatar string `json:"avatar"`
|
||||
}
|
||||
|
||||
func (self *User) GetByEmail(email string) (*User, error) {
|
||||
@@ -132,12 +128,12 @@ func (self *User) FastListUsers(limit, offset int64) (*[]UserSearchDoc, error) {
|
||||
|
||||
func (self *User) UpdateSearchIndex() error {
|
||||
doc := UserSearchDoc{
|
||||
UserId: self.UserId.String(),
|
||||
Email: self.Email,
|
||||
Nickname: self.Nickname,
|
||||
Subtitle: self.Subtitle,
|
||||
Avatar: self.Avatar,
|
||||
PermissionLevel: self.PermissionLevel,
|
||||
UserId: self.UserId.String(),
|
||||
Email: self.Email,
|
||||
Username: self.Username,
|
||||
Nickname: self.Nickname,
|
||||
Subtitle: self.Subtitle,
|
||||
Avatar: self.Avatar,
|
||||
}
|
||||
index := MeiliSearch.Index("user")
|
||||
|
||||
|
||||
1
go.mod
1
go.mod
@@ -17,6 +17,7 @@ require (
|
||||
github.com/sirupsen/logrus v1.9.3
|
||||
github.com/spf13/viper v1.21.0
|
||||
golang.org/x/crypto v0.46.0
|
||||
golang.org/x/oauth2 v0.34.0
|
||||
gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df
|
||||
gorm.io/datatypes v1.2.7
|
||||
gorm.io/driver/postgres v1.6.0
|
||||
|
||||
2
go.sum
2
go.sum
@@ -292,6 +292,8 @@ golang.org/x/net v0.26.0/go.mod h1:5YKkiSynbBIh3p6iOc/vibscux0x38BZDkn8sCUPxHE=
|
||||
golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU=
|
||||
golang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY=
|
||||
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
|
||||
golang.org/x/oauth2 v0.34.0 h1:hqK/t4AKgbqWkdkcAeI8XLmbK+4m4G5YeQRrmiotGlw=
|
||||
golang.org/x/oauth2 v0.34.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA=
|
||||
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
|
||||
@@ -2,6 +2,7 @@ package middleware
|
||||
|
||||
import (
|
||||
"nixcn-cms/pkgs/authtoken"
|
||||
"nixcn-cms/utils"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
@@ -14,12 +15,12 @@ func JWTAuth(required bool) gin.HandlerFunc {
|
||||
authtoken := new(authtoken.Token)
|
||||
uid, err := authtoken.HeaderVerify(auth)
|
||||
if err != nil {
|
||||
c.AbortWithStatusJSON(401, gin.H{"status": err.Error()})
|
||||
utils.HttpAbort(c, 401, "", "unauthorized")
|
||||
return
|
||||
}
|
||||
|
||||
if required == true && uid == "" {
|
||||
c.AbortWithStatusJSON(401, gin.H{"status": "unauthorized"})
|
||||
utils.HttpAbort(c, 401, "", "unauthorized")
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ package middleware
|
||||
|
||||
import (
|
||||
"nixcn-cms/data"
|
||||
"nixcn-cms/utils"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
@@ -14,19 +15,19 @@ func Permission(requiredLevel uint) gin.HandlerFunc {
|
||||
if !ok {
|
||||
userIdOrig, ok := c.Get("user_id")
|
||||
if !ok || userIdOrig.(string) == "" {
|
||||
c.AbortWithStatusJSON(401, gin.H{"status": "missing user id"})
|
||||
utils.HttpAbort(c, 401, "", "missing user id")
|
||||
return
|
||||
}
|
||||
|
||||
userId, err := uuid.Parse(userIdOrig.(string))
|
||||
if err != nil {
|
||||
c.AbortWithStatusJSON(500, gin.H{"status": "error parsing user id"})
|
||||
utils.HttpAbort(c, 500, "", "error parsing user id")
|
||||
return
|
||||
}
|
||||
|
||||
userData, err := new(data.User).GetByUserId(userId)
|
||||
if err != nil {
|
||||
c.AbortWithStatusJSON(404, gin.H{"status": "user not found"})
|
||||
utils.HttpAbort(c, 404, "", "user not found")
|
||||
return
|
||||
}
|
||||
|
||||
@@ -37,7 +38,7 @@ func Permission(requiredLevel uint) gin.HandlerFunc {
|
||||
}
|
||||
|
||||
if permissionLevel < requiredLevel {
|
||||
c.AbortWithStatusJSON(403, gin.H{"status": "permission denied"})
|
||||
utils.HttpAbort(c, 403, "", "permission denied")
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -1,18 +1,67 @@
|
||||
package email
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/smtp"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
"golang.org/x/oauth2"
|
||||
"golang.org/x/oauth2/clientcredentials"
|
||||
gomail "gopkg.in/gomail.v2"
|
||||
)
|
||||
|
||||
type Client struct {
|
||||
// basic smtp
|
||||
dialer *gomail.Dialer
|
||||
from string
|
||||
|
||||
// shared
|
||||
from string
|
||||
host string
|
||||
port int
|
||||
username string
|
||||
|
||||
security string
|
||||
insecure bool
|
||||
|
||||
// auth mode
|
||||
authMode string
|
||||
|
||||
// oauth2
|
||||
oauth *oauthTokenProvider
|
||||
}
|
||||
|
||||
type oauthTokenProvider struct {
|
||||
cfg clientcredentials.Config
|
||||
|
||||
mu sync.Mutex
|
||||
token *oauth2.Token
|
||||
fetchErr error
|
||||
}
|
||||
|
||||
func (p *oauthTokenProvider) getToken(ctx context.Context) (string, error) {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
|
||||
if p.token != nil && p.token.Valid() && time.Until(p.token.Expiry) > 60*time.Second {
|
||||
return p.token.AccessToken, nil
|
||||
}
|
||||
|
||||
tok, err := p.cfg.Token(ctx)
|
||||
if err != nil {
|
||||
p.fetchErr = err
|
||||
return "", err
|
||||
}
|
||||
p.token = tok
|
||||
p.fetchErr = nil
|
||||
return tok.AccessToken, nil
|
||||
}
|
||||
|
||||
func NewSMTPClient() (*Client, error) {
|
||||
@@ -25,46 +74,240 @@ func NewSMTPClient() (*Client, error) {
|
||||
security := strings.ToLower(viper.GetString("email.security"))
|
||||
insecure := viper.GetBool("email.insecure_skip_verify")
|
||||
|
||||
if host == "" || port == 0 || user == "" || pass == "" {
|
||||
authMode := strings.ToLower(viper.GetString("email.auth"))
|
||||
if authMode == "" {
|
||||
authMode = "basic"
|
||||
}
|
||||
|
||||
if host == "" || port == 0 || user == "" {
|
||||
return nil, errors.New("SMTP config not set")
|
||||
}
|
||||
|
||||
dialer := gomail.NewDialer(host, port, user, pass)
|
||||
|
||||
dialer.TLSConfig = &tls.Config{
|
||||
ServerName: host,
|
||||
InsecureSkipVerify: insecure,
|
||||
c := &Client{
|
||||
from: from,
|
||||
host: host,
|
||||
port: port,
|
||||
username: user,
|
||||
security: security,
|
||||
insecure: insecure,
|
||||
authMode: authMode,
|
||||
}
|
||||
|
||||
switch security {
|
||||
case "ssl":
|
||||
dialer.SSL = true
|
||||
case "starttls":
|
||||
dialer.SSL = false
|
||||
case "plain", "":
|
||||
dialer.SSL = false
|
||||
dialer.TLSConfig = nil
|
||||
switch authMode {
|
||||
case "basic":
|
||||
if pass == "" {
|
||||
return nil, errors.New("SMTP basic auth requires email.password")
|
||||
}
|
||||
|
||||
dialer := gomail.NewDialer(host, port, user, pass)
|
||||
dialer.TLSConfig = &tls.Config{
|
||||
ServerName: host,
|
||||
InsecureSkipVerify: insecure,
|
||||
}
|
||||
|
||||
switch security {
|
||||
case "ssl":
|
||||
dialer.SSL = true
|
||||
case "starttls":
|
||||
dialer.SSL = false
|
||||
case "plain", "":
|
||||
dialer.SSL = false
|
||||
dialer.TLSConfig = nil
|
||||
default:
|
||||
return nil, errors.New("unknown smtp security mode: " + security)
|
||||
}
|
||||
|
||||
c.dialer = dialer
|
||||
return c, nil
|
||||
|
||||
case "oauth2":
|
||||
if security == "" {
|
||||
security = "starttls"
|
||||
c.security = "starttls"
|
||||
}
|
||||
if security == "plain" {
|
||||
return nil, errors.New("oauth2 requires TLS (starttls or ssl); plain is not allowed")
|
||||
}
|
||||
|
||||
tenantID := viper.GetString("email.oauth2.tenant_id")
|
||||
clientID := viper.GetString("email.oauth2.client_id")
|
||||
clientSecret := viper.GetString("email.oauth2.client_secret")
|
||||
scope := viper.GetString("email.oauth2.scope")
|
||||
if scope == "" {
|
||||
// Microsoft Learn: client credentials for SMTP uses https://outlook.office365.com/.default :contentReference[oaicite:3]{index=3}
|
||||
scope = "https://outlook.office365.com/.default"
|
||||
}
|
||||
|
||||
if tenantID == "" || clientID == "" || clientSecret == "" {
|
||||
return nil, errors.New("oauth2 requires email.oauth2.tenant_id/client_id/client_secret")
|
||||
}
|
||||
|
||||
c.oauth = &oauthTokenProvider{
|
||||
cfg: clientcredentials.Config{
|
||||
ClientID: clientID,
|
||||
ClientSecret: clientSecret,
|
||||
TokenURL: fmt.Sprintf("https://login.microsoftonline.com/%s/oauth2/v2.0/token", tenantID),
|
||||
Scopes: []string{scope},
|
||||
},
|
||||
}
|
||||
return c, nil
|
||||
|
||||
default:
|
||||
return nil, errors.New("unknown smtp security mode: " + security)
|
||||
return nil, errors.New("unknown email.auth: " + authMode)
|
||||
}
|
||||
|
||||
return &Client{
|
||||
dialer: dialer,
|
||||
from: from,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *Client) Send(to, subject, html string) (string, error) {
|
||||
m := gomail.NewMessage()
|
||||
|
||||
m.SetHeader("From", c.from)
|
||||
m.SetHeader("To", to)
|
||||
m.SetHeader("Subject", subject)
|
||||
m.SetBody("text/html", html)
|
||||
|
||||
if err := c.dialer.DialAndSend(m); err != nil {
|
||||
return "", err
|
||||
switch c.authMode {
|
||||
case "basic":
|
||||
if c.dialer == nil {
|
||||
return "", errors.New("basic dialer not initialized")
|
||||
}
|
||||
if err := c.dialer.DialAndSend(m); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return time.Now().Format(time.RFC3339Nano), nil
|
||||
|
||||
case "oauth2":
|
||||
if err := c.sendWithXOAUTH2(m, to); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return time.Now().Format(time.RFC3339Nano), nil
|
||||
|
||||
default:
|
||||
return "", errors.New("unsupported auth mode: " + c.authMode)
|
||||
}
|
||||
}
|
||||
|
||||
// XOAUTH2 auth for net/smtp
|
||||
type xoauth2Auth struct {
|
||||
username string
|
||||
token string
|
||||
}
|
||||
|
||||
func (a *xoauth2Auth) Start(server *smtp.ServerInfo) (string, []byte, error) {
|
||||
if !server.TLS {
|
||||
return "", nil, errors.New("refusing to authenticate over insecure connection")
|
||||
}
|
||||
|
||||
return time.Now().Format(time.RFC3339Nano), nil
|
||||
// Microsoft Learn XOAUTH2 Format: user=<user>\x01auth=Bearer <token>\x01\x01 :contentReference[oaicite:4]{index=4}
|
||||
resp := fmt.Sprintf("user=%s\x01auth=Bearer %s\x01\x01", a.username, a.token)
|
||||
return "XOAUTH2", []byte(resp), nil
|
||||
}
|
||||
|
||||
func (a *xoauth2Auth) Next(fromServer []byte, more bool) ([]byte, error) {
|
||||
if more {
|
||||
return nil, errors.New("unexpected server challenge during XOAUTH2 auth")
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (c *Client) sendWithXOAUTH2(m *gomail.Message, rcpt string) error {
|
||||
if c.oauth == nil {
|
||||
return errors.New("oauth2 provider not initialized")
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
|
||||
token, err := c.oauth.getToken(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("oauth2 token error: %w", err)
|
||||
}
|
||||
|
||||
// write gomail.Message to RFC822
|
||||
var buf bytes.Buffer
|
||||
if _, err := m.WriteTo(&buf); err != nil {
|
||||
return err
|
||||
}
|
||||
msg := buf.Bytes()
|
||||
|
||||
addr := fmt.Sprintf("%s:%d", c.host, c.port)
|
||||
tlsCfg := &tls.Config{
|
||||
ServerName: c.host,
|
||||
InsecureSkipVerify: c.insecure,
|
||||
}
|
||||
|
||||
var (
|
||||
conn net.Conn
|
||||
cl *smtp.Client
|
||||
)
|
||||
|
||||
switch c.security {
|
||||
case "ssl":
|
||||
conn, err = tls.Dial("tcp", addr, tlsCfg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cl, err = smtp.NewClient(conn, c.host)
|
||||
if err != nil {
|
||||
_ = conn.Close()
|
||||
return err
|
||||
}
|
||||
|
||||
case "starttls", "":
|
||||
conn, err = net.Dial("tcp", addr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cl, err = smtp.NewClient(conn, c.host)
|
||||
if err != nil {
|
||||
_ = conn.Close()
|
||||
return err
|
||||
}
|
||||
|
||||
// Upgrade with STARTTLS
|
||||
if ok, _ := cl.Extension("STARTTLS"); ok {
|
||||
if err := cl.StartTLS(tlsCfg); err != nil {
|
||||
_ = cl.Close()
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
_ = cl.Close()
|
||||
return errors.New("server does not support STARTTLS")
|
||||
}
|
||||
|
||||
default:
|
||||
return errors.New("unknown smtp security mode: " + c.security)
|
||||
}
|
||||
|
||||
defer func() { _ = cl.Quit() }()
|
||||
|
||||
// AUTH XOAUTH2
|
||||
if err := cl.Auth(&xoauth2Auth{username: c.username, token: token}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// MAIL FROM / RCPT TO / DATA
|
||||
if err := cl.Mail(extractAddress(c.from)); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := cl.Rcpt(rcpt); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
w, err := cl.Data()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := w.Write(msg); err != nil {
|
||||
_ = w.Close()
|
||||
return err
|
||||
}
|
||||
return w.Close()
|
||||
}
|
||||
|
||||
func extractAddress(from string) string {
|
||||
if i := strings.LastIndex(from, "<"); i >= 0 {
|
||||
if j := strings.LastIndex(from, ">"); j > i {
|
||||
return strings.TrimSpace(from[i+1 : j])
|
||||
}
|
||||
}
|
||||
return strings.TrimSpace(from)
|
||||
}
|
||||
|
||||
@@ -9,6 +9,6 @@ import (
|
||||
func Handler(r *gin.RouterGroup) {
|
||||
r.GET("/redirect", Redirect, middleware.JWTAuth(false))
|
||||
r.POST("/magic", Magic)
|
||||
r.POST("/refresh", Refresh)
|
||||
r.POST("/token", Token)
|
||||
r.POST("/refresh", Refresh)
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"nixcn-cms/pkgs/authcode"
|
||||
"nixcn-cms/pkgs/email"
|
||||
"nixcn-cms/pkgs/turnstile"
|
||||
"nixcn-cms/utils"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/spf13/viper"
|
||||
@@ -22,26 +23,28 @@ func Magic(c *gin.Context) {
|
||||
// Parse request
|
||||
var req MagicRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(400, gin.H{"error": "invalid request"})
|
||||
utils.HttpResponse(c, 400, "", "invalid request")
|
||||
return
|
||||
}
|
||||
|
||||
// Cloudflare turnstile
|
||||
ok, err := turnstile.VerifyTurnstile(req.TurnstileToken, c.ClientIP())
|
||||
if err != nil || !ok {
|
||||
c.JSON(403, gin.H{"error": "turnstile failed"})
|
||||
utils.HttpResponse(c, 403, "", "turnstile failed")
|
||||
return
|
||||
}
|
||||
|
||||
code, err := authcode.NewAuthCode(req.ClientId, req.Email)
|
||||
if err != nil {
|
||||
c.JSON(500, gin.H{"status": "code gen failed"})
|
||||
utils.HttpResponse(c, 500, "", "code gen failed")
|
||||
return
|
||||
}
|
||||
|
||||
externalUrl := viper.GetString("server.external_url")
|
||||
url, err := url.Parse(externalUrl)
|
||||
if err != nil {
|
||||
c.JSON(500, gin.H{"status": "invalid external url"})
|
||||
utils.HttpResponse(c, 500, "", "invalid external url")
|
||||
return
|
||||
}
|
||||
|
||||
url.Path = "/api/v1/auth/redirect"
|
||||
@@ -54,13 +57,17 @@ func Magic(c *gin.Context) {
|
||||
|
||||
debugMode := viper.GetBool("server.debug_mode")
|
||||
if debugMode {
|
||||
c.JSON(200, gin.H{"status": "magiclink sent", "uri": url.String()})
|
||||
uriData := struct {
|
||||
Uri string `json:"uri"`
|
||||
}{url.String()}
|
||||
|
||||
utils.HttpResponse(c, 200, "", "magiclink sent", uriData)
|
||||
return
|
||||
} else {
|
||||
// Send email using resend
|
||||
emailClient, err := email.NewSMTPClient()
|
||||
if err != nil {
|
||||
c.JSON(500, gin.H{"status": "invalid email config"})
|
||||
utils.HttpResponse(c, 500, "", "invalid email config")
|
||||
return
|
||||
}
|
||||
emailClient.Send(
|
||||
@@ -70,5 +77,5 @@ func Magic(c *gin.Context) {
|
||||
)
|
||||
}
|
||||
|
||||
c.JSON(200, gin.H{"status": "magic link sent"})
|
||||
utils.HttpResponse(c, 200, "", "magic link sent")
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"net/url"
|
||||
"nixcn-cms/data"
|
||||
"nixcn-cms/pkgs/authcode"
|
||||
"nixcn-cms/utils"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
@@ -13,19 +14,19 @@ import (
|
||||
func Redirect(c *gin.Context) {
|
||||
clientId := c.Query("client_id")
|
||||
if clientId == "" {
|
||||
c.JSON(400, gin.H{"status": "invalid request"})
|
||||
utils.HttpResponse(c, 400, "", "invalid request")
|
||||
return
|
||||
}
|
||||
|
||||
redirectUri := c.Query("redirect_uri")
|
||||
if redirectUri == "" {
|
||||
c.JSON(400, gin.H{"status": "invalid request"})
|
||||
utils.HttpResponse(c, 400, "", "invalid request")
|
||||
return
|
||||
}
|
||||
|
||||
state := c.Query("state")
|
||||
if state == "" {
|
||||
c.JSON(400, gin.H{"status": "invalid request"})
|
||||
utils.HttpResponse(c, 400, "", "invalid request")
|
||||
return
|
||||
}
|
||||
|
||||
@@ -33,32 +34,32 @@ func Redirect(c *gin.Context) {
|
||||
if code == "" {
|
||||
userIdOrig, ok := c.Get("user_id")
|
||||
if !ok || userIdOrig == "" {
|
||||
c.JSON(401, gin.H{"status": "unauthorized"})
|
||||
utils.HttpResponse(c, 401, "", "unauthorized")
|
||||
return
|
||||
}
|
||||
|
||||
userId, err := uuid.Parse(userIdOrig.(string))
|
||||
if err != nil {
|
||||
c.JSON(500, gin.H{"status": "failed to parse uuid"})
|
||||
utils.HttpResponse(c, 500, "", "failed to parse uuid")
|
||||
return
|
||||
}
|
||||
|
||||
userData := new(data.User)
|
||||
user, err := userData.GetByUserId(userId)
|
||||
if err != nil {
|
||||
c.JSON(500, gin.H{"status": "failed to get user id"})
|
||||
utils.HttpResponse(c, 500, "", "failed to get user id")
|
||||
return
|
||||
}
|
||||
|
||||
code, err := authcode.NewAuthCode(clientId, user.Email)
|
||||
if err != nil {
|
||||
c.JSON(500, gin.H{"status": "code gen failed"})
|
||||
utils.HttpResponse(c, 500, "", "code gen failed")
|
||||
return
|
||||
}
|
||||
|
||||
url, err := url.Parse(redirectUri)
|
||||
if err != nil {
|
||||
c.JSON(400, gin.H{"status": "invalid redirect uri"})
|
||||
utils.HttpResponse(c, 400, "", "invalid redirect uri")
|
||||
return
|
||||
}
|
||||
query := url.Query()
|
||||
@@ -71,7 +72,7 @@ func Redirect(c *gin.Context) {
|
||||
// Verify email token
|
||||
authCode, ok := authcode.VerifyAuthCode(code)
|
||||
if !ok {
|
||||
c.JSON(403, gin.H{"status": "invalid or expired token"})
|
||||
utils.HttpResponse(c, 403, "", "invalid or expired token")
|
||||
return
|
||||
}
|
||||
|
||||
@@ -85,13 +86,14 @@ func Redirect(c *gin.Context) {
|
||||
user.UUID = uuid.New()
|
||||
user.UserId = uuid.New()
|
||||
user.Email = authCode.Email
|
||||
user.Username = user.UserId.String()
|
||||
user.PermissionLevel = 10
|
||||
if err := user.Create(); err != nil {
|
||||
c.JSON(500, gin.H{"status": "internal server error"})
|
||||
utils.HttpResponse(c, 500, "", "internal server error")
|
||||
return
|
||||
}
|
||||
} else {
|
||||
c.JSON(500, gin.H{"status": "internal server error"})
|
||||
utils.HttpResponse(c, 500, "", "internal server error")
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -99,25 +101,25 @@ func Redirect(c *gin.Context) {
|
||||
clientData := new(data.Client)
|
||||
client, err := clientData.GetClientByClientId(clientId)
|
||||
if err != nil {
|
||||
c.JSON(400, gin.H{"status": "client not found"})
|
||||
utils.HttpResponse(c, 400, "", "client not found")
|
||||
return
|
||||
}
|
||||
|
||||
err = client.ValidateRedirectURI(redirectUri)
|
||||
if err != nil {
|
||||
c.JSON(400, gin.H{"status": "redirect uri not match"})
|
||||
utils.HttpResponse(c, 400, "", "redirect uri not match")
|
||||
return
|
||||
}
|
||||
|
||||
newCode, err := authcode.NewAuthCode(clientId, authCode.Email)
|
||||
if err != nil {
|
||||
c.JSON(500, gin.H{"status": "internal server error"})
|
||||
utils.HttpResponse(c, 500, "", "internal server error")
|
||||
return
|
||||
}
|
||||
|
||||
url, err := url.Parse(redirectUri)
|
||||
if err != nil {
|
||||
c.JSON(400, gin.H{"status": "invalid redirect uri"})
|
||||
utils.HttpResponse(c, 400, "", "invalid redirect uri")
|
||||
return
|
||||
}
|
||||
query := url.Query()
|
||||
|
||||
@@ -2,6 +2,7 @@ package auth
|
||||
|
||||
import (
|
||||
"nixcn-cms/pkgs/authtoken"
|
||||
"nixcn-cms/utils"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/spf13/viper"
|
||||
@@ -13,7 +14,7 @@ func Refresh(c *gin.Context) {
|
||||
}
|
||||
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(400, gin.H{"status": "invalid request"})
|
||||
utils.HttpResponse(c, 400, "", "invalid request")
|
||||
return
|
||||
}
|
||||
|
||||
@@ -21,20 +22,22 @@ func Refresh(c *gin.Context) {
|
||||
Application: viper.GetString("server.application"),
|
||||
}
|
||||
|
||||
access, err := JwtTool.RefreshAccessToken(req.RefreshToken)
|
||||
accessToken, err := JwtTool.RefreshAccessToken(req.RefreshToken)
|
||||
if err != nil {
|
||||
c.JSON(401, gin.H{"status": "invalid refresh token"})
|
||||
utils.HttpResponse(c, 401, "", "invalid refresh token")
|
||||
return
|
||||
}
|
||||
|
||||
refresh, err := JwtTool.RenewRefreshToken(req.RefreshToken)
|
||||
refreshToken, err := JwtTool.RenewRefreshToken(req.RefreshToken)
|
||||
if err != nil {
|
||||
c.JSON(500, gin.H{"statis": "error renew refresh token"})
|
||||
utils.HttpResponse(c, 500, "", "error renew refresh token")
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(200, gin.H{
|
||||
"access_token": access,
|
||||
"refresh_token": refresh,
|
||||
})
|
||||
tokenResp := struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
RefreshToken string `json:"refresh_token"`
|
||||
}{accessToken, refreshToken}
|
||||
|
||||
utils.HttpResponse(c, 200, "", "success", tokenResp)
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"nixcn-cms/data"
|
||||
"nixcn-cms/pkgs/authcode"
|
||||
"nixcn-cms/pkgs/authtoken"
|
||||
"nixcn-cms/utils"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/spf13/viper"
|
||||
@@ -18,20 +19,20 @@ func Token(c *gin.Context) {
|
||||
|
||||
err := c.ShouldBindJSON(&req)
|
||||
if err != nil {
|
||||
c.JSON(400, gin.H{"status": "invalid request"})
|
||||
utils.HttpResponse(c, 400, "", "invalid request")
|
||||
return
|
||||
}
|
||||
|
||||
authCode, ok := authcode.VerifyAuthCode(req.Code)
|
||||
if !ok {
|
||||
c.JSON(403, gin.H{"status": "invalid or expired token"})
|
||||
utils.HttpResponse(c, 403, "", "invalid or expired token")
|
||||
return
|
||||
}
|
||||
|
||||
userData := new(data.User)
|
||||
user, err := userData.GetByEmail(authCode.Email)
|
||||
if err != nil {
|
||||
c.JSON(500, gin.H{"status": "internal server error"})
|
||||
utils.HttpResponse(c, 500, "", "internal server error")
|
||||
return
|
||||
}
|
||||
|
||||
@@ -41,12 +42,14 @@ func Token(c *gin.Context) {
|
||||
}
|
||||
accessToken, refreshToken, err := JwtTool.IssueTokens(authCode.ClientId, user.UserId)
|
||||
if err != nil {
|
||||
c.JSON(500, gin.H{"status": "error generating tokens"})
|
||||
utils.HttpResponse(c, 500, "", "error generating tokens")
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(200, gin.H{
|
||||
"access_token": accessToken,
|
||||
"refresh_token": refreshToken,
|
||||
})
|
||||
tokenResp := struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
RefreshToken string `json:"refresh_token"`
|
||||
}{accessToken, refreshToken}
|
||||
|
||||
utils.HttpResponse(c, 200, "", "success", tokenResp)
|
||||
}
|
||||
|
||||
108
service/event/checkin.go
Normal file
108
service/event/checkin.go
Normal file
@@ -0,0 +1,108 @@
|
||||
package event
|
||||
|
||||
import (
|
||||
"nixcn-cms/data"
|
||||
"nixcn-cms/utils"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func Checkin(c *gin.Context) {
|
||||
data := new(data.Attendance)
|
||||
userIdOrig, ok := c.Get("user_id")
|
||||
if !ok {
|
||||
utils.HttpResponse(c, 403, "", "userid error")
|
||||
return
|
||||
}
|
||||
userId, err := uuid.Parse(userIdOrig.(string))
|
||||
if err != nil {
|
||||
utils.HttpResponse(c, 500, "", "failed to parse uuid")
|
||||
}
|
||||
|
||||
// Get event id from query
|
||||
eventIdOrig, ok := c.GetQuery("event_id")
|
||||
if !ok {
|
||||
utils.HttpResponse(c, 400, "", "undefinded event id")
|
||||
return
|
||||
}
|
||||
|
||||
// Parse event id to uuid
|
||||
eventId, err := uuid.Parse(eventIdOrig)
|
||||
if err != nil {
|
||||
utils.HttpResponse(c, 500, "", "error parsing string to uuid")
|
||||
return
|
||||
}
|
||||
data.UserId = userId
|
||||
code, err := data.GenCheckinCode(eventId)
|
||||
if err != nil {
|
||||
utils.HttpResponse(c, 500, "", "error generating code")
|
||||
return
|
||||
}
|
||||
|
||||
checkinCodeResp := struct {
|
||||
CheckinCode *string `json:"checkin_code"`
|
||||
}{code}
|
||||
utils.HttpResponse(c, 200, "", "success", checkinCodeResp)
|
||||
}
|
||||
|
||||
func CheckinSubmit(c *gin.Context) {
|
||||
var req struct {
|
||||
ChekinCode string `json:"checkin_code"`
|
||||
}
|
||||
c.ShouldBindJSON(&req)
|
||||
|
||||
attendanceData := new(data.Attendance)
|
||||
err := attendanceData.VerifyCheckinCode(req.ChekinCode)
|
||||
if err != nil {
|
||||
utils.HttpResponse(c, 400, "", "error verify checkin code")
|
||||
return
|
||||
}
|
||||
|
||||
utils.HttpResponse(c, 200, "", "success")
|
||||
}
|
||||
|
||||
func CheckinQuery(c *gin.Context) {
|
||||
userIdOrig, ok := c.Get("user_id")
|
||||
if !ok {
|
||||
utils.HttpResponse(c, 400, "", "userid error")
|
||||
return
|
||||
}
|
||||
userId, err := uuid.Parse(userIdOrig.(string))
|
||||
if err != nil {
|
||||
utils.HttpResponse(c, 500, "", "failed to parse uuid")
|
||||
return
|
||||
}
|
||||
|
||||
eventIdOrig, ok := c.GetQuery("event_id")
|
||||
if !ok {
|
||||
utils.HttpResponse(c, 400, "", "could not found event_id")
|
||||
return
|
||||
}
|
||||
eventId, err := uuid.Parse(eventIdOrig)
|
||||
if err != nil {
|
||||
utils.HttpResponse(c, 400, "", "event_id is not valid")
|
||||
return
|
||||
}
|
||||
|
||||
attendanceData := new(data.Attendance)
|
||||
attendance, err := attendanceData.GetAttendance(userId, eventId)
|
||||
|
||||
if err != nil {
|
||||
utils.HttpResponse(c, 500, "", "database error")
|
||||
return
|
||||
} else if attendance == nil {
|
||||
utils.HttpResponse(c, 404, "", "event checkin record not found")
|
||||
return
|
||||
} else if attendance.CheckinAt.IsZero() {
|
||||
utils.HttpResponse(c, 200, "", "success", gin.H{"checkin_at": nil})
|
||||
return
|
||||
}
|
||||
|
||||
checkInAtResp := struct {
|
||||
CheckinAt time.Time `json:"checkin_at"`
|
||||
}{attendance.CheckinAt}
|
||||
|
||||
utils.HttpResponse(c, 200, "", "success", checkInAtResp)
|
||||
}
|
||||
@@ -7,6 +7,9 @@ import (
|
||||
)
|
||||
|
||||
func Handler(r *gin.RouterGroup) {
|
||||
r.Use(middleware.JWTAuth(true))
|
||||
r.Use(middleware.JWTAuth(true), middleware.Permission(10))
|
||||
r.GET("/info", Info)
|
||||
r.GET("/checkin", Checkin)
|
||||
r.GET("/checkin/query", CheckinQuery)
|
||||
r.POST("/checkin/submit", CheckinSubmit, middleware.Permission(20))
|
||||
}
|
||||
|
||||
@@ -2,6 +2,8 @@ package event
|
||||
|
||||
import (
|
||||
"nixcn-cms/data"
|
||||
"nixcn-cms/utils"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
@@ -11,26 +13,28 @@ func Info(c *gin.Context) {
|
||||
eventData := new(data.Event)
|
||||
eventIdOrig, ok := c.GetQuery("event_id")
|
||||
if !ok {
|
||||
c.JSON(400, gin.H{"status": "undefinded event id"})
|
||||
utils.HttpResponse(c, 400, "", "undefinded event id")
|
||||
return
|
||||
}
|
||||
|
||||
// Parse event id
|
||||
eventId, err := uuid.Parse(eventIdOrig)
|
||||
if err != nil {
|
||||
c.JSON(500, gin.H{"status": "error parsing string to uuid"})
|
||||
utils.HttpResponse(c, 500, "", "error parsing string to uuid")
|
||||
return
|
||||
}
|
||||
|
||||
event, err := eventData.GetEventById(eventId)
|
||||
if err != nil {
|
||||
c.JSON(404, gin.H{"status": "event id not found"})
|
||||
utils.HttpResponse(c, 404, "", "event id not found")
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(200, gin.H{
|
||||
"name": event.Name,
|
||||
"start_time": event.StartTime,
|
||||
"end_time": event.EndTime,
|
||||
})
|
||||
eventInfoResp := struct {
|
||||
Name string `json:"name"`
|
||||
StartTime time.Time `json:"start_time"`
|
||||
EndTime time.Time `json:"end_time"`
|
||||
}{event.Name, event.StartTime, event.EndTime}
|
||||
|
||||
utils.HttpResponse(c, 200, "", "success", eventInfoResp)
|
||||
}
|
||||
|
||||
@@ -1,59 +0,0 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"nixcn-cms/data"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func Checkin(c *gin.Context) {
|
||||
data := new(data.Attendance)
|
||||
userIdOrig, ok := c.Get("user_id")
|
||||
if !ok {
|
||||
c.JSON(403, gin.H{"status": "userid error"})
|
||||
return
|
||||
}
|
||||
userId, err := uuid.Parse(userIdOrig.(string))
|
||||
if err != nil {
|
||||
c.JSON(500, gin.H{"status": "failed to parse uuid"})
|
||||
}
|
||||
|
||||
// Get event id from query
|
||||
eventIdOrig, ok := c.GetQuery("event_id")
|
||||
if !ok {
|
||||
c.JSON(400, gin.H{"status": "undefinded event id"})
|
||||
return
|
||||
}
|
||||
|
||||
// Parse event id to uuid
|
||||
eventId, err := uuid.Parse(eventIdOrig)
|
||||
if err != nil {
|
||||
c.JSON(500, gin.H{"status": "error parsing string to uuid"})
|
||||
return
|
||||
}
|
||||
data.UserId = userId
|
||||
code, err := data.GenCheckinCode(eventId)
|
||||
if err != nil {
|
||||
c.JSON(500, gin.H{"status": "error generating code"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(200, gin.H{"checkin_code": code})
|
||||
}
|
||||
|
||||
func CheckinSubmit(c *gin.Context) {
|
||||
var req struct {
|
||||
ChekinCode string `json:"checkin_code"`
|
||||
}
|
||||
c.ShouldBindJSON(&req)
|
||||
|
||||
attendanceData := new(data.Attendance)
|
||||
err := attendanceData.VerifyCheckinCode(req.ChekinCode)
|
||||
if err != nil {
|
||||
c.JSON(400, gin.H{"status": "error verify checkin code"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(200, gin.H{"status": "success"})
|
||||
}
|
||||
7
service/user/create.go
Normal file
7
service/user/create.go
Normal file
@@ -0,0 +1,7 @@
|
||||
package user
|
||||
|
||||
import "github.com/gin-gonic/gin"
|
||||
|
||||
func Create(c *gin.Context) {
|
||||
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package user
|
||||
|
||||
import (
|
||||
"nixcn-cms/data"
|
||||
"nixcn-cms/utils"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
@@ -10,26 +11,29 @@ import (
|
||||
func Full(c *gin.Context) {
|
||||
userIdOrig, ok := c.Get("user_id")
|
||||
if !ok {
|
||||
c.JSON(403, gin.H{"status": "userid error"})
|
||||
utils.HttpResponse(c, 403, "", "userid error")
|
||||
return
|
||||
}
|
||||
userId, err := uuid.Parse(userIdOrig.(string))
|
||||
if err != nil {
|
||||
c.JSON(500, gin.H{"status": "failed to parse uuid"})
|
||||
utils.HttpResponse(c, 500, "", "failed to parse uuid")
|
||||
return
|
||||
}
|
||||
|
||||
userData, err := new(data.User).GetByUserId(userId)
|
||||
if err != nil {
|
||||
c.JSON(404, gin.H{"status": "user not found"})
|
||||
utils.HttpResponse(c, 404, "", "user not found")
|
||||
return
|
||||
}
|
||||
|
||||
data, err := userData.GetFullTable()
|
||||
users, err := userData.GetFullTable()
|
||||
if err != nil {
|
||||
c.JSON(500, gin.H{"status": "database error"})
|
||||
utils.HttpResponse(c, 500, "", "database error")
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(200, gin.H{"user_table": data})
|
||||
userFullResp := struct {
|
||||
UserTable *[]data.User `json:"user_table"`
|
||||
}{users}
|
||||
utils.HttpResponse(c, 200, "", "success", userFullResp)
|
||||
}
|
||||
|
||||
@@ -7,12 +7,10 @@ import (
|
||||
)
|
||||
|
||||
func Handler(r *gin.RouterGroup) {
|
||||
r.Use(middleware.JWTAuth(true), middleware.Permission(10))
|
||||
r.Use(middleware.JWTAuth(true), middleware.Permission(5))
|
||||
r.GET("/info", Info)
|
||||
r.GET("/checkin", Checkin)
|
||||
r.POST("/checkin/submit", CheckinSubmit, middleware.Permission(20))
|
||||
r.PATCH("/update", Update)
|
||||
r.GET("/list", List)
|
||||
r.GET("/query", Query)
|
||||
r.POST("/full", Full, middleware.Permission(50))
|
||||
r.GET("/list", List, middleware.Permission(20))
|
||||
r.POST("/full", Full, middleware.Permission(40))
|
||||
r.POST("/create", Create, middleware.Permission(50))
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package user
|
||||
|
||||
import (
|
||||
"nixcn-cms/data"
|
||||
"nixcn-cms/utils"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
@@ -11,29 +12,32 @@ func Info(c *gin.Context) {
|
||||
userData := new(data.User)
|
||||
userIdOrig, ok := c.Get("user_id")
|
||||
if !ok {
|
||||
c.JSON(403, gin.H{"status": "userid error"})
|
||||
utils.HttpResponse(c, 403, "", "userid error")
|
||||
return
|
||||
}
|
||||
userId, err := uuid.Parse(userIdOrig.(string))
|
||||
if err != nil {
|
||||
c.JSON(500, gin.H{"status": "failed to parse uuid"})
|
||||
utils.HttpResponse(c, 500, "", "failed to parse uuid")
|
||||
return
|
||||
}
|
||||
|
||||
// Get user from database
|
||||
user, err := userData.GetByUserId(userId)
|
||||
if err != nil {
|
||||
c.JSON(404, gin.H{"status": "user not found"})
|
||||
utils.HttpResponse(c, 404, "", "user not found")
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(200, gin.H{
|
||||
"user_id": user.UserId,
|
||||
"email": user.Email,
|
||||
"nickname": user.Nickname,
|
||||
"subtitle": user.Subtitle,
|
||||
"avatar": user.Avatar,
|
||||
"bio": user.Bio,
|
||||
"permission_level": user.PermissionLevel,
|
||||
})
|
||||
userInfoResp := struct {
|
||||
UserId uuid.UUID `json:"user_id"`
|
||||
Email string `json:"email"`
|
||||
Username string `json:"username"`
|
||||
Nickname string `json:"nickname"`
|
||||
Subtitle string `json:"subtitle"`
|
||||
Avatar string `json:"avatar"`
|
||||
Bio string `json:"bio"`
|
||||
PermissionLevel uint `json:"permission_level"`
|
||||
}{user.UserId, user.Email, user.Username, user.Nickname, user.Subtitle, user.Avatar, user.Bio, user.PermissionLevel}
|
||||
|
||||
utils.HttpResponse(c, 200, "", "success", userInfoResp)
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package user
|
||||
|
||||
import (
|
||||
"nixcn-cms/data"
|
||||
"nixcn-cms/utils"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -15,26 +16,30 @@ func List(c *gin.Context) {
|
||||
}
|
||||
offset, ok := c.GetQuery("offset")
|
||||
if !ok {
|
||||
c.JSON(400, gin.H{"status": "offset not found"})
|
||||
utils.HttpResponse(c, 400, "", "offset not found")
|
||||
return
|
||||
}
|
||||
|
||||
// Parse string to int64
|
||||
limitNum, err := strconv.ParseInt(limit, 10, 64)
|
||||
if err != nil {
|
||||
c.JSON(400, gin.H{"status": "parse string to int error"})
|
||||
utils.HttpResponse(c, 400, "", "parse string to int error")
|
||||
return
|
||||
}
|
||||
offsetNum, err := strconv.ParseInt(offset, 10, 64)
|
||||
if err != nil {
|
||||
c.JSON(400, gin.H{"status": "parse string to int error"})
|
||||
utils.HttpResponse(c, 400, "", "parse string to int error")
|
||||
return
|
||||
}
|
||||
|
||||
// Get user list from search engine
|
||||
list, err := new(data.User).FastListUsers(limitNum, offsetNum)
|
||||
if err != nil {
|
||||
c.JSON(500, gin.H{"status": "failed list users from meilisearch"})
|
||||
utils.HttpResponse(c, 500, "", "failed list users from meilisearch")
|
||||
}
|
||||
c.JSON(200, list)
|
||||
|
||||
userListResp := struct {
|
||||
List *[]data.UserSearchDoc `json:"list"`
|
||||
}{list}
|
||||
utils.HttpResponse(c, 200, "", "success", userListResp)
|
||||
}
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"nixcn-cms/data"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func Query(c *gin.Context) {
|
||||
userIdOrig, ok := c.Get("user_id")
|
||||
if !ok {
|
||||
c.JSON(403, gin.H{"status": "userid error"})
|
||||
return
|
||||
}
|
||||
userId, err := uuid.Parse(userIdOrig.(string))
|
||||
if err != nil {
|
||||
c.JSON(500, gin.H{
|
||||
"status": "failed to parse uuid",
|
||||
})
|
||||
}
|
||||
|
||||
eventIdOrig, ok := c.GetQuery("event_id")
|
||||
if !ok {
|
||||
c.JSON(400, gin.H{"status": "could not found event_id"})
|
||||
return
|
||||
}
|
||||
eventId, err := uuid.Parse(eventIdOrig)
|
||||
if err != nil {
|
||||
c.JSON(400, gin.H{"status": "event_id is not valid"})
|
||||
return
|
||||
}
|
||||
|
||||
attendanceData := new(data.Attendance)
|
||||
attendance, err := attendanceData.GetAttendance(userId, eventId)
|
||||
if err != nil {
|
||||
c.JSON(500, gin.H{"status": "database error"})
|
||||
return
|
||||
} else if attendance == nil {
|
||||
c.JSON(404, gin.H{"status": "event checkin record not found"})
|
||||
return
|
||||
} else if attendance.CheckinAt.IsZero() {
|
||||
c.JSON(200, gin.H{"checkin_at": nil})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(200, gin.H{"checkin_at": attendance.CheckinAt})
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package user
|
||||
import (
|
||||
"nixcn-cms/data"
|
||||
"nixcn-cms/internal/cryptography"
|
||||
"nixcn-cms/utils"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
@@ -12,12 +13,12 @@ func Update(c *gin.Context) {
|
||||
// New user model
|
||||
userIdOrig, ok := c.Get("user_id")
|
||||
if !ok {
|
||||
c.JSON(403, gin.H{"status": "userid error"})
|
||||
utils.HttpResponse(c, 403, "", "userid error")
|
||||
return
|
||||
}
|
||||
userId, err := uuid.Parse(userIdOrig.(string))
|
||||
if err != nil {
|
||||
c.JSON(500, gin.H{"status": "failed to parse uuid"})
|
||||
utils.HttpResponse(c, 500, "", "failed to parse uuid")
|
||||
return
|
||||
}
|
||||
|
||||
@@ -27,18 +28,29 @@ func Update(c *gin.Context) {
|
||||
// Get user info
|
||||
userData, err := new(data.User).GetByUserId(userId)
|
||||
if err != nil {
|
||||
c.JSON(500, gin.H{"status": "failed to find user"})
|
||||
utils.HttpResponse(c, 500, "", "failed to find user")
|
||||
return
|
||||
}
|
||||
|
||||
userData.Avatar = ReqInfo.Avatar
|
||||
if len(ReqInfo.Email) < 5 || len(ReqInfo.Email) >= 255 {
|
||||
utils.HttpResponse(c, 400, "", "invilad email")
|
||||
return
|
||||
}
|
||||
userData.Email = ReqInfo.Email
|
||||
|
||||
if len(ReqInfo.Username) < 5 || len(ReqInfo.Username) >= 255 {
|
||||
utils.HttpResponse(c, 400, "", "invilad user name")
|
||||
return
|
||||
}
|
||||
userData.Username = ReqInfo.Username
|
||||
|
||||
userData.Nickname = ReqInfo.Nickname
|
||||
userData.Subtitle = ReqInfo.Subtitle
|
||||
userData.Avatar = ReqInfo.Avatar
|
||||
|
||||
if ReqInfo.Bio != "" {
|
||||
if !cryptography.IsBase64Std(ReqInfo.Bio) {
|
||||
c.JSON(400, gin.H{"status": "invalid base64"})
|
||||
utils.HttpResponse(c, 400, "", "invalid base64")
|
||||
}
|
||||
}
|
||||
userData.Bio = ReqInfo.Bio
|
||||
@@ -46,5 +58,5 @@ func Update(c *gin.Context) {
|
||||
// Update user info
|
||||
userData.UpdateByUserID(userId)
|
||||
|
||||
c.JSON(200, gin.H{"status": "success"})
|
||||
utils.HttpResponse(c, 200, "", "success")
|
||||
}
|
||||
|
||||
30
utils/response.go
Normal file
30
utils/response.go
Normal file
@@ -0,0 +1,30 @@
|
||||
package utils
|
||||
|
||||
import "github.com/gin-gonic/gin"
|
||||
|
||||
type RespStatus struct {
|
||||
Code int `json:"code"`
|
||||
ErrorId string `json:"error_id"`
|
||||
Status string `json:"status"`
|
||||
Data any `json:"data"`
|
||||
}
|
||||
|
||||
func HttpResponse(c *gin.Context, code int, errorId string, status string, data ...any) {
|
||||
var resp = RespStatus{
|
||||
Code: code,
|
||||
ErrorId: errorId,
|
||||
Status: status,
|
||||
Data: data,
|
||||
}
|
||||
c.JSON(code, resp)
|
||||
}
|
||||
|
||||
func HttpAbort(c *gin.Context, code int, errorId string, status string, data ...any) {
|
||||
var resp = RespStatus{
|
||||
Code: code,
|
||||
ErrorId: errorId,
|
||||
Status: status,
|
||||
Data: data,
|
||||
}
|
||||
c.AbortWithStatusJSON(code, resp)
|
||||
}
|
||||
Reference in New Issue
Block a user