Add github oauth.

This commit is contained in:
Yang Luo 2021-02-14 00:22:24 +08:00
parent ea09beffe2
commit c81118feff
14 changed files with 419 additions and 8 deletions

View File

@ -3,4 +3,5 @@ httpport = 8000
runmode = dev
SessionOn = true
copyrequestbody = true
dataSourceName = root:123@tcp(localhost:3306)/
dataSourceName = root:123@tcp(localhost:3306)/
AuthState = "casdoor"

180
controllers/auth_github.go Normal file
View File

@ -0,0 +1,180 @@
// Copyright 2020 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 (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"sync"
"github.com/astaxie/beego"
"github.com/casdoor/casdoor/object"
"github.com/casdoor/casdoor/util"
"golang.org/x/oauth2"
)
var githubEndpoint = oauth2.Endpoint{
AuthURL: "https://github.com/login/oauth/authorize",
TokenURL: "https://github.com/login/oauth/access_token",
}
var githubOauthConfig = &oauth2.Config{
ClientID: beego.AppConfig.String("GithubAuthClientID"),
ClientSecret: beego.AppConfig.String("GithubAuthClientSecret"),
RedirectURL: "",
Scopes: []string{"user:email", "read:user"},
Endpoint: githubEndpoint,
}
func (c *ApiController) AuthGithub() {
providerName := c.Input().Get("provider")
code := c.Input().Get("code")
state := c.Input().Get("state")
addition := c.Input().Get("addition")
RedirectURL := c.Input().Get("redirect_url")
provider := object.GetProvider(fmt.Sprintf("admin/%s", providerName))
githubOauthConfig.ClientID = provider.ClientId
githubOauthConfig.ClientSecret = provider.ClientSecret
var resp Response
var res authResponse
res.IsAuthenticated = true
if state != beego.AppConfig.String("AuthState") {
res.IsAuthenticated = false
resp = Response{Status: "fail", Msg: "unauthorized", Data: res}
c.ServeJSON()
return
}
githubOauthConfig.RedirectURL = RedirectURL
// https://github.com/golang/oauth2/issues/123#issuecomment-103715338
ctx := context.WithValue(oauth2.NoContext, oauth2.HTTPClient, httpClient)
token, err := githubOauthConfig.Exchange(ctx, code)
if err != nil {
res.IsAuthenticated = false
panic(err)
}
if !token.Valid() {
resp = Response{Status: "fail", Msg: "unauthorized", Data: res}
c.Data["json"] = resp
c.ServeJSON()
return
}
var wg sync.WaitGroup
var tempUserEmail []userEmailFromGithub
var tempUserAccount userInfoFromGithub
wg.Add(2)
go func() {
req, err := http.NewRequest("GET", "https://api.github.com/user/emails", nil)
if err != nil {
panic(err)
}
req.Header.Add("Authorization", "token " + token.AccessToken)
response, err := httpClient.Do(req)
if err != nil {
panic(err)
}
defer response.Body.Close()
contents, err := ioutil.ReadAll(response.Body)
err = json.Unmarshal(contents, &tempUserEmail)
if err != nil {
res.IsAuthenticated = false
panic(err)
}
for _, v := range tempUserEmail {
if v.Primary == true {
res.Email = v.Email
break
}
}
wg.Done()
}()
go func() {
req, err := http.NewRequest("GET", "https://api.github.com/user", nil)
if err != nil {
panic(err)
}
req.Header.Add("Authorization", "token " + token.AccessToken)
response2, err := httpClient.Do(req)
if err != nil {
panic(err)
}
defer response2.Body.Close()
contents2, err := ioutil.ReadAll(response2.Body)
err = json.Unmarshal(contents2, &tempUserAccount)
if err != nil {
res.IsAuthenticated = false
panic(err)
}
wg.Done()
}()
wg.Wait()
if addition == "signup" {
userId := object.HasGithub(tempUserAccount.Login)
if userId != "" {
//if len(object.GetMemberAvatar(userId)) == 0 {
// avatar := UploadAvatarToOSS(tempUserAccount.AvatarUrl, userId)
// object.LinkMemberAccount(userId, "avatar", avatar)
//}
c.SetSessionUser(userId)
util.LogInfo(c.Ctx, "API: [%s] signed in", userId)
res.IsSignedUp = true
} else {
if userId := object.HasMail(res.Email); userId != "" {
c.SetSessionUser(userId)
util.LogInfo(c.Ctx, "API: [%s] signed in", userId)
res.IsSignedUp = true
_ = object.LinkUserAccount(userId, "github", tempUserAccount.Login)
} else {
res.IsSignedUp = false
}
}
res.Addition = tempUserAccount.Login
res.Avatar = tempUserAccount.AvatarUrl
resp = Response{Status: "ok", Msg: "success", Data: res}
} else {
memberId := c.GetSessionUser()
if memberId == "" {
resp = Response{Status: "fail", Msg: "no account exist", Data: res}
c.Data["json"] = resp
c.ServeJSON()
return
}
linkRes := object.LinkUserAccount(memberId, "github_account", tempUserAccount.Login)
if linkRes {
resp = Response{Status: "ok", Msg: "success", Data: linkRes}
} else {
resp = Response{Status: "fail", Msg: "link account failed", Data: linkRes}
}
//if len(object.GetMemberAvatar(memberId)) == 0 {
// avatar := UploadAvatarToOSS(tempUserAccount.AvatarUrl, memberId)
// object.LinkUserAccount(memberId, "avatar", avatar)
//}
}
c.Data["json"] = resp
c.ServeJSON()
}

35
controllers/type.go Normal file
View File

@ -0,0 +1,35 @@
// Copyright 2021 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
type userEmailFromGithub struct {
Email string `json:"email"`
Primary bool `json:"primary"`
Verified bool `json:"verified"`
Visibility string `json:"visibility"`
}
type userInfoFromGithub struct {
Login string `json:"login"`
AvatarUrl string `json:"avatar_url"`
}
type authResponse struct {
IsAuthenticated bool `json:"isAuthenticated"`
IsSignedUp bool `json:"isSignedUp"`
Email string `json:"email"`
Avatar string `json:"avatar"`
Addition string `json:"addition"`
}

50
controllers/util.go Normal file
View File

@ -0,0 +1,50 @@
// Copyright 2021 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 (
"net/http"
"golang.org/x/net/proxy"
)
var httpClient *http.Client
var UseOAuthProxy = true
func InitHttpClient() {
if !UseOAuthProxy {
httpClient = &http.Client{}
return
}
// https://stackoverflow.com/questions/33585587/creating-a-go-socks5-client
proxyAddress := "127.0.0.1:10808"
dialer, err := proxy.SOCKS5("tcp", proxyAddress, nil, proxy.Direct)
if err != nil {
panic(err)
}
tr := &http.Transport{Dial: dialer.Dial}
httpClient = &http.Client{
Transport: tr,
}
//resp, err2 := httpClient.Get("https://google.com")
//if err2 != nil {
// panic(err2)
//}
//defer resp.Body.Close()
//println("Response status: %s", resp.Status)
}

2
go.mod
View File

@ -6,6 +6,8 @@ require (
github.com/astaxie/beego v1.12.2
github.com/go-sql-driver/mysql v1.5.0
github.com/google/uuid v1.2.0
golang.org/x/net v0.0.0-20190620200207-3b0461eec859
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421
xorm.io/core v0.7.2
xorm.io/xorm v0.8.1
)

1
go.sum
View File

@ -197,6 +197,7 @@ golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLL
golang.org/x/net v0.0.0-20190620200207-3b0461eec859 h1:R/3boaszxrf1GEUWTVDzSKVwLmSJpwZ1yqXm8j0v2QI=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421 h1:Wo7BWFiOk0QRFMLYMqJGFMd9CgUAcGx7V+qEg/h5IBI=
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
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=

View File

@ -17,6 +17,7 @@ package main
import (
"github.com/astaxie/beego"
"github.com/astaxie/beego/plugins/cors"
"github.com/casdoor/casdoor/controllers"
"github.com/casdoor/casdoor/object"
"github.com/casdoor/casdoor/routers"
@ -25,6 +26,7 @@ import (
func main() {
object.InitAdapter()
controllers.InitHttpClient()
beego.InsertFilter("*", beego.BeforeRouter, cors.Allow(&cors.Options{
AllowOrigins: []string{"*"},

View File

@ -21,3 +21,19 @@ func CheckUserLogin(userId string, password string) string {
return ""
}
func HasMail(email string) string {
user := GetMail(email)
if user != nil {
return user.Email
}
return ""
}
func HasGithub(github string) string {
user := GetGithub(github)
if user != nil {
return user.Github
}
return ""
}

View File

@ -31,6 +31,8 @@ type User struct {
Avatar string `xorm:"varchar(100)" json:"avatar"`
Email string `xorm:"varchar(100)" json:"email"`
Phone string `xorm:"varchar(100)" json:"phone"`
Github string `xorm:"varchar(100)" json:"github"`
}
func GetGlobalUsers() []*User {
@ -114,3 +116,40 @@ func DeleteUser(user *User) bool {
return affected != 0
}
func GetMail(email string) *User {
user := User{Email: email}
existed, err := adapter.engine.Get(&user)
if err != nil {
panic(err)
}
if existed {
return &user
} else {
return nil
}
}
func GetGithub(github string) *User {
user := User{Github: github}
existed, err := adapter.engine.Get(&user)
if err != nil {
panic(err)
}
if existed {
return &user
} else {
return nil
}
}
func LinkUserAccount(user, field, value string) bool {
affected, err := adapter.engine.Table(new(User)).ID(user).Update(map[string]interface{}{field: value})
if err != nil {
panic(err)
}
return affected != 0
}

View File

@ -37,6 +37,7 @@ func initAPI() {
beego.Router("/api/login", &controllers.ApiController{}, "POST:Login")
beego.Router("/api/logout", &controllers.ApiController{}, "POST:Logout")
beego.Router("/api/get-account", &controllers.ApiController{}, "GET:GetAccount")
beego.Router("/api/auth/github", &controllers.ApiController{}, "GET:AuthGithub")
beego.Router("/api/get-organizations", &controllers.ApiController{}, "GET:GetOrganizations")
beego.Router("/api/get-organization", &controllers.ApiController{}, "GET:GetOrganization")

View File

@ -32,6 +32,7 @@ import AccountPage from "./account/AccountPage";
import LoginPage from "./account/LoginPage";
import HomePage from "./basic/HomePage";
import CustomGithubCorner from "./CustomGithubCorner";
import CallbackBox from "./common/AuthBox";
const { Header, Footer } = Layout;
@ -155,9 +156,9 @@ class App extends Component {
renderAccount() {
let res = [];
if (this.state.account !== null && this.state.account !== undefined) {
res.push(this.renderRightDropdown());
} else {
if (this.state.account === undefined) {
return null;
} else if (this.state.account === null) {
res.push(
<Menu.Item key="100" style={{float: 'right', marginRight: '20px'}}>
<Link to="/register">
@ -172,6 +173,8 @@ class App extends Component {
</Link>
</Menu.Item>
);
} else {
res.push(this.renderRightDropdown());
}
return res;
@ -271,6 +274,7 @@ class App extends Component {
</Header>
<Switch>
<Route exact path="/login" render={(props) => this.renderHomeIfLoggedIn(<LoginPage onLoggedIn={this.onLoggedIn.bind(this)} {...props} />)}/>
<Route exact path="/callback/:providerType/:providerName/:addition" component={CallbackBox}/>
<Route exact path="/" render={(props) => this.renderLoginIfNotLoggedIn(<HomePage account={this.state.account} onLoggedIn={this.onLoggedIn.bind(this)} {...props} />)}/>
<Route exact path="/account" render={(props) => this.renderLoginIfNotLoggedIn(<AccountPage account={this.state.account} {...props} />)}/>
<Route exact path="/organizations" render={(props) => this.renderLoginIfNotLoggedIn(<OrganizationListPage account={this.state.account} {...props} />)}/>

View File

@ -50,3 +50,11 @@ export function logout() {
credentials: "include",
}).then(res => res.json());
}
export function githubLogin(providerName, code, state, redirectUrl, addition) {
console.log(redirectUrl)
return fetch(`${Setting.ServerUrl}/api/auth/github?provider=${providerName}&code=${code}&state=${state}&redirect_url=${redirectUrl}&addition=${addition}`, {
method: 'GET',
credentials: 'include',
}).then(res => res.json());
}

View File

@ -42,13 +42,14 @@ export function getAuthLogo(provider) {
}
export function getAuthUrl(provider, method) {
const redirectUri = `${Setting.ClientUrl}/callback/${provider.type}/${provider.name}/${method}`;
if (provider.type === "google") {
return `${GoogleAuthUri}?client_id=${provider.clientId}&redirect_uri=${Setting.ClientUrl}/callback/google/${method}&scope=${GoogleAuthScope}&response_type=code&state=${AuthState}`;
return `${GoogleAuthUri}?client_id=${provider.clientId}&redirect_uri=${redirectUri}&scope=${GoogleAuthScope}&response_type=code&state=${AuthState}`;
} else if (provider.type === "github") {
return `${GithubAuthUri}?client_id=${provider.clientId}&redirect_uri=${Setting.ClientUrl}/callback/github/${method}&scope=${GithubAuthScope}&response_type=code&state=${AuthState}`;
return `${GithubAuthUri}?client_id=${provider.clientId}&redirect_uri=${redirectUri}&scope=${GithubAuthScope}&response_type=code&state=${AuthState}`;
} else if (provider.type === "qq") {
return `${QqAuthUri}?client_id=${provider.clientId}&redirect_uri=${Setting.ClientUrl}/callback/qq/${method}&scope=${QqAuthScope}&response_type=code&state=${AuthState}`;
return `${QqAuthUri}?client_id=${provider.clientId}&redirect_uri=${redirectUri}&scope=${QqAuthScope}&response_type=code&state=${AuthState}`;
} else if (provider.type === "wechat") {
return `${WeChatAuthUri}?appid=${provider.clientId}&redirect_uri=${Setting.ClientUrl}/callback/wechat/${method}&scope=${WeChatAuthScope}&response_type=code&state=${AuthState}#wechat_redirect`;
return `${WeChatAuthUri}?appid=${provider.clientId}&redirect_uri=${redirectUri}&scope=${WeChatAuthScope}&response_type=code&state=${AuthState}#wechat_redirect`;
}
}

71
web/src/common/AuthBox.js Normal file
View File

@ -0,0 +1,71 @@
// Copyright 2021 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.
import React from "react";
import {withRouter} from "react-router-dom";
import * as Setting from "../Setting";
import * as AccountBackend from "../backend/AccountBackend";
class CallbackBox extends React.Component {
constructor(props) {
super(props);
this.state = {
classes: props,
providerType: props.match.params.providerType,
providerName: props.match.params.providerName,
addition: props.match.params.addition,
state: "",
code: "",
isAuthenticated: false,
isSignedUp: false,
email: ""
};
const params = new URLSearchParams(this.props.location.search);
this.state.code = params.get("code");
this.state.state = params.get("state");
}
getAuthenticatedInfo() {
let redirectUrl;
redirectUrl = `${Setting.ClientUrl}/callback/${this.state.providerType}/${this.state.providerName}/${this.state.addition}`;
switch (this.state.providerType) {
case "github":
AccountBackend.githubLogin(this.state.providerName, this.state.code, this.state.state, redirectUrl, this.state.addition)
.then((res) => {
if (res.status === "ok") {
window.location.href = '/';
}else {
Setting.showMessage("error", res?.msg);
}
});
break;
}
}
componentDidMount() {
this.getAuthenticatedInfo();
}
render() {
return (
<div>
<h3>
Logging in ...
</h3>
</div>
)
}
}
export default withRouter(CallbackBox);