Skip to content

Commit

Permalink
Merge pull request #64 from mc0814/master
Browse files Browse the repository at this point in the history
add login captcha
  • Loading branch information
zhenorzz authored Aug 17, 2023
2 parents 82e699f + 7bc6a27 commit 76ccb46
Show file tree
Hide file tree
Showing 20 changed files with 1,447 additions and 8 deletions.
127 changes: 125 additions & 2 deletions cmd/server/api/user/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,19 @@ import (
"errors"
"fmt"
"github.com/go-ldap/ldap/v3"
"github.com/wenlng/go-captcha/captcha"
"github.com/zhenorzz/goploy/cmd/server/api"
"github.com/zhenorzz/goploy/cmd/server/api/middleware"
"github.com/zhenorzz/goploy/config"
"github.com/zhenorzz/goploy/internal/cache"
"github.com/zhenorzz/goploy/internal/media"
"github.com/zhenorzz/goploy/internal/model"
"github.com/zhenorzz/goploy/internal/server"
"github.com/zhenorzz/goploy/internal/server/response"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)

Expand All @@ -40,6 +43,9 @@ func (u User) Handler() []server.Route {
server.NewRoute("/user/remove", http.MethodDelete, u.Remove).Permissions(config.DeleteMember).LogFunc(middleware.AddOPLog),
server.NewWhiteRoute("/user/mediaLogin", http.MethodPost, u.MediaLogin).LogFunc(middleware.AddLoginLog),
server.NewWhiteRoute("/user/getMediaLoginUrl", http.MethodGet, u.GetMediaLoginUrl),
server.NewWhiteRoute("/user/getCaptchaConfig", http.MethodGet, u.GetCaptchaConfig),
server.NewWhiteRoute("/user/getCaptcha", http.MethodGet, u.GetCaptcha),
server.NewWhiteRoute("/user/checkCaptcha", http.MethodPost, u.CheckCaptcha),
}
}

Expand All @@ -52,14 +58,30 @@ func (u User) Handler() []server.Route {
// @Router /user/login [post]
func (User) Login(gp *server.Goploy) server.Response {
type ReqData struct {
Account string `json:"account" validate:"required,min=1,max=25"`
Password string `json:"password" validate:"required,password"`
Account string `json:"account" validate:"required,min=1,max=25"`
Password string `json:"password" validate:"required,password"`
CaptchaKey string `json:"captchaKey" validate:"omitempty"`
}
var reqData ReqData
if err := gp.Decode(&reqData); err != nil {
return response.JSON{Code: response.IllegalParam, Message: err.Error()}
}

userCache := cache.GetUserCache()

if config.Toml.Captcha.Enabled && userCache.IsShowCaptcha(reqData.Account) {
captchaCache := cache.GetCaptchaCache()
if !captchaCache.IsChecked(reqData.CaptchaKey) {
return response.JSON{Code: response.Error, Message: "Captcha error, please check captcha again"}
}
// captcha should be deleted after check
captchaCache.Delete(reqData.CaptchaKey)
}

if userCache.IsLock(reqData.Account) {
return response.JSON{Code: response.Error, Message: "Your account has been locked, please retry login in 15 minutes"}
}

userData, err := model.User{Account: reqData.Account}.GetDataByAccount()
if errors.Is(err, sql.ErrNoRows) {
return response.JSON{Code: response.Error, Message: "We couldn't verify your identity. Please confirm if your username and password are correct."}
Expand Down Expand Up @@ -108,10 +130,17 @@ func (User) Login(gp *server.Goploy) server.Response {
}
} else {
if err := userData.Validate(reqData.Password); err != nil {
errorTimes := userCache.IncErrorTimes(reqData.Account, cache.UserCacheExpireTime, cache.UserCacheShowCaptchaTime)
// error times over 5 times, then lock the account 15 minutes
if errorTimes >= cache.UserCacheMaxErrorTimes {
userCache.LockAccount(reqData.Account, cache.UserCacheLockTime)
}
return response.JSON{Code: response.Deny, Message: err.Error()}
}
}

userCache.DeleteShowCaptcha(reqData.Account)

if userData.State == model.Disable {
return response.JSON{Code: response.AccountDisabled, Message: "Account is disabled"}
}
Expand Down Expand Up @@ -566,3 +595,97 @@ func (User) GetMediaLoginUrl(gp *server.Goploy) server.Response {
}{Dingtalk: dingtalk, Feishu: feishu},
}
}

func (User) GetCaptchaConfig(gp *server.Goploy) server.Response {
return response.JSON{
Data: struct {
Enabled bool `json:"enabled"`
}{
Enabled: config.Toml.Captcha.Enabled,
},
}
}

func (User) GetCaptcha(gp *server.Goploy) server.Response {
type ReqData struct {
Language string `schema:"language" validate:"required"`
}

var reqData ReqData
if err := gp.Decode(&reqData); err != nil {
return response.JSON{Code: response.Error, Message: err.Error()}
}

capt := captcha.GetCaptcha()
if reqData.Language == "zh-cn" {
chars := captcha.GetCaptchaDefaultChars()
_ = capt.SetRangChars(*chars)
} else {
chars := "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
_ = capt.SetRangChars(strings.Split(chars, ""))
}

dots, b64, tb64, key, err := capt.Generate()
if err != nil {
return response.JSON{Code: response.AccountDisabled, Message: "generate captcha fail, error msg:" + err.Error()}
}

captchaCache := cache.GetCaptchaCache()
captchaCache.Set(key, dots, 2*time.Minute)

return response.JSON{
Data: struct {
Base64 string `json:"base64"`
ThumbBase64 string `json:"thumbBase64"`
Key string `json:"key"`
}{
Base64: b64,
ThumbBase64: tb64,
Key: key,
},
}
}

func (User) CheckCaptcha(gp *server.Goploy) server.Response {
type ReqData struct {
Key string `json:"key" validate:"required"`
Dots []int64 `json:"dots" validate:"required"`
RedirectUri string `json:"redirectUri" validate:"omitempty"`
}

var reqData ReqData
if err := gp.Decode(&reqData); err != nil {
return response.JSON{Code: response.Error, Message: err.Error()}
}

captchaCache := cache.GetCaptchaCache()
dotsCache, ok := captchaCache.Get(reqData.Key)
if !ok {
return response.JSON{Code: response.Error, Message: "Illegal key, please refresh the captcha again"}
}
dots, _ := dotsCache.(map[int]captcha.CharDot)

check := false
if (len(dots) * 2) == len(reqData.Dots) {
for i, dot := range dots {
j := i * 2
k := i*2 + 1
sx, _ := strconv.ParseFloat(fmt.Sprintf("%v", reqData.Dots[j]), 64)
sy, _ := strconv.ParseFloat(fmt.Sprintf("%v", reqData.Dots[k]), 64)

check = captcha.CheckPointDistWithPadding(int64(sx), int64(sy), int64(dot.Dx), int64(dot.Dy), int64(dot.Width), int64(dot.Height), 15)
if !check {
break
}
}
}

if !check {
return response.JSON{Code: response.Error, Message: "check captcha fail"}
}

// set captcha key checked for login verify
captchaCache.Set(reqData.Key, true, 2*time.Minute)

return response.JSON{}
}
10 changes: 10 additions & 0 deletions config/toml.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ type Config struct {
Dingtalk DingtalkConfig `toml:"dingtalk"`
Feishu FeishuConfig `toml:"feishu"`
CORS CORSConfig `toml:"cors"`
Captcha CaptchaConfig `toml:"captcha"`
Cache CacheConfig `toml:"cache"`
}

type APPConfig struct {
Expand Down Expand Up @@ -91,6 +93,14 @@ type FeishuConfig struct {
AppSecret string `toml:"appSecret"`
}

type CaptchaConfig struct {
Enabled bool `toml:"enabled"`
}

type CacheConfig struct {
Type string `toml:"type"`
}

var Toml Config

func InitToml() {
Expand Down
3 changes: 3 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -18,20 +18,23 @@ require (
github.com/pkg/sftp v1.13.1
github.com/sirupsen/logrus v1.9.3
github.com/vearutop/statigz v1.1.8
github.com/wenlng/go-captcha v1.2.5
golang.org/x/crypto v0.1.0
gopkg.in/go-playground/validator.v9 v9.31.0
)

require (
github.com/Azure/go-ntlmssp v0.0.0-20211209120228-48547f28849e // indirect
github.com/go-asn1-ber/asn1-ber v1.5.3 // indirect
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 // indirect
github.com/hashicorp/errwrap v1.1.0 // indirect
github.com/hashicorp/go-multierror v1.1.1 // indirect
github.com/kr/fs v0.1.0 // indirect
github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 // indirect
github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 // indirect
github.com/leodido/go-urn v1.2.0 // indirect
github.com/pkg/errors v0.9.1 // indirect
golang.org/x/image v0.1.0 // indirect
golang.org/x/sys v0.1.0 // indirect
gopkg.in/go-playground/assert.v1 v1.2.1 // indirect
)
26 changes: 26 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ github.com/go-sql-driver/mysql v1.5.0 h1:ozyZYNQW3x3HtqT1jira07DN2PArx2v7/mN66gG
github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg=
github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY=
github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I=
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 h1:DACJavvAHhabrF08vX0COfcOBJRhZ8lUbR+ZWIs0Y5g=
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0/go.mod h1:E/TSTwGwJL78qG/PmXZO1EjYhfJinVAhrmmHX6Z8B9k=
github.com/google/uuid v1.1.1 h1:Gkbcsh/GbpXz7lPftLA3P6TYMwjCLYm83jiFQZF/3gY=
github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/schema v1.2.0 h1:YufUaxZYCKGFuAq3c96BOhjgd5nmXiOY9NGzF247Tsc=
Expand Down Expand Up @@ -62,26 +64,50 @@ github.com/stretchr/testify v1.7.1-0.20210427113832-6241f9ab9942 h1:t0lM6y/M5IiU
github.com/stretchr/testify v1.7.1-0.20210427113832-6241f9ab9942/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/vearutop/statigz v1.1.8 h1:IJgQHx6EomuYOYd2TzFt3haP+BIzV471zn7aepRiLHA=
github.com/vearutop/statigz v1.1.8/go.mod h1:pfzrpvgLRnFeSVZd9iUYrpYDLqbV+RgeCfizr3ZFf44=
github.com/wenlng/go-captcha v1.2.5 h1:zA0/fovEl9oAhSg+KwHBwmq99GeeAXknWx6wYKjhjTg=
github.com/wenlng/go-captcha v1.2.5/go.mod h1:QgPgpEURSa37gF3GtojNoNRwbMwuatSBx5NXrzASOb0=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20200604202706-70a84ac30bf9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4=
golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.1.0 h1:MDRAIl0xIo9Io2xV565hzXHw3zVseKrJKodhohM5CjU=
golang.org/x/crypto v0.1.0/go.mod h1:RecgLatLF4+eUMCP1PoPZQb+cVrJcOPbHkTkbkB9sbw=
golang.org/x/image v0.0.0-20210628002857-a66eb6448b8d h1:RNPAfi2nHY7C2srAV8A49jpsYr0ADedCk1wq6fTMTvs=
golang.org/x/image v0.0.0-20210628002857-a66eb6448b8d/go.mod h1:023OzeP/+EPmXeapQh35lcL3II3LrY8Ic+EFFKVhULM=
golang.org/x/image v0.1.0 h1:r8Oj8ZA2Xy12/b5KZYj3tuv7NG/fBz3TwQVvpJ9l8Rk=
golang.org/x/image v0.1.0/go.mod h1:iyPr49SD/G/TBxYVB/9RRtGUT5eNbo2u4NamWeQcD5c=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423185535-09eb48e85fd7/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.1.0 h1:kunALQeHf1/185U1i0GOB/fy1IPRDDpuoOOqRReG57U=
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.1.0 h1:g6Z6vPFA9dYBAF7DWcH6sCcOntplXsDKcliusYijMlw=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/go-playground/assert.v1 v1.2.1 h1:xoYuJVE7KT85PYWrN730RguIQO0ePzVRfFMXadIrXTM=
gopkg.in/go-playground/assert.v1 v1.2.1/go.mod h1:9RXL0bg/zibRAgZUYszZSwO/z8Y/a8bDuhia5mkpMnE=
Expand Down
8 changes: 7 additions & 1 deletion goploy.example.toml
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,10 @@ appSecret = ''

[feishu]
appKey = ''
appSecret = ''
appSecret = ''

[captcha]
enabled = false

[cache]
type = 'memory'
10 changes: 10 additions & 0 deletions internal/cache/captcha.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package cache

import "time"

type Captcha interface {
Get(key string) (interface{}, bool)
Set(key string, value interface{}, ttl time.Duration)
Delete(key string)
IsChecked(key string) bool
}
8 changes: 8 additions & 0 deletions internal/cache/dingtalk.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package cache

import "time"

type DingtalkAccessToken interface {
Get(key string) (string, bool)
Set(key string, value string, ttl time.Duration)
}
37 changes: 37 additions & 0 deletions internal/cache/factory.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package cache

import (
"github.com/zhenorzz/goploy/config"
"github.com/zhenorzz/goploy/internal/cache/memory"
)

const MemoryCache = "memory"

var cacheType = config.Toml.Cache.Type

func GetUserCache() User {
switch cacheType {
case MemoryCache:
return memory.GetUserCache()
default:
return memory.GetUserCache()
}
}

func GetCaptchaCache() Captcha {
switch cacheType {
case MemoryCache:
return memory.GetCaptchaCache()
default:
return memory.GetCaptchaCache()
}
}

func GetDingTalkAccessTokenCache() DingtalkAccessToken {
switch cacheType {
case MemoryCache:
return memory.GetDingTalkAccessTokenCache()
default:
return memory.GetDingTalkAccessTokenCache()
}
}
Loading

0 comments on commit 76ccb46

Please sign in to comment.