diff --git a/idp/kwai.go b/idp/kwai.go new file mode 100644 index 00000000..a70ecc32 --- /dev/null +++ b/idp/kwai.go @@ -0,0 +1,161 @@ +// Copyright 2024 The Casdoor 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 idp + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + "time" + + "golang.org/x/oauth2" +) + +type KwaiIdProvider struct { + Client *http.Client + Config *oauth2.Config +} + +func NewKwaiIdProvider(clientId string, clientSecret string, redirectUrl string) *KwaiIdProvider { + idp := &KwaiIdProvider{} + idp.Config = idp.getConfig(clientId, clientSecret, redirectUrl) + return idp +} + +func (idp *KwaiIdProvider) SetHttpClient(client *http.Client) { + idp.Client = client +} + +func (idp *KwaiIdProvider) getConfig(clientId string, clientSecret string, redirectUrl string) *oauth2.Config { + endpoint := oauth2.Endpoint{ + TokenURL: "https://open.kuaishou.com/oauth2/access_token", + AuthURL: "https://open.kuaishou.com/oauth2/authorize", // qr code: /oauth2/connect + } + + config := &oauth2.Config{ + Scopes: []string{"user_info"}, + Endpoint: endpoint, + ClientID: clientId, + ClientSecret: clientSecret, + RedirectURL: redirectUrl, + } + + return config +} + +type KwaiTokenResp struct { + Result int `json:"result"` + ErrorMsg string `json:"error_msg"` + AccessToken string `json:"access_token"` + ExpiresIn int `json:"expires_in"` + RefreshToken string `json:"refresh_token"` + RefreshTokenExpiresIn int `json:"refresh_token_expires_in"` + OpenId string `json:"open_id"` + Scopes []string `json:"scopes"` +} + +// GetToken use code to get access_token +func (idp *KwaiIdProvider) GetToken(code string) (*oauth2.Token, error) { + params := map[string]string{ + "app_id": idp.Config.ClientID, + "app_secret": idp.Config.ClientSecret, + "code": code, + "grant_type": "authorization_code", + } + tokenUrl := fmt.Sprintf("%s?app_id=%s&app_secret=%s&code=%s&grant_type=authorization_code", + idp.Config.Endpoint.TokenURL, params["app_id"], params["app_secret"], params["code"]) + resp, err := idp.Client.Get(tokenUrl) + if err != nil { + return nil, err + } + defer resp.Body.Close() + body, err := io.ReadAll(resp.Body) + if err != nil { + return nil, err + } + var tokenResp KwaiTokenResp + err = json.Unmarshal(body, &tokenResp) + if err != nil { + return nil, err + } + if tokenResp.Result != 1 { + return nil, fmt.Errorf("get token error: %s", tokenResp.ErrorMsg) + } + + token := &oauth2.Token{ + AccessToken: tokenResp.AccessToken, + RefreshToken: tokenResp.RefreshToken, + Expiry: time.Now().Add(time.Duration(tokenResp.ExpiresIn) * time.Second), + } + + raw := make(map[string]interface{}) + raw["open_id"] = tokenResp.OpenId + token = token.WithExtra(raw) + + return token, nil +} + +// More details: https://open.kuaishou.com/openapi/user_info +type KwaiUserInfo struct { + Result int `json:"result"` + ErrorMsg string `json:"error_msg"` + UserInfo struct { + Head string `json:"head"` + Name string `json:"name"` + Sex string `json:"sex"` + City string `json:"city"` + } `json:"user_info"` +} + +// GetUserInfo use token to get user profile +func (idp *KwaiIdProvider) GetUserInfo(token *oauth2.Token) (*UserInfo, error) { + userInfoUrl := fmt.Sprintf("https://open.kuaishou.com/openapi/user_info?app_id=%s&access_token=%s", + idp.Config.ClientID, token.AccessToken) + + resp, err := idp.Client.Get(userInfoUrl) + if err != nil { + return nil, err + } + defer resp.Body.Close() + + body, err := io.ReadAll(resp.Body) + if err != nil { + return nil, err + } + + var kwaiUserInfo KwaiUserInfo + err = json.Unmarshal(body, &kwaiUserInfo) + if err != nil { + return nil, err + } + + if kwaiUserInfo.Result != 1 { + return nil, fmt.Errorf("get user info error: %s", kwaiUserInfo.ErrorMsg) + } + + userInfo := &UserInfo{ + Id: token.Extra("open_id").(string), + Username: kwaiUserInfo.UserInfo.Name, + DisplayName: kwaiUserInfo.UserInfo.Name, + AvatarUrl: kwaiUserInfo.UserInfo.Head, + Extra: map[string]string{ + "gender": kwaiUserInfo.UserInfo.Sex, + "city": kwaiUserInfo.UserInfo.City, + }, + } + + return userInfo, nil +} diff --git a/idp/provider.go b/idp/provider.go index 959d85cf..a858414b 100644 --- a/idp/provider.go +++ b/idp/provider.go @@ -113,6 +113,8 @@ func GetIdProvider(idpInfo *ProviderInfo, redirectUrl string) (IdProvider, error return NewOktaIdProvider(idpInfo.ClientId, idpInfo.ClientSecret, redirectUrl, idpInfo.HostUrl), nil case "Douyin": return NewDouyinIdProvider(idpInfo.ClientId, idpInfo.ClientSecret, redirectUrl), nil + case "Kwai": + return NewKwaiIdProvider(idpInfo.ClientId, idpInfo.ClientSecret, redirectUrl), nil case "Bilibili": return NewBilibiliIdProvider(idpInfo.ClientId, idpInfo.ClientSecret, redirectUrl), nil case "MetaMask": diff --git a/object/user.go b/object/user.go index fcd6482c..3b01cde6 100644 --- a/object/user.go +++ b/object/user.go @@ -129,6 +129,7 @@ type User struct { Bilibili string `xorm:"bilibili varchar(100)" json:"bilibili"` Okta string `xorm:"okta varchar(100)" json:"okta"` Douyin string `xorm:"douyin varchar(100)" json:"douyin"` + Kwai string `xorm:"kwai varchar(100)" json:"kwai"` Line string `xorm:"line varchar(100)" json:"line"` Amazon string `xorm:"amazon varchar(100)" json:"amazon"` Auth0 string `xorm:"auth0 varchar(100)" json:"auth0"` @@ -698,7 +699,7 @@ func UpdateUser(id string, user *User, columns []string, isAdmin bool) (bool, er "is_admin", "is_forbidden", "is_deleted", "hash", "is_default_avatar", "properties", "webauthnCredentials", "managedAccounts", "face_ids", "mfaAccounts", "signin_wrong_times", "last_change_password_time", "last_signin_wrong_time", "groups", "access_key", "access_secret", "mfa_phone_enabled", "mfa_email_enabled", "github", "google", "qq", "wechat", "facebook", "dingtalk", "weibo", "gitee", "linkedin", "wecom", "lark", "gitlab", "adfs", - "baidu", "alipay", "casdoor", "infoflow", "apple", "azuread", "azureadb2c", "slack", "steam", "bilibili", "okta", "douyin", "line", "amazon", + "baidu", "alipay", "casdoor", "infoflow", "apple", "azuread", "azureadb2c", "slack", "steam", "bilibili", "okta", "douyin", "kwai", "line", "amazon", "auth0", "battlenet", "bitbucket", "box", "cloudfoundry", "dailymotion", "deezer", "digitalocean", "discord", "dropbox", "eveonline", "fitbit", "gitea", "heroku", "influxcloud", "instagram", "intercom", "kakao", "lastfm", "mailru", "meetup", "microsoftonline", "naver", "nextcloud", "onedrive", "oura", "patreon", "paypal", "salesforce", "shopify", "soundcloud", diff --git a/swagger/swagger.json b/swagger/swagger.json index b54d5f8f..10acdf1f 100644 --- a/swagger/swagger.json +++ b/swagger/swagger.json @@ -7558,6 +7558,9 @@ "type": "integer", "format": "int64" }, + "kwai": { + "type": "string" + }, "language": { "type": "string" }, diff --git a/swagger/swagger.yml b/swagger/swagger.yml index 2095501c..a408db8e 100644 --- a/swagger/swagger.yml +++ b/swagger/swagger.yml @@ -4981,6 +4981,8 @@ definitions: karma: type: integer format: int64 + kwai: + type: string language: type: string lark: diff --git a/web/src/Setting.js b/web/src/Setting.js index 47be88a9..e1991ead 100644 --- a/web/src/Setting.js +++ b/web/src/Setting.js @@ -985,6 +985,7 @@ export function getProviderTypeOptions(category) { {id: "Bilibili", name: "Bilibili"}, {id: "Okta", name: "Okta"}, {id: "Douyin", name: "Douyin"}, + {id: "Kwai", name: "Kwai"}, {id: "Line", name: "Line"}, {id: "Amazon", name: "Amazon"}, {id: "Auth0", name: "Auth0"}, diff --git a/web/src/auth/KwaiLoginButton.js b/web/src/auth/KwaiLoginButton.js new file mode 100644 index 00000000..a572af71 --- /dev/null +++ b/web/src/auth/KwaiLoginButton.js @@ -0,0 +1,31 @@ +// Copyright 2024 The Casdoor 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. + +import {createButton} from "react-social-login-buttons"; +import {StaticBaseUrl} from "../Setting"; + +function Icon({width = 24, height = 24}) { + return Sign in with Kwai; +} + +const config = { + text: "Sign in with Kwai", + icon: Icon, + style: {background: "#ffffff", color: "#000000"}, + activeStyle: {background: "#ededee"}, +}; + +const KwaiLoginButton = createButton(config); + +export default KwaiLoginButton; diff --git a/web/src/auth/Provider.js b/web/src/auth/Provider.js index 4f5938df..b86b05bc 100644 --- a/web/src/auth/Provider.js +++ b/web/src/auth/Provider.js @@ -119,6 +119,10 @@ const authInfo = { scope: "user_info", endpoint: "https://open.douyin.com/platform/oauth/connect", }, + Kwai: { + scope: "user_info", + endpoint: "https://open.kuaishou.com/oauth2/connect", + }, Custom: { endpoint: "https://example.com/", }, @@ -470,6 +474,8 @@ export function getAuthUrl(application, provider, method, code) { return `${provider.domain}/v1/authorize?client_id=${provider.clientId}&redirect_uri=${redirectUri}&state=${state}&response_type=code&scope=${scope}`; } else if (provider.type === "Douyin" || provider.type === "TikTok") { return `${endpoint}?client_key=${provider.clientId}&redirect_uri=${redirectUri}&state=${state}&response_type=code&scope=${scope}`; + } else if (provider.type === "Kwai") { + return `${endpoint}?app_id=${provider.clientId}&redirect_uri=${redirectUri}&state=${state}&response_type=code&scope=${scope}`; } else if (provider.type === "Custom") { return `${provider.customAuthUrl}?client_id=${provider.clientId}&redirect_uri=${redirectUri}&scope=${provider.scopes}&response_type=code&state=${state}`; } else if (provider.type === "Bilibili") { diff --git a/web/src/auth/ProviderButton.js b/web/src/auth/ProviderButton.js index 4d4ee86c..1e1323b9 100644 --- a/web/src/auth/ProviderButton.js +++ b/web/src/auth/ProviderButton.js @@ -40,6 +40,7 @@ import SteamLoginButton from "./SteamLoginButton"; import BilibiliLoginButton from "./BilibiliLoginButton"; import OktaLoginButton from "./OktaLoginButton"; import DouyinLoginButton from "./DouyinLoginButton"; +import KwaiLoginButton from "./KwaiLoginButton"; import LoginButton from "./LoginButton"; import * as AuthBackend from "./AuthBackend"; import {WechatOfficialAccountModal} from "./Util"; @@ -96,6 +97,8 @@ function getSigninButton(provider) { return ; } else if (provider.type === "Douyin") { return ; + } else if (provider.type === "Kwai") { + return ; } else { return ; }