2022-02-13 23:39:27 +08:00
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
2021-02-14 00:22:24 +08:00
//
// 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 (
2021-12-10 00:23:04 +08:00
"encoding/base64"
2021-03-15 00:49:16 +08:00
"encoding/json"
2022-11-13 15:05:15 +08:00
"encoding/xml"
2021-02-14 00:22:24 +08:00
"fmt"
2022-11-13 15:05:15 +08:00
"io/ioutil"
2023-09-18 15:42:00 +08:00
"net/http"
2021-12-06 21:46:50 +08:00
"net/url"
2021-06-11 23:34:45 +08:00
"strconv"
2021-06-02 13:39:01 +08:00
"strings"
2022-11-13 15:05:15 +08:00
"sync"
2021-02-14 00:22:24 +08:00
2022-10-28 13:38:14 +08:00
"github.com/casdoor/casdoor/captcha"
2022-03-20 23:21:09 +08:00
"github.com/casdoor/casdoor/conf"
2023-04-25 23:05:53 +08:00
"github.com/casdoor/casdoor/form"
2022-01-20 14:11:46 +08:00
"github.com/casdoor/casdoor/idp"
"github.com/casdoor/casdoor/object"
"github.com/casdoor/casdoor/proxy"
"github.com/casdoor/casdoor/util"
2022-05-31 21:49:56 +08:00
"github.com/google/uuid"
2023-11-19 19:58:07 +08:00
"golang.org/x/oauth2"
2021-02-14 00:22:24 +08:00
)
2022-11-13 15:05:15 +08:00
var (
wechatScanType string
lock sync . RWMutex
)
2021-03-20 22:34:22 +08:00
func codeToResponse ( code * object . Code ) * Response {
if code . Code == "" {
return & Response { Status : "error" , Msg : code . Message , Data : code . Code }
}
2021-08-07 22:02:56 +08:00
return & Response { Status : "ok" , Msg : "" , Data : code . Code }
2021-03-20 22:34:22 +08:00
}
2022-03-01 19:09:59 +08:00
func tokenToResponse ( token * object . Token ) * Response {
if token . AccessToken == "" {
return & Response { Status : "error" , Msg : "fail to get accessToken" , Data : token . AccessToken }
}
2023-01-09 23:33:03 +08:00
return & Response { Status : "ok" , Msg : "" , Data : token . AccessToken , Data2 : token . RefreshToken }
2022-03-01 19:09:59 +08:00
}
2021-08-07 22:02:56 +08:00
// HandleLoggedIn ...
2023-04-25 23:05:53 +08:00
func ( c * ApiController ) HandleLoggedIn ( application * object . Application , user * object . User , form * form . AuthForm ) ( resp * Response ) {
2021-05-01 19:45:40 +08:00
userId := user . GetId ( )
2022-07-13 00:34:35 +08:00
2023-09-15 02:47:53 +08:00
allowed , err := object . CheckLoginPermission ( userId , application )
2022-07-13 00:34:35 +08:00
if err != nil {
c . ResponseError ( err . Error ( ) , nil )
return
}
if ! allowed {
2022-12-07 13:13:23 +08:00
c . ResponseError ( c . T ( "auth:Unauthorized operation" ) )
2022-07-13 00:34:35 +08:00
return
}
2023-06-30 00:04:12 +08:00
// check user's tag
2023-08-19 12:23:15 +08:00
if ! user . IsGlobalAdmin ( ) && ! user . IsAdmin && len ( application . Tags ) > 0 {
2023-06-30 00:04:12 +08:00
// only users with the tag that is listed in the application tags can login
if ! util . InSlice ( application . Tags , user . Tag ) {
c . ResponseError ( fmt . Sprintf ( c . T ( "auth:User's tag: %s is not listed in the application's tags" ) , user . Tag ) )
return
}
}
2023-08-24 23:20:50 +08:00
// check whether paid-user have active subscription
if user . Type == "paid-user" {
subscriptions , err := object . GetSubscriptionsByUser ( user . Owner , user . Name )
if err != nil {
c . ResponseError ( err . Error ( ) )
return
}
existActiveSubscription := false
for _ , subscription := range subscriptions {
if subscription . State == object . SubStateActive {
existActiveSubscription = true
break
}
}
if ! existActiveSubscription {
// check pending subscription
for _ , sub := range subscriptions {
if sub . State == object . SubStatePending {
c . ResponseOk ( "BuyPlanResult" , sub )
return
}
}
// paid-user does not have active or pending subscription, find the default pricing of application
pricing , err := object . GetApplicationDefaultPricing ( application . Organization , application . Name )
if err != nil {
c . ResponseError ( err . Error ( ) )
return
}
if pricing == nil {
c . ResponseError ( fmt . Sprintf ( c . T ( "auth:paid-user %s does not have active or pending subscription and the application: %s does not have default pricing" ) , user . Name , application . Name ) )
return
} else {
// let the paid-user select plan
c . ResponseOk ( "SelectPlan" , pricing )
return
}
}
}
2021-03-20 10:51:00 +08:00
if form . Type == ResponseTypeLogin {
2021-07-18 07:15:22 +08:00
c . SetSessionUsername ( userId )
2021-03-20 10:51:00 +08:00
util . LogInfo ( c . Ctx , "API: [%s] signed in" , userId )
2021-03-20 13:05:34 +08:00
resp = & Response { Status : "ok" , Msg : "" , Data : userId }
2021-03-20 10:51:00 +08:00
} else if form . Type == ResponseTypeCode {
clientId := c . Input ( ) . Get ( "clientId" )
responseType := c . Input ( ) . Get ( "responseType" )
redirectUri := c . Input ( ) . Get ( "redirectUri" )
scope := c . Input ( ) . Get ( "scope" )
state := c . Input ( ) . Get ( "state" )
2021-12-15 21:42:16 +08:00
nonce := c . Input ( ) . Get ( "nonce" )
2022-01-21 09:29:19 +08:00
challengeMethod := c . Input ( ) . Get ( "code_challenge_method" )
codeChallenge := c . Input ( ) . Get ( "code_challenge" )
2022-01-30 17:58:54 +08:00
if challengeMethod != "S256" && challengeMethod != "null" && challengeMethod != "" {
2022-12-07 13:13:23 +08:00
c . ResponseError ( c . T ( "auth:Challenge method should be S256" ) )
2022-01-21 09:29:19 +08:00
return
}
2023-05-30 15:49:39 +08:00
code , err := object . GetOAuthCode ( userId , clientId , responseType , redirectUri , scope , state , nonce , codeChallenge , c . Ctx . Request . Host , c . GetAcceptLanguage ( ) )
if err != nil {
c . ResponseError ( err . Error ( ) , nil )
return
}
2021-03-20 10:51:00 +08:00
resp = codeToResponse ( code )
2021-06-20 22:17:03 +08:00
2021-12-28 17:13:45 +08:00
if application . EnableSigninSession || application . HasPromptPage ( ) {
2021-06-20 22:17:03 +08:00
// The prompt page needs the user to be signed in
2021-07-18 07:15:22 +08:00
c . SetSessionUsername ( userId )
2021-06-20 22:17:03 +08:00
}
2022-08-07 12:26:14 +08:00
} else if form . Type == ResponseTypeToken || form . Type == ResponseTypeIdToken { // implicit flow
2022-03-01 19:09:59 +08:00
if ! object . IsGrantTypeValid ( form . Type , application . GrantTypes ) {
resp = & Response { Status : "error" , Msg : fmt . Sprintf ( "error: grant_type: %s is not supported in this application" , form . Type ) , Data : "" }
} else {
scope := c . Input ( ) . Get ( "scope" )
token , _ := object . GetTokenByUser ( application , user , scope , c . Ctx . Request . Host )
resp = tokenToResponse ( token )
}
2022-04-08 23:06:48 +08:00
} else if form . Type == ResponseTypeSaml { // saml flow
2023-01-03 19:42:12 +08:00
res , redirectUrl , method , err := object . GetSamlResponse ( application , user , form . SamlRequest , c . Ctx . Request . Host )
2022-04-08 23:06:48 +08:00
if err != nil {
c . ResponseError ( err . Error ( ) , nil )
return
}
2023-01-03 19:42:12 +08:00
resp = & Response { Status : "ok" , Msg : "" , Data : res , Data2 : map [ string ] string { "redirectUrl" : redirectUrl , "method" : method } }
2023-07-14 11:27:18 +08:00
if application . EnableSigninSession || application . HasPromptPage ( ) {
// The prompt page needs the user to be signed in
c . SetSessionUsername ( userId )
}
2022-04-04 00:09:04 +08:00
} else if form . Type == ResponseTypeCas {
2022-08-07 12:26:14 +08:00
// not oauth but CAS SSO protocol
2022-04-04 00:09:04 +08:00
service := c . Input ( ) . Get ( "service" )
resp = wrapErrorResponse ( nil )
if service != "" {
st , err := object . GenerateCasToken ( userId , service )
if err != nil {
resp = wrapErrorResponse ( err )
} else {
resp . Data = st
}
}
2023-07-14 11:27:18 +08:00
2022-04-04 00:09:04 +08:00
if application . EnableSigninSession || application . HasPromptPage ( ) {
// The prompt page needs the user to be signed in
c . SetSessionUsername ( userId )
}
2021-03-20 10:51:00 +08:00
} else {
2022-08-09 16:50:49 +08:00
resp = wrapErrorResponse ( fmt . Errorf ( "unknown response type: %s" , form . Type ) )
2021-03-20 10:51:00 +08:00
}
2021-07-18 07:54:49 +08:00
// if user did not check auto signin
if resp . Status == "ok" && ! form . AutoSignin {
2023-05-05 21:23:59 +08:00
c . setExpireForSession ( )
2021-07-18 07:54:49 +08:00
}
2023-05-09 00:06:52 +08:00
if resp . Status == "ok" {
2023-05-30 15:49:39 +08:00
_ , err = object . AddSession ( & object . Session {
2023-02-12 09:33:24 +08:00
Owner : user . Owner ,
Name : user . Name ,
Application : application . Name ,
SessionId : [ ] string { c . Ctx . Input . CruSession . SessionID ( ) } ,
} )
2023-05-30 15:49:39 +08:00
if err != nil {
c . ResponseError ( err . Error ( ) , nil )
return
}
2023-01-06 15:04:13 +08:00
}
2021-03-20 10:51:00 +08:00
return resp
}
2021-08-07 22:02:56 +08:00
// GetApplicationLogin ...
2021-03-29 23:40:25 +08:00
// @Title GetApplicationLogin
2021-12-03 20:42:36 +08:00
// @Tag Login API
2021-03-29 23:40:25 +08:00
// @Description get application login
// @Param clientId query string true "client id"
// @Param responseType query string true "response type"
// @Param redirectUri query string true "redirect uri"
// @Param scope query string true "scope"
// @Param state query string true "state"
2022-06-21 23:11:29 +08:00
// @Success 200 {object} Response The Response object
2022-05-04 19:15:13 +08:00
// @router /get-app-login [get]
2021-03-20 10:51:00 +08:00
func ( c * ApiController ) GetApplicationLogin ( ) {
clientId := c . Input ( ) . Get ( "clientId" )
responseType := c . Input ( ) . Get ( "responseType" )
redirectUri := c . Input ( ) . Get ( "redirectUri" )
scope := c . Input ( ) . Get ( "scope" )
state := c . Input ( ) . Get ( "state" )
2023-08-19 01:05:55 +08:00
id := c . Input ( ) . Get ( "id" )
loginType := c . Input ( ) . Get ( "type" )
2021-03-20 10:51:00 +08:00
2023-08-19 01:05:55 +08:00
var application * object . Application
var msg string
var err error
if loginType == "code" {
msg , application , err = object . CheckOAuthLogin ( clientId , responseType , redirectUri , scope , state , c . GetAcceptLanguage ( ) )
if err != nil {
c . ResponseError ( err . Error ( ) )
return
}
} else if loginType == "cas" {
application , err = object . GetApplication ( id )
if err != nil {
c . ResponseError ( err . Error ( ) )
return
}
if application == nil {
c . ResponseError ( fmt . Sprintf ( c . T ( "auth:The application: %s does not exist" ) , id ) )
return
}
err = object . CheckCasLogin ( application , c . GetAcceptLanguage ( ) , redirectUri )
if err != nil {
c . ResponseError ( err . Error ( ) )
return
}
2023-05-30 15:49:39 +08:00
}
2022-03-02 20:58:16 +08:00
application = object . GetMaskedApplication ( application , "" )
2021-03-20 10:51:00 +08:00
if msg != "" {
2021-08-08 16:00:19 +08:00
c . ResponseError ( msg , application )
2021-03-20 10:51:00 +08:00
} else {
2021-08-08 16:00:19 +08:00
c . ResponseOk ( application )
2021-03-20 10:51:00 +08:00
}
2021-03-15 19:11:41 +08:00
}
2021-08-01 14:48:29 +08:00
func setHttpClient ( idProvider idp . IdProvider , providerType string ) {
2023-02-04 12:20:18 +08:00
if isProxyProviderType ( providerType ) {
2021-08-21 22:16:25 +08:00
idProvider . SetHttpClient ( proxy . ProxyHttpClient )
2021-08-01 14:48:29 +08:00
} else {
2021-08-21 22:16:25 +08:00
idProvider . SetHttpClient ( proxy . DefaultHttpClient )
2021-08-01 14:48:29 +08:00
}
}
2023-02-04 12:20:18 +08:00
func isProxyProviderType ( providerType string ) bool {
providerTypes := [ ] string {
"GitHub" ,
"Google" ,
"Facebook" ,
"LinkedIn" ,
"Steam" ,
"Line" ,
"Amazon" ,
"Instagram" ,
"TikTok" ,
"Twitter" ,
"Uber" ,
"Yahoo" ,
}
for _ , v := range providerTypes {
if strings . EqualFold ( v , providerType ) {
return true
}
}
return false
}
2021-08-07 22:02:56 +08:00
// Login ...
2021-03-29 23:40:25 +08:00
// @Title Login
2021-12-03 20:42:36 +08:00
// @Tag Login API
2021-03-29 23:40:25 +08:00
// @Description login
2022-06-21 23:11:29 +08:00
// @Param clientId query string true clientId
// @Param responseType query string true responseType
// @Param redirectUri query string true redirectUri
// @Param scope query string false scope
// @Param state query string false state
// @Param nonce query string false nonce
// @Param code_challenge_method query string false code_challenge_method
// @Param code_challenge query string false code_challenge
2023-04-25 23:05:53 +08:00
// @Param form body controllers.AuthForm true "Login information"
2023-06-30 00:48:39 +08:00
// @Success 200 {object} controllers.Response The Response object
2021-03-29 23:40:25 +08:00
// @router /login [post]
2021-03-20 00:23:37 +08:00
func ( c * ApiController ) Login ( ) {
2021-08-08 16:00:19 +08:00
resp := & Response { }
2023-04-25 23:05:53 +08:00
var authForm form . AuthForm
err := json . Unmarshal ( c . Ctx . Input . RequestBody , & authForm )
2021-03-15 00:49:16 +08:00
if err != nil {
2021-08-08 11:06:45 +08:00
c . ResponseError ( err . Error ( ) )
2021-06-09 19:54:26 +08:00
return
2021-03-15 00:49:16 +08:00
}
2021-02-14 00:22:24 +08:00
2023-04-25 23:05:53 +08:00
if authForm . Username != "" {
if authForm . Type == ResponseTypeLogin {
2021-07-18 07:15:22 +08:00
if c . GetSessionUsername ( ) != "" {
2023-03-19 21:47:49 +08:00
c . ResponseError ( c . T ( "account:Please sign out first" ) , c . GetSessionUsername ( ) )
2021-03-20 13:05:34 +08:00
return
}
2021-03-20 00:23:37 +08:00
}
2021-02-21 22:33:53 +08:00
2021-06-02 13:39:01 +08:00
var user * object . User
2023-04-25 23:05:53 +08:00
if authForm . Password == "" {
2023-05-30 15:49:39 +08:00
if user , err = object . GetUserByFields ( authForm . Organization , authForm . Username ) ; err != nil {
c . ResponseError ( err . Error ( ) , nil )
return
} else if user == nil {
2023-04-25 23:05:53 +08:00
c . ResponseError ( fmt . Sprintf ( c . T ( "general:The user: %s doesn't exist" ) , util . GetId ( authForm . Organization , authForm . Username ) ) )
2023-01-06 17:51:43 +07:00
return
}
2023-04-06 23:06:18 +08:00
2023-04-25 23:05:53 +08:00
verificationCodeType := object . GetVerifyType ( authForm . Username )
2023-04-06 23:06:18 +08:00
var checkDest string
if verificationCodeType == object . VerifyTypePhone {
2023-04-25 23:05:53 +08:00
authForm . CountryCode = user . GetCountryCode ( authForm . CountryCode )
2023-02-16 22:53:28 +08:00
var ok bool
2023-04-25 23:05:53 +08:00
if checkDest , ok = util . GetE164Number ( authForm . Username , authForm . CountryCode ) ; ! ok {
c . ResponseError ( fmt . Sprintf ( c . T ( "verification:Phone number is invalid in your region %s" ) , authForm . CountryCode ) )
2023-02-16 22:53:28 +08:00
return
}
}
2023-04-06 23:06:18 +08:00
// check result through Email or Phone
2023-11-19 19:58:07 +08:00
err = object . CheckSigninCode ( user , checkDest , authForm . Code , c . GetAcceptLanguage ( ) )
if err != nil {
c . ResponseError ( fmt . Sprintf ( "%s - %s" , verificationCodeType , err . Error ( ) ) )
2021-12-07 00:05:53 +08:00
return
2021-06-02 13:39:01 +08:00
}
2021-12-07 00:05:53 +08:00
// disable the verification code
2023-11-19 19:58:07 +08:00
err = object . DisableVerificationCode ( checkDest )
2023-05-30 15:49:39 +08:00
if err != nil {
c . ResponseError ( err . Error ( ) , nil )
return
}
2021-06-02 13:39:01 +08:00
} else {
2023-11-19 19:58:07 +08:00
var application * object . Application
application , err = object . GetApplication ( fmt . Sprintf ( "admin/%s" , authForm . Application ) )
2023-05-30 15:49:39 +08:00
if err != nil {
c . ResponseError ( err . Error ( ) , nil )
return
}
2022-10-28 13:38:14 +08:00
if application == nil {
2023-04-25 23:05:53 +08:00
c . ResponseError ( fmt . Sprintf ( c . T ( "auth:The application: %s does not exist" ) , authForm . Application ) )
2022-10-28 13:38:14 +08:00
return
}
2022-12-27 13:46:57 +07:00
if ! application . EnablePassword {
c . ResponseError ( c . T ( "auth:The login method: login with password is not enabled for the application" ) )
return
}
2023-04-22 16:16:25 +08:00
var enableCaptcha bool
2023-05-30 15:49:39 +08:00
if enableCaptcha , err = object . CheckToEnableCaptcha ( application , authForm . Organization , authForm . Username ) ; err != nil {
c . ResponseError ( err . Error ( ) )
return
} else if enableCaptcha {
2023-11-19 19:58:07 +08:00
var isHuman bool
isHuman , err = captcha . VerifyCaptchaByCaptchaType ( authForm . CaptchaType , authForm . CaptchaToken , authForm . ClientSecret )
2022-10-28 13:38:14 +08:00
if err != nil {
c . ResponseError ( err . Error ( ) )
return
}
if ! isHuman {
2023-03-19 21:47:49 +08:00
c . ResponseError ( c . T ( "verification:Turing test failed." ) )
2022-10-28 13:38:14 +08:00
return
}
}
2023-04-25 23:05:53 +08:00
password := authForm . Password
2023-11-19 19:58:07 +08:00
user , err = object . CheckUserPassword ( authForm . Organization , authForm . Username , password , c . GetAcceptLanguage ( ) , enableCaptcha )
2021-06-02 13:39:01 +08:00
}
2021-02-14 00:22:24 +08:00
2023-11-19 19:58:07 +08:00
if err != nil {
c . ResponseError ( err . Error ( ) )
return
2021-03-20 00:23:37 +08:00
} else {
2023-11-19 19:58:07 +08:00
var application * object . Application
application , err = object . GetApplication ( fmt . Sprintf ( "admin/%s" , authForm . Application ) )
2023-05-30 15:49:39 +08:00
if err != nil {
c . ResponseError ( err . Error ( ) )
return
}
2022-03-06 00:09:57 +08:00
if application == nil {
2023-04-25 23:05:53 +08:00
c . ResponseError ( fmt . Sprintf ( c . T ( "auth:The application: %s does not exist" ) , authForm . Application ) )
2022-03-06 00:09:57 +08:00
return
}
2023-11-19 19:58:07 +08:00
var organization * object . Organization
organization , err = object . GetOrganizationByUser ( user )
2023-05-30 15:49:39 +08:00
if err != nil {
c . ResponseError ( err . Error ( ) )
}
2023-07-07 12:30:07 +08:00
if object . IsNeedPromptMfa ( organization , user ) {
// The prompt page needs the user to be signed in
c . SetSessionUsername ( user . GetId ( ) )
c . ResponseOk ( object . RequiredMfa )
return
}
if user . IsMfaEnabled ( ) {
c . setMfaUserSession ( user . GetId ( ) )
c . ResponseOk ( object . NextMfa , user . GetPreferredMfaProps ( true ) )
return
2023-05-17 01:13:13 +08:00
}
2023-07-07 12:30:07 +08:00
resp = c . HandleLoggedIn ( application , user , & authForm )
2021-11-07 16:51:16 +08:00
record := object . NewRecord ( c . Ctx )
2021-07-07 14:59:03 +08:00
record . Organization = application . Organization
2021-11-07 17:20:15 +08:00
record . User = user . Name
2022-05-31 21:49:56 +08:00
util . SafeGoroutine ( func ( ) { object . AddRecord ( record ) } )
2021-03-20 00:23:37 +08:00
}
2023-04-25 23:05:53 +08:00
} else if authForm . Provider != "" {
2023-03-23 21:38:33 +08:00
var application * object . Application
2023-04-25 23:05:53 +08:00
if authForm . ClientId != "" {
2023-05-30 15:49:39 +08:00
application , err = object . GetApplicationByClientId ( authForm . ClientId )
if err != nil {
c . ResponseError ( err . Error ( ) )
return
}
2023-03-23 21:38:33 +08:00
} else {
2023-05-30 15:49:39 +08:00
application , err = object . GetApplication ( fmt . Sprintf ( "admin/%s" , authForm . Application ) )
if err != nil {
c . ResponseError ( err . Error ( ) )
return
}
2023-03-23 21:38:33 +08:00
}
2022-03-06 00:09:57 +08:00
if application == nil {
2023-04-25 23:05:53 +08:00
c . ResponseError ( fmt . Sprintf ( c . T ( "auth:The application: %s does not exist" ) , authForm . Application ) )
2022-03-06 00:09:57 +08:00
return
}
2023-11-19 19:58:07 +08:00
var organization * object . Organization
organization , err = object . GetOrganization ( util . GetId ( "admin" , application . Organization ) )
2023-05-30 15:49:39 +08:00
if err != nil {
c . ResponseError ( c . T ( err . Error ( ) ) )
}
2023-11-19 19:58:07 +08:00
var provider * object . Provider
provider , err = object . GetProvider ( util . GetId ( "admin" , authForm . Provider ) )
2023-05-30 15:49:39 +08:00
if err != nil {
c . ResponseError ( err . Error ( ) )
return
}
2022-03-06 00:09:57 +08:00
2021-06-14 21:35:19 +08:00
providerItem := application . GetProviderItem ( provider . Name )
2021-08-08 10:50:29 +08:00
if ! providerItem . IsProviderVisible ( ) {
2022-12-07 13:13:23 +08:00
c . ResponseError ( fmt . Sprintf ( c . T ( "auth:The provider: %s is not enabled for the application" ) , provider . Name ) )
2021-08-08 10:50:29 +08:00
return
}
2021-12-06 21:46:50 +08:00
userInfo := & idp . UserInfo { }
if provider . Category == "SAML" {
// SAML
2023-10-20 21:11:36 +08:00
userInfo , err = object . ParseSamlResponse ( authForm . SamlResponse , provider , c . Ctx . Request . Host )
2021-12-06 21:46:50 +08:00
if err != nil {
c . ResponseError ( err . Error ( ) )
return
}
2023-07-20 17:51:36 +08:00
} else if provider . Category == "OAuth" || provider . Category == "Web3" {
2021-12-06 21:46:50 +08:00
// OAuth
2023-07-05 20:35:02 +08:00
idpInfo := object . FromProviderToIdpInfo ( c . Ctx , provider )
2023-11-19 19:58:07 +08:00
var idProvider idp . IdProvider
idProvider , err = idp . GetIdProvider ( idpInfo , authForm . RedirectUri )
2023-10-31 23:09:49 +08:00
if err != nil {
c . ResponseError ( err . Error ( ) )
return
}
2021-12-06 21:46:50 +08:00
if idProvider == nil {
2023-03-19 21:47:49 +08:00
c . ResponseError ( fmt . Sprintf ( c . T ( "storage:The provider type: %s is not supported" ) , provider . Type ) )
2021-12-06 21:46:50 +08:00
return
}
2021-06-06 11:17:37 +08:00
2021-12-06 21:46:50 +08:00
setHttpClient ( idProvider , provider . Type )
2021-02-14 00:22:24 +08:00
2023-04-25 23:05:53 +08:00
if authForm . State != conf . GetConfigString ( "authState" ) && authForm . State != application . Name {
c . ResponseError ( fmt . Sprintf ( c . T ( "auth:State expected: %s, but got: %s" ) , conf . GetConfigString ( "authState" ) , authForm . State ) )
2021-12-06 21:46:50 +08:00
return
}
2021-02-14 00:22:24 +08:00
2021-12-06 21:46:50 +08:00
// https://github.com/golang/oauth2/issues/123#issuecomment-103715338
2023-11-19 19:58:07 +08:00
var token * oauth2 . Token
token , err = idProvider . GetToken ( authForm . Code )
2021-12-06 21:46:50 +08:00
if err != nil {
c . ResponseError ( err . Error ( ) )
return
}
2021-02-14 00:22:24 +08:00
2021-12-06 21:46:50 +08:00
if ! token . Valid ( ) {
2022-12-07 13:13:23 +08:00
c . ResponseError ( c . T ( "auth:Invalid token" ) )
2021-12-06 21:46:50 +08:00
return
}
2021-02-21 23:51:40 +08:00
2021-12-06 21:46:50 +08:00
userInfo , err = idProvider . GetUserInfo ( token )
if err != nil {
2022-12-07 13:13:23 +08:00
c . ResponseError ( fmt . Sprintf ( c . T ( "auth:Failed to login in: %s" ) , err . Error ( ) ) )
2021-12-06 21:46:50 +08:00
return
}
2021-03-20 00:23:37 +08:00
}
2021-02-21 23:51:40 +08:00
2023-04-25 23:05:53 +08:00
if authForm . Method == "signup" {
2021-12-06 21:46:50 +08:00
user := & object . User { }
if provider . Category == "SAML" {
2023-10-20 21:11:36 +08:00
// The userInfo.Id is the NameID in SAML response, it could be name / email / phone
user , err = object . GetUserByFields ( application . Organization , userInfo . Id )
2023-05-30 15:49:39 +08:00
if err != nil {
c . ResponseError ( err . Error ( ) )
return
}
2023-07-20 17:51:36 +08:00
} else if provider . Category == "OAuth" || provider . Category == "Web3" {
2023-05-30 15:49:39 +08:00
user , err = object . GetUserByField ( application . Organization , provider . Type , userInfo . Id )
if err != nil {
c . ResponseError ( err . Error ( ) )
return
}
2021-06-12 12:46:25 +08:00
}
2021-06-01 23:14:49 +08:00
2022-08-20 21:09:32 +08:00
if user != nil && ! user . IsDeleted {
2021-08-08 21:36:19 +08:00
// Sign in via OAuth (want to sign up but already have account)
2021-06-14 21:35:19 +08:00
2021-08-08 21:36:19 +08:00
if user . IsForbidden {
2023-03-19 21:47:49 +08:00
c . ResponseError ( c . T ( "check:The user is forbidden to sign in, please contact the administrator" ) )
2021-08-08 21:36:19 +08:00
}
2023-11-11 17:16:57 +08:00
// sync info from 3rd-party if possible
2023-11-19 19:58:07 +08:00
_ , err = object . SetUserOAuthProperties ( organization , user , provider . Type , userInfo )
2023-11-11 17:16:57 +08:00
if err != nil {
c . ResponseError ( err . Error ( ) )
return
}
2023-04-25 23:05:53 +08:00
resp = c . HandleLoggedIn ( application , user , & authForm )
2021-07-07 14:59:03 +08:00
2021-11-07 16:51:16 +08:00
record := object . NewRecord ( c . Ctx )
2021-07-07 14:59:03 +08:00
record . Organization = application . Organization
2021-11-07 17:20:15 +08:00
record . User = user . Name
2022-05-31 21:49:56 +08:00
util . SafeGoroutine ( func ( ) { object . AddRecord ( record ) } )
2023-07-20 17:51:36 +08:00
} else if provider . Category == "OAuth" || provider . Category == "Web3" {
2021-06-14 21:35:19 +08:00
// Sign up via OAuth
2023-01-11 23:19:16 +08:00
if application . EnableLinkWithEmail {
2023-05-17 22:14:57 +08:00
if userInfo . Email != "" {
// Find existing user with Email
2023-05-30 15:49:39 +08:00
user , err = object . GetUserByField ( application . Organization , "email" , userInfo . Email )
if err != nil {
c . ResponseError ( err . Error ( ) )
return
}
2023-05-17 22:14:57 +08:00
}
if user == nil && userInfo . Phone != "" {
// Find existing user with phone number
2023-05-30 15:49:39 +08:00
user , err = object . GetUserByField ( application . Organization , "phone" , userInfo . Phone )
if err != nil {
c . ResponseError ( err . Error ( ) )
return
}
2023-05-17 22:14:57 +08:00
}
2023-01-11 23:19:16 +08:00
}
if user == nil || user . IsDeleted {
2023-05-17 21:56:36 +08:00
if ! application . EnableSignUp {
c . ResponseError ( fmt . Sprintf ( c . T ( "auth:The account for provider: %s and username: %s (%s) does not exist and is not allowed to sign up as new account, please contact your IT support" ) , provider . Type , userInfo . Username , userInfo . DisplayName ) )
return
}
if ! providerItem . CanSignUp {
c . ResponseError ( fmt . Sprintf ( c . T ( "auth:The account for provider: %s and username: %s (%s) does not exist and is not allowed to sign up as new account via %%s, please use another way to sign up" ) , provider . Type , userInfo . Username , userInfo . DisplayName , provider . Type ) )
return
}
2023-01-11 23:19:16 +08:00
// Handle username conflicts
2023-11-19 19:58:07 +08:00
var tmpUser * object . User
tmpUser , err = object . GetUser ( util . GetId ( application . Organization , userInfo . Username ) )
2023-05-30 15:49:39 +08:00
if err != nil {
c . ResponseError ( err . Error ( ) )
return
}
2023-01-11 23:19:16 +08:00
if tmpUser != nil {
2023-11-19 19:58:07 +08:00
var uid uuid . UUID
uid , err = uuid . NewRandom ( )
2023-01-11 23:19:16 +08:00
if err != nil {
c . ResponseError ( err . Error ( ) )
return
}
uidStr := strings . Split ( uid . String ( ) , "-" )
userInfo . Username = fmt . Sprintf ( "%s_%s" , userInfo . Username , uidStr [ 1 ] )
}
properties := map [ string ] string { }
2023-11-19 19:58:07 +08:00
var count int64
count , err = object . GetUserCount ( application . Organization , "" , "" , "" )
2023-05-30 15:49:39 +08:00
if err != nil {
c . ResponseError ( err . Error ( ) )
return
}
properties [ "no" ] = strconv . Itoa ( int ( count + 2 ) )
2023-11-19 19:58:07 +08:00
var initScore int
initScore , err = organization . GetInitScore ( )
2022-05-31 21:49:56 +08:00
if err != nil {
2023-01-11 23:19:16 +08:00
c . ResponseError ( fmt . Errorf ( c . T ( "account:Get init score failed, error: %w" ) , err ) . Error ( ) )
2022-05-31 21:49:56 +08:00
return
}
2023-09-23 00:13:13 +08:00
userId := userInfo . Id
if userId == "" {
userId = util . GenerateId ( )
}
2023-01-11 23:19:16 +08:00
user = & object . User {
Owner : application . Organization ,
Name : userInfo . Username ,
CreatedTime : util . GetCurrentTime ( ) ,
2023-09-23 00:13:13 +08:00
Id : userId ,
2023-01-11 23:19:16 +08:00
Type : "normal-user" ,
DisplayName : userInfo . DisplayName ,
Avatar : userInfo . AvatarUrl ,
Address : [ ] string { } ,
Email : userInfo . Email ,
2023-04-29 01:11:58 +08:00
Phone : userInfo . Phone ,
CountryCode : userInfo . CountryCode ,
Region : userInfo . CountryCode ,
2023-01-11 23:19:16 +08:00
Score : initScore ,
IsAdmin : false ,
IsForbidden : false ,
IsDeleted : false ,
SignupApplication : application . Name ,
Properties : properties ,
}
2022-05-31 21:49:56 +08:00
2023-11-19 19:58:07 +08:00
var affected bool
affected , err = object . AddUser ( user )
2023-05-30 15:49:39 +08:00
if err != nil {
c . ResponseError ( err . Error ( ) )
return
}
2023-01-11 23:19:16 +08:00
if ! affected {
c . ResponseError ( fmt . Sprintf ( c . T ( "auth:Failed to create user, user information is invalid: %s" ) , util . StructToJson ( user ) ) )
return
}
2023-10-20 23:10:43 +08:00
if providerItem . SignupGroup != "" {
user . Groups = [ ] string { providerItem . SignupGroup }
_ , err = object . UpdateUser ( user . GetId ( ) , user , [ ] string { "groups" } , false )
if err != nil {
c . ResponseError ( err . Error ( ) )
return
}
}
2022-08-20 21:09:32 +08:00
}
2021-06-14 21:35:19 +08:00
// sync info from 3rd-party if possible
2023-11-19 19:58:07 +08:00
_ , err = object . SetUserOAuthProperties ( organization , user , provider . Type , userInfo )
2023-05-30 15:49:39 +08:00
if err != nil {
c . ResponseError ( err . Error ( ) )
return
}
_ , err = object . LinkUserAccount ( user , provider . Type , userInfo . Id )
if err != nil {
c . ResponseError ( err . Error ( ) )
return
}
2021-06-14 21:35:19 +08:00
2023-04-25 23:05:53 +08:00
resp = c . HandleLoggedIn ( application , user , & authForm )
2021-07-07 14:59:03 +08:00
2021-11-07 16:51:16 +08:00
record := object . NewRecord ( c . Ctx )
2021-07-07 14:59:03 +08:00
record . Organization = application . Organization
2021-11-07 17:20:15 +08:00
record . User = user . Name
2022-05-31 21:49:56 +08:00
util . SafeGoroutine ( func ( ) { object . AddRecord ( record ) } )
2022-06-01 09:34:56 +08:00
record2 := object . NewRecord ( c . Ctx )
record2 . Action = "signup"
record2 . Organization = application . Organization
record2 . User = user . Name
util . SafeGoroutine ( func ( ) { object . AddRecord ( record2 ) } )
2021-12-06 21:46:50 +08:00
} else if provider . Category == "SAML" {
2023-10-20 21:11:36 +08:00
// TODO: since we get the user info from SAML response, we can try to create the user
2023-01-06 20:24:14 +08:00
resp = & Response { Status : "error" , Msg : fmt . Sprintf ( c . T ( "general:The user: %s doesn't exist" ) , util . GetId ( application . Organization , userInfo . Id ) ) }
2021-02-14 00:22:24 +08:00
}
2022-08-07 12:26:14 +08:00
// resp = &Response{Status: "ok", Msg: "", Data: res}
2023-04-25 23:05:53 +08:00
} else { // authForm.Method != "signup"
2021-07-18 07:15:22 +08:00
userId := c . GetSessionUsername ( )
2021-03-20 00:23:37 +08:00
if userId == "" {
2023-01-06 20:24:14 +08:00
c . ResponseError ( fmt . Sprintf ( c . T ( "general:The user: %s doesn't exist" ) , util . GetId ( application . Organization , userInfo . Id ) ) , userInfo )
2021-03-20 00:23:37 +08:00
return
}
2023-11-19 19:58:07 +08:00
var oldUser * object . User
oldUser , err = object . GetUserByField ( application . Organization , provider . Type , userInfo . Id )
2023-05-30 15:49:39 +08:00
if err != nil {
c . ResponseError ( err . Error ( ) )
return
}
2021-06-18 23:25:24 +08:00
if oldUser != nil {
2022-12-07 13:13:23 +08:00
c . ResponseError ( fmt . Sprintf ( c . T ( "auth:The account for provider: %s and username: %s (%s) is already linked to another account: %s (%s)" ) , provider . Type , userInfo . Username , userInfo . DisplayName , oldUser . Name , oldUser . DisplayName ) )
2021-06-18 23:25:24 +08:00
return
}
2023-11-19 19:58:07 +08:00
var user * object . User
user , err = object . GetUser ( userId )
2023-05-30 15:49:39 +08:00
if err != nil {
c . ResponseError ( err . Error ( ) )
return
}
2021-04-27 19:35:40 +08:00
// sync info from 3rd-party if possible
2023-05-30 15:49:39 +08:00
_ , err = object . SetUserOAuthProperties ( organization , user , provider . Type , userInfo )
if err != nil {
c . ResponseError ( err . Error ( ) )
return
}
2023-11-19 19:58:07 +08:00
var isLinked bool
isLinked , err = object . LinkUserAccount ( user , provider . Type , userInfo . Id )
2023-05-30 15:49:39 +08:00
if err != nil {
c . ResponseError ( err . Error ( ) )
return
}
2021-04-27 19:35:40 +08:00
2021-03-24 00:11:20 +08:00
if isLinked {
resp = & Response { Status : "ok" , Msg : "" , Data : isLinked }
2021-03-20 00:23:37 +08:00
} else {
2021-03-28 08:59:12 +08:00
resp = & Response { Status : "error" , Msg : "Failed to link user account" , Data : isLinked }
2021-03-20 00:23:37 +08:00
}
2021-02-14 00:22:24 +08:00
}
2023-07-07 12:30:07 +08:00
} else if c . getMfaUserSession ( ) != "" {
2023-11-19 19:58:07 +08:00
var user * object . User
user , err = object . GetUser ( c . getMfaUserSession ( ) )
2023-05-30 15:49:39 +08:00
if err != nil {
c . ResponseError ( err . Error ( ) )
return
}
2023-07-07 12:30:07 +08:00
if user == nil {
c . ResponseError ( "expired user session" )
return
}
2023-05-05 21:23:59 +08:00
if authForm . Passcode != "" {
2023-06-21 18:56:37 +08:00
mfaUtil := object . GetMfaUtil ( authForm . MfaType , user . GetPreferredMfaProps ( false ) )
if mfaUtil == nil {
c . ResponseError ( "Invalid multi-factor authentication type" )
return
}
err = mfaUtil . Verify ( authForm . Passcode )
2023-05-05 21:23:59 +08:00
if err != nil {
c . ResponseError ( err . Error ( ) )
return
}
2023-07-07 12:30:07 +08:00
} else if authForm . RecoveryCode != "" {
2023-06-21 18:56:37 +08:00
err = object . MfaRecover ( user , authForm . RecoveryCode )
2023-05-05 21:23:59 +08:00
if err != nil {
c . ResponseError ( err . Error ( ) )
return
}
2023-07-07 12:30:07 +08:00
} else {
c . ResponseError ( "missing passcode or recovery code" )
return
2023-05-05 21:23:59 +08:00
}
2023-11-19 19:58:07 +08:00
var application * object . Application
application , err = object . GetApplication ( fmt . Sprintf ( "admin/%s" , authForm . Application ) )
2023-05-30 15:49:39 +08:00
if err != nil {
c . ResponseError ( err . Error ( ) )
return
}
2023-05-05 21:23:59 +08:00
if application == nil {
c . ResponseError ( fmt . Sprintf ( c . T ( "auth:The application: %s does not exist" ) , authForm . Application ) )
return
}
resp = c . HandleLoggedIn ( application , user , & authForm )
2023-07-07 12:30:07 +08:00
c . setMfaUserSession ( "" )
2023-05-05 21:23:59 +08:00
record := object . NewRecord ( c . Ctx )
record . Organization = application . Organization
record . User = user . Name
util . SafeGoroutine ( func ( ) { object . AddRecord ( record ) } )
2021-03-20 00:23:37 +08:00
} else {
2021-10-09 21:15:57 +08:00
if c . GetSessionUsername ( ) != "" {
// user already signed in to Casdoor, so let the user click the avatar button to do the quick sign-in
2023-11-19 19:58:07 +08:00
var application * object . Application
application , err = object . GetApplication ( fmt . Sprintf ( "admin/%s" , authForm . Application ) )
2023-05-30 15:49:39 +08:00
if err != nil {
c . ResponseError ( err . Error ( ) )
return
}
2022-03-06 00:09:57 +08:00
if application == nil {
2023-04-25 23:05:53 +08:00
c . ResponseError ( fmt . Sprintf ( c . T ( "auth:The application: %s does not exist" ) , authForm . Application ) )
2022-03-06 00:09:57 +08:00
return
}
2021-10-09 21:15:57 +08:00
user := c . getCurrentUser ( )
2023-04-25 23:05:53 +08:00
resp = c . HandleLoggedIn ( application , user , & authForm )
2022-06-01 09:34:56 +08:00
record := object . NewRecord ( c . Ctx )
record . Organization = application . Organization
record . User = user . Name
util . SafeGoroutine ( func ( ) { object . AddRecord ( record ) } )
2021-10-09 21:15:57 +08:00
} else {
2023-05-05 21:23:59 +08:00
c . ResponseError ( fmt . Sprintf ( c . T ( "auth:Unknown authentication type (not password or provider), form = %s" ) , util . StructToJson ( authForm ) ) )
2021-10-09 21:15:57 +08:00
return
}
2021-02-14 00:22:24 +08:00
}
c . Data [ "json" ] = resp
c . ServeJSON ( )
}
2021-12-06 21:46:50 +08:00
func ( c * ApiController ) GetSamlLogin ( ) {
providerId := c . Input ( ) . Get ( "id" )
2021-12-15 21:38:00 +08:00
relayState := c . Input ( ) . Get ( "relayState" )
2023-04-16 00:36:25 +08:00
authURL , method , err := object . GenerateSamlRequest ( providerId , relayState , c . Ctx . Request . Host , c . GetAcceptLanguage ( ) )
2021-12-06 21:46:50 +08:00
if err != nil {
c . ResponseError ( err . Error ( ) )
}
2021-12-15 21:38:00 +08:00
c . ResponseOk ( authURL , method )
2021-12-06 21:46:50 +08:00
}
func ( c * ApiController ) HandleSamlLogin ( ) {
relayState := c . Input ( ) . Get ( "RelayState" )
samlResponse := c . Input ( ) . Get ( "SAMLResponse" )
2021-12-10 00:23:04 +08:00
decode , err := base64 . StdEncoding . DecodeString ( relayState )
if err != nil {
c . ResponseError ( err . Error ( ) )
}
slice := strings . Split ( string ( decode ) , "&" )
relayState = url . QueryEscape ( relayState )
2021-12-06 21:46:50 +08:00
samlResponse = url . QueryEscape ( samlResponse )
2021-12-10 00:23:04 +08:00
targetUrl := fmt . Sprintf ( "%s?relayState=%s&samlResponse=%s" ,
slice [ 4 ] , relayState , samlResponse )
2021-12-06 21:46:50 +08:00
c . Redirect ( targetUrl , 303 )
}
2022-11-13 15:05:15 +08:00
// HandleOfficialAccountEvent ...
// @Tag HandleOfficialAccountEvent API
// @Title HandleOfficialAccountEvent
// @router /api/webhook [POST]
func ( c * ApiController ) HandleOfficialAccountEvent ( ) {
respBytes , err := ioutil . ReadAll ( c . Ctx . Request . Body )
if err != nil {
2023-06-27 20:33:47 +07:00
c . ResponseError ( err . Error ( ) )
return
2022-11-13 15:05:15 +08:00
}
2023-05-30 15:49:39 +08:00
2022-11-13 15:05:15 +08:00
var data struct {
MsgType string ` xml:"MsgType" `
Event string ` xml:"Event" `
EventKey string ` xml:"EventKey" `
}
err = xml . Unmarshal ( respBytes , & data )
if err != nil {
2023-06-27 20:33:47 +07:00
c . ResponseError ( err . Error ( ) )
return
2022-11-13 15:05:15 +08:00
}
2023-05-30 15:49:39 +08:00
2022-11-13 15:05:15 +08:00
lock . Lock ( )
defer lock . Unlock ( )
if data . EventKey != "" {
wechatScanType = data . Event
c . Ctx . WriteString ( "" )
}
}
// GetWebhookEventType ...
// @Tag GetWebhookEventType API
// @Title GetWebhookEventType
// @router /api/get-webhook-event [GET]
func ( c * ApiController ) GetWebhookEventType ( ) {
lock . Lock ( )
defer lock . Unlock ( )
resp := & Response {
Status : "ok" ,
Msg : "" ,
Data : wechatScanType ,
}
c . Data [ "json" ] = resp
wechatScanType = ""
c . ServeJSON ( )
}
2023-04-22 16:16:25 +08:00
// GetCaptchaStatus
// @Title GetCaptchaStatus
// @Tag Token API
// @Description Get Login Error Counts
// @Param id query string true "The id ( owner/name ) of user"
// @Success 200 {object} controllers.Response The Response object
// @router /api/get-captcha-status [get]
func ( c * ApiController ) GetCaptchaStatus ( ) {
organization := c . Input ( ) . Get ( "organization" )
userId := c . Input ( ) . Get ( "user_id" )
2023-05-30 15:49:39 +08:00
user , err := object . GetUserByFields ( organization , userId )
if err != nil {
c . ResponseError ( err . Error ( ) )
return
}
2023-04-22 16:16:25 +08:00
var captchaEnabled bool
if user != nil && user . SigninWrongTimes >= object . SigninWrongTimesLimit {
captchaEnabled = true
}
c . ResponseOk ( captchaEnabled )
}
2023-09-18 15:42:00 +08:00
// Callback
// @Title Callback
// @Tag Callback API
// @Description Get Login Error Counts
// @router /api/Callback [post]
func ( c * ApiController ) Callback ( ) {
code := c . GetString ( "code" )
state := c . GetString ( "state" )
frontendCallbackUrl := fmt . Sprintf ( "/callback?code=%s&state=%s" , code , state )
c . Ctx . Redirect ( http . StatusFound , frontendCallbackUrl )
}