Skip to content

Commit

Permalink
add oauth support
Browse files Browse the repository at this point in the history
Signed-off-by: yxxhero <aiopsclub@163.com>
  • Loading branch information
yxxhero authored and gaius-qi committed Aug 31, 2021
1 parent c955317 commit 9047f42
Show file tree
Hide file tree
Showing 14 changed files with 510 additions and 2 deletions.
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ require (
go.uber.org/atomic v1.6.0
go.uber.org/zap v1.16.0
golang.org/x/crypto v0.0.0-20210616213533-5ff15b29337e
golang.org/x/oauth2 v0.0.0-20210805134026-6f1e6394065a
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c
golang.org/x/time v0.0.0-20201208040808-7e3f01d25324
Expand Down
3 changes: 2 additions & 1 deletion go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -977,8 +977,9 @@ golang.org/x/oauth2 v0.0.0-20200902213428-5d25da1a8d43/go.mod h1:KelEdhl1UZF7XfJ
golang.org/x/oauth2 v0.0.0-20201109201403-9fd604954f58/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A=
golang.org/x/oauth2 v0.0.0-20201208152858-08078c50e5b5/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A=
golang.org/x/oauth2 v0.0.0-20210113205817-d3ed898aa8a3/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A=
golang.org/x/oauth2 v0.0.0-20210201163806-010130855d6c h1:HiAZXo96zOhVhtFHchj/ojzoxCFiPrp9/j0GtS38V3g=
golang.org/x/oauth2 v0.0.0-20210201163806-010130855d6c/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A=
golang.org/x/oauth2 v0.0.0-20210805134026-6f1e6394065a h1:4Kd8OPUx1xgUwrHDaviWZO8MsgoZTZYC3g+8m16RBww=
golang.org/x/oauth2 v0.0.0-20210805134026-6f1e6394065a/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A=
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=
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
Expand Down
1 change: 1 addition & 0 deletions manager/database/database.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ func migrate(db *gorm.DB) error {
&model.Scheduler{},
&model.SecurityGroup{},
&model.User{},
&model.Settings{},
)
}

Expand Down
225 changes: 225 additions & 0 deletions manager/handlers/oauth.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,225 @@
package handlers

import (
"net/http"

"d7y.io/dragonfly/v2/manager/types"
jwt "github.com/appleboy/gin-jwt/v2"
"github.com/gin-gonic/gin"
)

// @Summary Create Oauth
// @Description create by json config
// @Tags Oauth
// @Accept json
// @Produce json
// @Param Oauth body types.CreateOauthRequest true "Oauth"
// @Success 200 {object} model.Oauth
// @Failure 400 {object} HTTPError
// @Failure 404 {object} HTTPError
// @Failure 500 {object} HTTPError
// @Router /oauths [post]
func (h *Handlers) CreateOauth(ctx *gin.Context) {
var json types.CreateOauthRequest
if err := ctx.ShouldBindJSON(&json); err != nil {
ctx.JSON(http.StatusUnprocessableEntity, gin.H{"errors": err.Error()})
return
}

oauth, err := h.Service.CreateOauth(json)
if err != nil {
ctx.Error(err)
return
}

ctx.JSON(http.StatusOK, oauth)
}

// @Summary Destroy Oauth
// @Description Destroy by id
// @Tags Oauth
// @Accept json
// @Produce json
// @Param id path string true "id"
// @Success 200
// @Failure 400 {object} HTTPError
// @Failure 404 {object} HTTPError
// @Failure 500 {object} HTTPError
// @Router /oauths/{id} [delete]
func (h *Handlers) DestroyOauth(ctx *gin.Context) {
var params types.OauthParams
if err := ctx.ShouldBindUri(&params); err != nil {
ctx.JSON(http.StatusUnprocessableEntity, gin.H{"errors": err.Error()})
return
}

err := h.Service.DestroyOauth(params.ID)
if err != nil {
ctx.Error(err)
return
}

ctx.Status(http.StatusOK)
}

// @Summary start oauth signin
// @Description start oauth signin
// @Tags Oauth
// @Accept json
// @Produce json
// @Param oauth_name path string true "oauth_name"
// @Success 200
// @Failure 400 {object} HTTPError
// @Failure 404 {object} HTTPError
// @Failure 500 {object} HTTPError
// @Router /{oauth_name}/sigin [get]
func (h *Handlers) OauthSignin(ctx *gin.Context) {
var params types.OauthPathParams
if err := ctx.ShouldBindUri(&params); err != nil {
ctx.JSON(http.StatusUnprocessableEntity, gin.H{"errors": err.Error()})
return
}

oauthURL, err := h.Service.OauthSignin(params.OauthName)
if err != nil {
ctx.Error(err)
return
}
ctx.Redirect(http.StatusMovedPermanently, oauthURL)
}

// @Summary start oauth callback
// @Description start oauth callback
// @Tags Oauth
// @Param oauth_name path string true "oauth_name"
// @Param code query string true "code"
// @Success 200
// @Failure 400 {object} HTTPError
// @Failure 404 {object} HTTPError
// @Failure 500 {object} HTTPError
// @Router /{oauth_name}/callback [get]
func (h *Handlers) OauthCallback(j *jwt.GinJWTMiddleware) func(*gin.Context) {
return func(ctx *gin.Context) {
var params types.OauthPathParams
if err := ctx.ShouldBindUri(&params); err != nil {
ctx.JSON(http.StatusUnprocessableEntity, gin.H{"errors": err.Error()})
return
}

code := ctx.Query("code")
if code == "" {
ctx.JSON(http.StatusUnprocessableEntity, gin.H{"errors": "code is required"})
return
}

user, err := h.Service.OauthCallback(params.OauthName, code)
if err != nil {
ctx.Error(err)
return
}
jwtToken, _, err := j.TokenGenerator(user)
if err != nil {
ctx.Error(err)
return
}
ctx.SetCookie("jwt", jwtToken, 600, "", "", false, true)
ctx.Redirect(http.StatusMovedPermanently, "/")
}
}

// @Summary Update Oauth
// @Description Update by json config
// @Tags Oauth
// @Accept json
// @Produce json
// @Param id path string true "id"
// @Param Oauth body types.UpdateOauthRequest true "Oauth"
// @Success 200 {object} model.Oauth
// @Failure 400 {object} HTTPError
// @Failure 404 {object} HTTPError
// @Failure 500 {object} HTTPError
// @Router /oauths/{id} [patch]
func (h *Handlers) UpdateOauth(ctx *gin.Context) {
var params types.OauthParams
if err := ctx.ShouldBindUri(&params); err != nil {
ctx.Error(err)
return
}

var json types.UpdateOauthRequest
if err := ctx.ShouldBindJSON(&json); err != nil {
ctx.Error(err)
return
}

oauth, err := h.Service.UpdateOauth(params.ID, json)
if err != nil {
ctx.Error(err)
return
}

ctx.JSON(http.StatusOK, oauth)
}

// @Summary Get Oauth
// @Description Get Oauth by id
// @Tags Oauth
// @Accept json
// @Produce json
// @Param id path string true "id"
// @Success 200 {object} model.Oauth
// @Failure 400 {object} HTTPError
// @Failure 404 {object} HTTPError
// @Failure 500 {object} HTTPError
// @Router /oauths/{id} [get]
func (h *Handlers) GetOauth(ctx *gin.Context) {
var params types.OauthParams
if err := ctx.ShouldBindUri(&params); err != nil {
ctx.JSON(http.StatusUnprocessableEntity, gin.H{"errors": err.Error()})
return
}

oauth, err := h.Service.GetOauth(params.ID)
if err != nil {
ctx.Error(err)
return
}

ctx.JSON(http.StatusOK, oauth)
}

// @Summary Get Oauths
// @Description Get Oauths
// @Tags Oauth
// @Accept json
// @Produce json
// @Param page query int true "current page" default(0)
// @Param per_page query int true "return max item count, default 10, max 50" default(10) minimum(2) maximum(50)
// @Success 200 {object} []model.Oauth
// @Failure 400 {object} HTTPError
// @Failure 404 {object} HTTPError
// @Failure 500 {object} HTTPError
// @Router /oauths [get]
func (h *Handlers) GetOauths(ctx *gin.Context) {
var query types.GetOauthsQuery
if err := ctx.ShouldBindQuery(&query); err != nil {
ctx.JSON(http.StatusUnprocessableEntity, gin.H{"errors": err.Error()})
return
}

h.setPaginationDefault(&query.Page, &query.PerPage)
oauths, err := h.Service.GetOauths(query)
if err != nil {
ctx.Error(err)
return
}

totalCount, err := h.Service.OauthTotalCount(query)
if err != nil {
ctx.Error(err)
return
}

h.setPaginationLinkHeader(ctx, query.Page, query.PerPage, int(totalCount))
ctx.JSON(http.StatusOK, oauths)
}
2 changes: 1 addition & 1 deletion manager/middlewares/jwt.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ func Jwt(service service.REST) (*jwt.GinJWTMiddleware, error) {
})
},

TokenLookup: "header: Authorization, query: token, cookie: jwt",
TokenLookup: "header: Authorization, cookie: jwt, query: token",
TokenHeadName: "Bearer",
TimeFunc: time.Now,
SendCookie: true,
Expand Down
13 changes: 13 additions & 0 deletions manager/model/oauth.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package model

type Oauth struct {
Model
Name string `gorm:"column:name;type:varchar(256);index:unique;not null;comment:oauth name" json:"name"`
ClientID string `gorm:"column:client_id;type:varchar(256);index:unique;not null;comment:client id for oauth" json:"client_id"`
ClientSecret string `gorm:"column:client_secret;type:varchar(1024);comment:client secret for oauth" json:"client_secret"`
// scope list split by ','
Scopes string `gorm:"column:scopes;type:varchar(1024);comment:scopes" json:"scopes"`
UserInfoURL string `gorm:"column:user_info_url;type:varchar(256);not null;comment:user info url" json:"user_info_url"`
AuthURL string `gorm:"column:auth_url;type:varchar(256);not null;comment:auth url" json:"auth_url"`
TokenURL string `gorm:"column:token_url;type:varchar(256);not null;comment:token url" json:"token_url"`
}
7 changes: 7 additions & 0 deletions manager/model/settings.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package model

type Settings struct {
Model
Key string `gorm:"column:key;type:varchar(256);index:unique;not null;comment: setting key" json:"key"`
Value string `gorm:"column:value;type:varchar(256);not null;comment: setting value" json:"value"`
}
1 change: 1 addition & 0 deletions manager/oauth/github.go
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
package oauth
27 changes: 27 additions & 0 deletions manager/oauth/google.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package oauth
import (
"golang.org/x/oauth2/google"
)

type googleOauth2 struct {
oauth2
}

func NewGoogle(name string, clientID string, clientSecret string, scopes string, authURL string, tokenURL string, db *gorm.DB) (*oauth, error) {

oa := &googleOauth2{
Name: name,
Config: &oauth2.Config{
ClientID: clientID,
ClientSecret: clientSecret,
Scopes: strings.Split(scopes, ","),
Endpoint: google.
},
}
redirectURL, err := oa.GetRediectURL(db)
if err != nil {
return nil, err
}
oa.Config.RedirectURL = redirectURL
return oa, nil
}
60 changes: 60 additions & 0 deletions manager/oauth/oauth.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package oauth

import (
"fmt"
"strings"

"d7y.io/dragonfly/v2/manager/model"
"golang.org/x/oauth2"
"gorm.io/gorm"
)

type oauth2 struct {
Name string
UserInfoURL string
Config *oauth2.Config
}

// oauth interface
type Oauther interface {
GetRediectURL(*gorm.DB) (string, error)
GetOauthUserInfo(string) (*model.User, error)
}

func NewOauth(name string, clientID string, clientSecret string, scopes string, authURL string, tokenURL string, db *gorm.DB) (*oauth, error) {

oa := &oauth2{
Name: name,
Config: &oauth2.Config{
ClientID: clientID,
ClientSecret: clientSecret,
Scopes: strings.Split(scopes, ","),
Endpoint: oauth2.Endpoint{
AuthURL: authURL,
TokenURL: tokenURL,
},
},
}
redirectURL, err := oa.GetRediectURL(db)
if err != nil {
return nil, err
}
oa.Config.RedirectURL = redirectURL
return oa, nil
}

func (o *oauth2) GetRediectURL(db *gorm.DB) (string, error) {

s := model.Settings{}
if err := db.First(&s, model.Settings{
Key: "server_domain",
}).Error; err != nil {
return "", err
}
return fmt.Sprintf("%s/api/v1/oauth/%s/sigin", s.Value, o.Name), nil
}

func (o *oauth2) GetOauthUserInfo(code string) (*model.User, error) {
user := model.User{}
return &user, nil
}
10 changes: 10 additions & 0 deletions manager/router/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,16 @@ func Init(console bool, verbose bool, publicPath string, service service.REST, e
pn := apiv1.Group("/permissions", jwt.MiddlewareFunc(), rbac)
pn.GET("", h.GetPermissions(r))

// oauth
oa := apiv1.Group("/oauth")
oa.GET("", h.GetOauths)
oa.GET("/:id", h.GetOauth)
oa.DELETE("/:id", h.DestroyOauth)
oa.PUT("/:id", h.UpdateOauth)
oa.POST("", h.CreateOauth)
oa.GET("/:oauth_name/signin", h.OauthSignin)
oa.GET("/:oauth_name/callback", h.OauthCallback(jwt))

// Security Group
sg := apiv1.Group("/security-groups")
sg.POST("", h.CreateSecurityGroup)
Expand Down
Loading

0 comments on commit 9047f42

Please sign in to comment.