Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add totp support #562

Closed
wants to merge 9 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 3 additions & 0 deletions authz/authz.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,9 @@ p, *, *, GET, /.well-known/openid-configuration, *, *
p, *, *, *, /api/certs, *, *
p, *, *, GET, /api/get-saml-login, *, *
p, *, *, POST, /api/acs, *, *
p, *, *, POST, /api/two-factor/setup/totp/init, *, *
p, *, *, POST, /api/two-factor/setup/totp/verity, *, *
p, *, *, POST, /api/two-factor/auth/totp, *, *
`

sa := stringadapter.NewAdapter(ruleText)
Expand Down
66 changes: 54 additions & 12 deletions controllers/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,18 +30,37 @@ import (
"github.com/casdoor/casdoor/util"
)

func codeToResponse(code *object.Code) *Response {
if code.Code == "" {
return &Response{Status: "error", Msg: code.Message, Data: code.Code}
}
const TwoFactorSessionKey = "TwoFactor"
const NextTwoFactor = "nextTwoFactor"

type TwoFactorSessionData struct {
UserId string
EnableSession bool
AutoSignIn bool
}

return &Response{Status: "ok", Msg: "", Data: code.Code}
func (c *ApiController) SetFactorSessionData(data *TwoFactorSessionData) {
c.SetSession(TwoFactorSessionKey, data)
}

func (c *ApiController) GetTOTPSessionData() *TwoFactorSessionData {
v := c.GetSession(TwoFactorSessionKey)
data, ok := v.(*TwoFactorSessionData)
if !ok {
return nil
}
return data
}

// HandleLoggedIn ...
func (c *ApiController) HandleLoggedIn(application *object.Application, user *object.User, form *RequestForm) (resp *Response) {
userId := user.GetId()
if form.Type == ResponseTypeLogin {
if user.IsEnableTwoFactor() {
c.SetFactorSessionData(&TwoFactorSessionData{UserId: userId, EnableSession: true, AutoSignIn: form.AutoSignin})
resp = &Response{Status: NextTwoFactor}
return
}
c.SetSessionUsername(userId)
util.LogInfo(c.Ctx, "API: [%s] signed in", userId)
resp = &Response{Status: "ok", Msg: "", Data: userId}
Expand All @@ -60,28 +79,51 @@ func (c *ApiController) HandleLoggedIn(application *object.Application, user *ob
return
}
code := object.GetOAuthCode(userId, clientId, responseType, redirectUri, scope, state, nonce, codeChallenge)
resp = codeToResponse(code)
status := ""
if code.Code == "" {
status = "error"
} else {
if user.IsEnableTwoFactor() {
status = NextTwoFactor
} else {
status = "ok"
}
}
resp = &Response{Status: status, Msg: code.Message, Data: code.Code}

if application.EnableSigninSession || application.HasPromptPage() {
// The prompt page needs the user to be signed in
c.SetSessionUsername(userId)
if user.IsEnableTwoFactor() {
c.SetFactorSessionData(&TwoFactorSessionData{
UserId: userId,
EnableSession: true,
AutoSignIn: form.AutoSignin,
})
return
} else {
c.SetSessionUsername(userId)
}
}
} else {
resp = &Response{Status: "error", Msg: fmt.Sprintf("Unknown response type: %s", form.Type)}
}

// if user did not check auto signin
if resp.Status == "ok" && !form.AutoSignin {
timestamp := time.Now().Unix()
timestamp += 3600 * 24
c.SetSessionData(&SessionData{
ExpireTime: timestamp,
})
c.setExpireForSession()
}

return resp
}

func (c *ApiController) setExpireForSession() {
timestamp := time.Now().Unix()
timestamp += 3600 * 24
c.SetSessionData(&SessionData{
ExpireTime: timestamp,
})
}

// GetApplicationLogin ...
// @Title GetApplicationLogin
// @Tag Login API
Expand Down
164 changes: 164 additions & 0 deletions controllers/two_factor_totp.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
// Copyright 2022 The casbin Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package controllers

import (
"fmt"
"net/http"
"strings"

"github.com/astaxie/beego"
jsoniter "github.com/json-iterator/go"

"github.com/casdoor/casdoor/object"
"github.com/google/uuid"
)

type TOTPInit struct {
Secret string `json:"secret"`
RecoveryCode string `json:"recoveryCode"`
URL string `json:"url"`
}

// TwoFactorSetupInitTOTP
// @Title: Setup init TOTP
// @Tag: Two-Factor API
// @router: /two-factor/setup/totp/init [post]
func (c *ApiController) TwoFactorSetupInitTOTP() {
userId := jsoniter.Get(c.Ctx.Input.RequestBody, "userId").ToString()
if len(userId) == 0 {
c.ResponseError(http.StatusText(http.StatusBadRequest))
return
}

user := object.GetUser(userId)
if user == nil {
c.ResponseError("User doesn't exist")
return
}
if len(user.TotpSecret) != 0 {
c.ResponseError("User has TOTP two-factor authentication enabled")
return
}

application := object.GetApplicationByUser(user)

issuer := beego.AppConfig.String("appname")
accountName := fmt.Sprintf("%s/%s", application.Name, user.Name)

key, err := object.NewTOTPKey(issuer, accountName)
if err != nil {
c.ResponseError(err.Error())
return
}

recoveryCode, err := uuid.NewRandom()
if err != nil {
c.ResponseError(err.Error())
return
}

resp := TOTPInit{
Secret: key.Secret(),
RecoveryCode: strings.ReplaceAll(recoveryCode.String(), "-", ""),
URL: key.URL(),
}
c.ResponseOk(resp)
}

// TwoFactorSetupVerityTOTP
// @Title: Setup verity TOTP
// @Tag: Two-Factor API
// @router: /two-factor/setup/totp/verity [post]
func (c *ApiController) TwoFactorSetupVerityTOTP() {
secret := jsoniter.Get(c.Ctx.Input.RequestBody, "secret").ToString()
passcode := jsoniter.Get(c.Ctx.Input.RequestBody, "passcode").ToString()
ok := object.ValidateTOTPPassCode(passcode, secret)
if ok {
c.ResponseOk(http.StatusText(http.StatusOK))
} else {
c.ResponseError(http.StatusText(http.StatusUnauthorized))
}
}

// TwoFactorEnableTOTP
// @Title: Enable TOTP
// @Tag: Two-Factor API
// @router: /two-factor/totp [post]
func (c *ApiController) TwoFactorEnableTOTP() {
userId := jsoniter.Get(c.Ctx.Input.RequestBody, "userId").ToString()
secret := jsoniter.Get(c.Ctx.Input.RequestBody, "secret").ToString()
recoveryCode := jsoniter.Get(c.Ctx.Input.RequestBody, "recoveryCode").ToString()

user := object.GetUser(userId)
if user == nil {
c.ResponseError("User doesn't exist")
return
}

object.SetUserField(user, "totp_secret", secret)
object.SetUserField(user, "two_factor_recovery_code", recoveryCode)

c.ResponseOk(http.StatusText(http.StatusOK))
}

// TwoFactorRemoveTOTP
// @Title: Remove TOTP
// @Tag: Two-Factor API
// @router: /two-factor/totp [delete]
func (c *ApiController) TwoFactorRemoveTOTP() {
userId := jsoniter.Get(c.Ctx.Input.RequestBody, "userId").ToString()

user := object.GetUser(userId)
if user == nil {
c.ResponseError("User doesn't exist")
return
}

object.SetUserField(user, "totp_secret", "")
c.ResponseOk(http.StatusText(http.StatusOK))
}

// TwoFactorAuthTOTP
// @Title: Auth TOTP
// @Tag: TOTP API
// @router: /two-factor/auth/totp [post]
func (c *ApiController) TwoFactorAuthTOTP() {
totpSessionData := c.GetTOTPSessionData()
if totpSessionData == nil {
c.ResponseError(http.StatusText(http.StatusBadRequest))
return
}

user := object.GetUser(totpSessionData.UserId)
if user == nil {
c.ResponseError("User does not exist")
return
}

passcode := jsoniter.Get(c.Ctx.Input.RequestBody, "passcode").ToString()
ok := object.ValidateTOTPPassCode(passcode, user.TotpSecret)
if ok {
if totpSessionData.EnableSession {
c.SetSessionUsername(totpSessionData.UserId)
}
if !totpSessionData.AutoSignIn {
c.setExpireForSession()
}
c.ResponseOk(http.StatusText(http.StatusOK))
} else {
c.ResponseError(http.StatusText(http.StatusUnauthorized))
}
}
40 changes: 20 additions & 20 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,39 +3,39 @@ module github.com/casdoor/casdoor
go 1.16

require (
github.com/aliyun/aliyun-oss-go-sdk v2.1.6+incompatible // indirect
github.com/aliyun/aliyun-oss-go-sdk v2.2.0+incompatible // indirect
github.com/astaxie/beego v1.12.3
github.com/aws/aws-sdk-go v1.37.30
github.com/aws/aws-sdk-go v1.42.49
github.com/baiyubin/aliyun-sts-go-sdk v0.0.0-20180326062324-cfa1a18b161f // indirect
github.com/casbin/casbin/v2 v2.30.1
github.com/casbin/casbin/v2 v2.41.0
github.com/casbin/xorm-adapter/v2 v2.5.1
github.com/casdoor/go-sms-sender v0.0.5
github.com/casdoor/go-sms-sender v0.0.6
github.com/dchest/captcha v0.0.0-20200903113550-03f5f0333e1f
github.com/go-gomail/gomail v0.0.0-20160411212932-81ebce5c23df
github.com/go-ldap/ldap/v3 v3.3.0
github.com/go-sql-driver/mysql v1.5.0
github.com/golang-jwt/jwt/v4 v4.1.0
github.com/google/uuid v1.2.0
github.com/go-ldap/ldap/v3 v3.4.1
github.com/go-sql-driver/mysql v1.6.0
github.com/golang-jwt/jwt/v4 v4.2.0
github.com/google/uuid v1.3.0
github.com/jinzhu/configor v1.2.1 // indirect
github.com/markbates/goth v1.68.1-0.20211006204042-9dc8905b41c8
github.com/json-iterator/go v1.1.11
github.com/markbates/goth v1.69.0
github.com/pquerna/otp v1.3.0
github.com/qiangmzsx/string-adapter/v2 v2.1.0
github.com/qor/oss v0.0.0-20191031055114-aef9ba66bf76
github.com/qor/oss v0.0.0-20210412121326-3c5583a62015
github.com/robfig/cron/v3 v3.0.1
github.com/russellhaering/gosaml2 v0.6.0
github.com/russellhaering/goxmldsig v1.1.1
github.com/satori/go.uuid v1.2.0 // indirect
github.com/smartystreets/goconvey v1.6.4 // indirect
github.com/tealeg/xlsx v1.0.5
github.com/thanhpk/randstr v1.0.4
golang.org/x/crypto v0.0.0-20211215153901-e495a2d5b3d3
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2
golang.org/x/oauth2 v0.0.0-20210628180205-a41e5a781914
golang.org/x/time v0.0.0-20210220033141-f8bda1e9f3ba // indirect
golang.org/x/crypto v0.0.0-20220208233918-bba287dce954
golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd
golang.org/x/oauth2 v0.0.0-20211104180415-d3ed0bb246c8
golang.org/x/time v0.0.0-20211116232009-f0f3c7e86c11 // indirect
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect
gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df // indirect
gopkg.in/ini.v1 v1.62.0 // indirect
gopkg.in/ini.v1 v1.66.3 // indirect
gopkg.in/square/go-jose.v2 v2.6.0
gopkg.in/yaml.v2 v2.3.0 // indirect
xorm.io/core v0.7.2
xorm.io/xorm v1.0.3
gopkg.in/yaml.v2 v2.4.0 // indirect
xorm.io/core v0.7.3
xorm.io/xorm v1.2.5
)