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

Integrate OAuth2 Provider #5378

Merged
merged 92 commits into from
Mar 8, 2019
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
Show all changes
92 commits
Select commit Hold shift + click to select a range
fb1bab1
Add oauth2 application
jonasfranz Nov 12, 2018
8b9fb4c
Update index.css
kolaente Nov 12, 2018
4b18995
Merge remote-tracking branch 'origin/master' into feature/oauth2
jonasfranz Nov 19, 2018
8a2e6f1
Add grant and redirection
jonasfranz Nov 20, 2018
6752e1a
Small improvements
jonasfranz Nov 20, 2018
ee833d1
Add documentation and missing vendors
jonasfranz Nov 22, 2018
114cf36
Merge branch 'master' into feature/oauth2
jonasfranz Nov 22, 2018
cabbbd9
Revert unwanted changes
jonasfranz Nov 22, 2018
6c5ddfb
Merge remote-tracking branch 'origin/master' into feature/oauth2
jonasfranz Nov 22, 2018
ccb990a
Merge branch 'feature/oauth2' of github.com:JonasFranzDEV/gitea into …
jonasfranz Nov 22, 2018
04d3420
Merge branch 'feature/oauth2' of github.com:JonasFranzDEV/gitea into …
jonasfranz Nov 24, 2018
de7210f
Add copyright headers
jonasfranz Nov 24, 2018
25793e6
Add access token cleanup cronjob
jonasfranz Nov 24, 2018
e5435ed
Merge branch 'master' of https://github.com/go-gitea/gitea into featu…
jonasfranz Dec 21, 2018
bd311a6
Use JWT tokens instead of "access tokens"
jonasfranz Dec 22, 2018
fd162c1
Fix some lint and documentation problems
jonasfranz Dec 22, 2018
fb2735c
Fix misspells
jonasfranz Dec 22, 2018
0c07b84
Remove unsused access tokens model changes
jonasfranz Dec 22, 2018
51ffa8a
Add auth code invalidation
jonasfranz Dec 22, 2018
0648d41
Ensure gopkg
jonasfranz Dec 22, 2018
3899a2e
Add oauth2 ui
jonasfranz Dec 23, 2018
1d7316c
Check OAuth2 token
jonasfranz Dec 23, 2018
dce746a
Merge branch 'feature/oauth2' into feature/oauth2-ui
jonasfranz Dec 23, 2018
ee44838
Change authorize and access token endpoint
jonasfranz Dec 26, 2018
f8b099a
Merge remote-tracking branch 'jonas/feature/oauth2' into feature/oauth2
jonasfranz Dec 26, 2018
869589e
Merge branch 'feature/oauth2' into feature/oauth2-ui
jonasfranz Dec 26, 2018
e334f2a
Merge branch 'master' into feature/oauth2
jonasfranz Dec 26, 2018
8773029
Merge branch 'master' of https://github.com/go-gitea/gitea into featu…
jonasfranz Dec 31, 2018
f1ff7c9
Add counter for preventing using a refresh token twice
jonasfranz Dec 31, 2018
d4cc413
Merge branch 'feature/oauth2' into feature/oauth2-ui
jonasfranz Dec 31, 2018
ef14bf7
Improved the counter mechanics
jonasfranz Dec 31, 2018
31112ee
Merge branch 'feature/oauth2' into feature/oauth2-ui
jonasfranz Dec 31, 2018
df63692
Fix increase counter
jonasfranz Dec 31, 2018
f7b7173
Merge remote-tracking branch 'jonas/feature/oauth2' into feature/oauth2
jonasfranz Dec 31, 2018
68a0736
Add comments and fmt
jonasfranz Dec 31, 2018
8a95e72
Merge branch 'master' into feature/oauth2
jonasfranz Dec 31, 2018
72f4ec8
Merge branch 'master' into feature/oauth2
jonasfranz Jan 2, 2019
93c9994
Merge branch 'master' into feature/oauth2
kolaente Jan 6, 2019
a892670
Add PKCE support
jonasfranz Jan 7, 2019
8db5aba
Merge remote-tracking branch 'jonas/feature/oauth2' into feature/oauth2
jonasfranz Jan 7, 2019
a57014a
Merge branch 'master' into feature/oauth2
jonasfranz Jan 7, 2019
2b737a1
Add some unit tests for oauth2_applications
jonasfranz Jan 7, 2019
ddb4244
Merge remote-tracking branch 'jonas/feature/oauth2' into feature/oauth2
jonasfranz Jan 7, 2019
3116afc
Remove unused test
jonasfranz Jan 7, 2019
a89c4de
gofmt
jonasfranz Jan 7, 2019
6e96c77
Merge branch 'master' into feature/oauth2
jonasfranz Jan 15, 2019
14270e1
Add additional tests for OAuth2
jonasfranz Jan 29, 2019
0ab5390
Merge branch 'master' of https://github.com/go-gitea/gitea into featu…
jonasfranz Jan 29, 2019
a4bc672
Merge branch 'master' into feature/oauth2
jonasfranz Feb 1, 2019
84b927d
Merge branch 'jo/feature/oauth2' into jo/feature/oauth2-ui
kolaente Feb 1, 2019
d942c57
Add better secret
jonasfranz Feb 1, 2019
f874fc9
added new fancy design
kolaente Feb 1, 2019
e2919f8
Merge branch 'jo/feature/oauth2-ui' into jo/feature/oauth2
kolaente Feb 1, 2019
3a853e6
Merged ui branch
kolaente Feb 1, 2019
96fea41
Removed unnessecary types
kolaente Feb 1, 2019
72c734c
fixed type not working
kolaente Feb 1, 2019
edf900f
Removed unnessecary types
kolaente Feb 1, 2019
d1a2a02
Removed more unnecessary stuff
kolaente Feb 1, 2019
e0b9307
fixed tests
kolaente Feb 1, 2019
9ce3a3e
Add additional integration tests
jonasfranz Feb 1, 2019
7e7d524
Merge remote-tracking branch 'jonas/feature/oauth2' into feature/oauth2
jonasfranz Feb 1, 2019
e8baddb
UI improvements
kolaente Feb 1, 2019
d645c00
Fixed lint
kolaente Feb 1, 2019
124eab9
Show secrets after generating them
kolaente Feb 2, 2019
8143eeb
Merge branch 'master' into feature/oauth2
kolaente Feb 2, 2019
6e3b4c8
Merge remote-tracking branch 'jonas/feature/oauth2' into feature/oauth2
jonasfranz Feb 2, 2019
b26df39
Add additional integrations tests
jonasfranz Feb 2, 2019
f082e40
Merge branch 'master' of ssh://github.com/go-gitea/gitea into feature…
jonasfranz Feb 3, 2019
7250d4a
Add remove functionality to application settings
jonasfranz Feb 4, 2019
e58c161
Add edit functionality
jonasfranz Feb 4, 2019
792d8e5
Add copyright headers
jonasfranz Feb 4, 2019
3fcfdb5
Add regenerated stylessheet
jonasfranz Feb 4, 2019
7370e05
Merge branch 'master' into feature/oauth2
jonasfranz Feb 4, 2019
82102fa
Fix pgsql/mssql failures with increase counter
jonasfranz Feb 5, 2019
c193062
Merge branch 'master' into feature/oauth2
jonasfranz Feb 5, 2019
a428f1a
Fix wrong bearer detection
jonasfranz Feb 6, 2019
6278b7a
Merge remote-tracking branch 'jonas/feature/oauth2' into feature/oauth2
jonasfranz Feb 6, 2019
2b55fbb
Merge branch 'master' of https://github.com/go-gitea/gitea into featu…
jonasfranz Feb 6, 2019
c2243c9
Update CSS
jonasfranz Feb 6, 2019
5740c12
Apply changes by @lunny
jonasfranz Feb 27, 2019
2262795
Use session to delete applications
jonasfranz Feb 27, 2019
49e2fac
Merge branch 'master' of https://github.com/go-gitea/gitea into featu…
jonasfranz Feb 27, 2019
4bcc28b
Use separate json tag for grant_id
jonasfranz Feb 27, 2019
dc8dc55
Move session begin and commit
jonasfranz Mar 1, 2019
141ae6b
Add authorization error page
jonasfranz Mar 5, 2019
bdf6643
Merge remote-tracking branch 'jonas/feature/oauth2' into feature/oauth2
jonasfranz Mar 5, 2019
709e8d5
Add login as reserved username
jonasfranz Mar 5, 2019
5c31409
Merge branch 'master' of https://github.com/go-gitea/gitea into featu…
jonasfranz Mar 5, 2019
b3c6962
Merge branch 'master' into feature/oauth2
jonasfranz Mar 5, 2019
9e27fea
Merge branch 'master' into feature/oauth2
techknowlogick Mar 8, 2019
ff266f4
generate stylesheets
techknowlogick Mar 8, 2019
9d11393
status 400 instead of 500 because error is with user not server
techknowlogick Mar 8, 2019
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion Gopkg.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

23 changes: 23 additions & 0 deletions models/error.go
Original file line number Diff line number Diff line change
Expand Up @@ -1366,3 +1366,26 @@ func IsErrReviewNotExist(err error) bool {
func (err ErrReviewNotExist) Error() string {
return fmt.Sprintf("review does not exist [id: %d]", err.ID)
}

// ________ _____ __ .__
// \_____ \ / _ \ __ ___/ |_| |__
// / | \ / /_\ \| | \ __\ | \
// / | \/ | \ | /| | | Y \
// \_______ /\____|__ /____/ |__| |___| /
// \/ \/ \/

// ErrOAuthClientIDInvalid will be thrown if client id cannot be found
type ErrOAuthClientIDInvalid struct {
ClientID string
}

// IsErrOauthClientIDInvalid checks if an error is a ErrReviewNotExist.
func IsErrOauthClientIDInvalid(err error) bool {
_, ok := err.(ErrOAuthClientIDInvalid)
return ok
}

// Error returns the error message
func (err ErrOAuthClientIDInvalid) Error() string {
return fmt.Sprintf("Client ID invalid [Client ID: %s]", err.ClientID)
}
3 changes: 3 additions & 0 deletions models/models.go
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,9 @@ func init() {
new(U2FRegistration),
new(TeamUnit),
new(Review),
new(OAuth2Application),
new(OAuth2AuthorizationCode),
new(OAuth2Grant),
)

gonicNames := []string{"SSL", "UID"}
Expand Down
193 changes: 193 additions & 0 deletions models/oauth2_application.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
package models
jonasfranz marked this conversation as resolved.
Show resolved Hide resolved

import (
"net/url"

gouuid "github.com/satori/go.uuid"

jonasfranz marked this conversation as resolved.
Show resolved Hide resolved
"code.gitea.io/gitea/modules/util"
"github.com/Unknwon/com"

"golang.org/x/crypto/bcrypt"
)

// OAuth2Application represents an OAuth2 client (RFC 6749)
type OAuth2Application struct {
ID int64 `xorm:"pk autoincr"`
UID int64 `xorm:"INDEX"`
User *User `xorm:"-"`

Name string
jonasfranz marked this conversation as resolved.
Show resolved Hide resolved

ClientID string `xorm:"INDEX unique"`
ClientSecret string

RedirectURIs []string `xorm:"redirect_uris JSON TEXT"`

CreatedUnix util.TimeStamp `xorm:"INDEX created"`
UpdatedUnix util.TimeStamp `xorm:"INDEX updated"`
}

// TableName sets the table name to `oauth2_application`
func (app *OAuth2Application) TableName() string {
return "oauth2_application"
}

// LoadUser will load User by UID
func (app *OAuth2Application) LoadUser() (err error) {
app.User = new(User)
jonasfranz marked this conversation as resolved.
Show resolved Hide resolved
app.User, err = GetUserByID(app.UID)
return
}

// ContainsRedirectURI checks if redirectURI is allowed for app
func (app *OAuth2Application) ContainsRedirectURI(redirectURI string) bool {
return com.IsSliceContainsStr(app.RedirectURIs, redirectURI)
jonasfranz marked this conversation as resolved.
Show resolved Hide resolved
}

// GenerateClientSecret will generate the client secret and returns the plaintext and saves the hash at the database
func (app *OAuth2Application) GenerateClientSecret() ([]byte, error) {
secret := gouuid.NewV4().Bytes()
hashedSecret, err := bcrypt.GenerateFromPassword(secret, bcrypt.DefaultCost)
if err != nil {
return nil, err
}
app.ClientSecret = string(hashedSecret)
return secret, nil
}

// ValidateClientSecret validates the given secret by the hash saved in database
func (app *OAuth2Application) ValidateClientSecret(secret []byte) bool {
return bcrypt.CompareHashAndPassword([]byte(app.ClientSecret), secret) == nil
}

// GetGrantByUserID returns a OAuth2Grant by its user and application ID
func (app *OAuth2Application) GetGrantByUserID(userID int64) (*OAuth2Grant, error) {
return app.getGrantByUserID(x, userID)
}

func (app *OAuth2Application) getGrantByUserID(e Engine, userID int64) (grant *OAuth2Grant, err error) {
grant = new(OAuth2Grant)
if has, err := e.Where("user_id = ? AND application_id", userID, app.ID).Get(grant); err != nil {
jonasfranz marked this conversation as resolved.
Show resolved Hide resolved
return nil, err
} else if !has {
return nil, nil
}
return grant, nil
}

// CreateGrant generates a grant for an user
func (app *OAuth2Application) CreateGrant(userID int64) (*OAuth2Grant, error) {
return app.createGrant(x, userID)
}

func (app *OAuth2Application) createGrant(e Engine, userID int64) (*OAuth2Grant, error) {
grant := &OAuth2Grant{
ApplicationID: app.ID,
UserID: userID,
}
_, err := e.Insert(grant)
if err != nil {
return nil, err
}
return grant, nil
}

// GetOAuth2ApplicationByClientID returns the oauth2 application with the given client_id. Returns an error if not found.
func GetOAuth2ApplicationByClientID(clientID string) (app *OAuth2Application, err error) {
return getOAuth2ApplicationByClientID(x, clientID)
}

func getOAuth2ApplicationByClientID(e Engine, clientID string) (app *OAuth2Application, err error) {
app = new(OAuth2Application)
has, err := e.Where("client_id = ?", clientID).Get(app)
if !has {
return app, ErrOAuthClientIDInvalid{ClientID: clientID}
}
return
}

// CreateOAuth2Application inserts a new oauth2 application
func CreateOAuth2Application(name string, userID int64) (*OAuth2Application, error) {
return createOAuth2Application(x, name, userID)
}

func createOAuth2Application(e Engine, name string, userID int64) (*OAuth2Application, error) {
secret := gouuid.NewV4().String()
jonasfranz marked this conversation as resolved.
Show resolved Hide resolved
app := &OAuth2Application{
UID: userID,
Name: name,
ClientID: secret,
RedirectURIs: []string{"http://localhost:3000"},
jonasfranz marked this conversation as resolved.
Show resolved Hide resolved
}
if _, err := e.Insert(app); err != nil {
return nil, err
}
return app, nil
}

//////////////////////////////////////////////////////

// OAuth2AuthorizationCode is a code to obtain an access token in combination with the client secret once. It has a limited lifetime.
type OAuth2AuthorizationCode struct {
ID int64 `xorm:"pk autoincr"`
Grant *OAuth2Grant `xorm:"-"`
GrantID int64
Code string `xorm:"INDEX unique"`
RedirectURI string
Lifetime util.TimeStamp
}
jonasfranz marked this conversation as resolved.
Show resolved Hide resolved

// TableName sets the table name to `oauth2_authorization_code`
func (code *OAuth2AuthorizationCode) TableName() string {
return "oauth2_authorization_code"
}

// GenerateRedirectURI generates a redirect URI for a sucessfull authorization request. State will be used if not empty.
func (code *OAuth2AuthorizationCode) GenerateRedirectURI(state string) (redirect *url.URL, err error) {
if redirect, err = url.Parse(code.RedirectURI); err != nil {
return
}
q := redirect.Query()
if state != "" {
q.Set("state", state)
}
q.Set("code", code.Code)
redirect.RawQuery = q.Encode()
return
}

//////////////////////////////////////////////////////

// OAuth2Grant represents the permission of an user for a specifc application to access resources
type OAuth2Grant struct {
ID int64 `xorm:"pk autoincr"`
UserID int64 `xorm:"INDEX unique(user_application)"`
ApplicationID int64 `xorm:"INDEX unique(user_application)"`
CreatedUnix util.TimeStamp `xorm:"created"`
UpdatedUnix util.TimeStamp `xorm:"updated"`
}

// TableName sets the table name to `oauth2_grant`
func (grant *OAuth2Grant) TableName() string {
return "oauth2_grant"
}

// GenerateNewAuthorizationCode generates a new authroization code for a grant and saves it to the databse
func (grant *OAuth2Grant) GenerateNewAuthorizationCode(redirectURI string) (*OAuth2AuthorizationCode, error) {
return grant.generateNewAuthorizationCode(x, redirectURI)
}

func (grant *OAuth2Grant) generateNewAuthorizationCode(e Engine, redirectURI string) (*OAuth2AuthorizationCode, error) {
secret := gouuid.NewV4().String()
code := &OAuth2AuthorizationCode{
Grant: grant,
GrantID: grant.ID,
RedirectURI: redirectURI,
Code: secret,
}
if _, err := e.Insert(code); err != nil {
return nil, err
}
return code, nil
}
43 changes: 42 additions & 1 deletion modules/auth/user_form.go
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ func (f *MustChangePasswordForm) Validate(ctx *macaron.Context, errs binding.Err
return validate(errs, ctx.Data, f, ctx.Locale)
}

// SignInForm form for signing in with user/password
// AuthorizationForm form for signing in with user/password
jonasfranz marked this conversation as resolved.
Show resolved Hide resolved
type SignInForm struct {
UserName string `binding:"Required;MaxSize(254)"`
Password string `binding:"Required;MaxSize(255)"`
Expand All @@ -137,6 +137,47 @@ func (f *SignInForm) Validate(ctx *macaron.Context, errs binding.Errors) binding
return validate(errs, ctx.Data, f, ctx.Locale)
}

// AuthorizationForm form for authorizing oauth2 clients
type AuthorizationForm struct {
ResponseType string `binding:"Required;In(code)"`
ClientID string `binding:"Required"`
RedirectURI string
State string
}

// Validate valideates the fields
func (f *AuthorizationForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}

// GrantApplicationForm form for authorizing oauth2 clients
type GrantApplicationForm struct {
ClientID string `binding:"Required"`
RedirectURI string
State string
}

// Validate valideates the fields
func (f *GrantApplicationForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}

// AccessTokenForm for issuing access tokens from authorization codes or refresh tokens
type AccessTokenForm struct {
GrantType string `binding:"Required;In(authorization_code,refresh_token)"`
ClientID string `binding:"Required"`
ClientSecret string `binding:"Required"`
RedirectURI string
// TODO Specify authentication code length to prevent against birthday attacks
Code string
RefreshToken string
}

// Validate valideates the fields
func (f *AccessTokenForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}

// __________________________________________.___ _______ ________ _________
// / _____/\_ _____/\__ ___/\__ ___/| |\ \ / _____/ / _____/
// \_____ \ | __)_ | | | | | |/ | \/ \ ___ \_____ \
Expand Down
3 changes: 3 additions & 0 deletions options/locale/locale_en-US.ini
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,9 @@ openid_register_desc = The chosen OpenID URI is unknown. Associate it with a new
openid_signin_desc = Enter your OpenID URI. For example: https://anne.me, bob.openid.org.cn or gnusocial.net/carry.
disable_forgot_password_mail = Password reset is disabled. Please contact your site administrator.
email_domain_blacklisted = You cannot register with your email address.
authorize_application = Authorize application
authorize_application_description = %s by %s would like permission to access your account.
authroize_redirect_notice = You will be redirected to "%s" if you authrize this application.

[mail]
activate_account = Please activate your account
Expand Down
7 changes: 7 additions & 0 deletions routers/routes/routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,13 @@ func RegisterRoutes(m *macaron.Macaron) {
})
}, reqSignOut)

m.Group("/user/oauth2", func() {
m.Get("/authorize", bindIgnErr(auth.AuthorizationForm{}), user.AuthorizeOAuth)
m.Post("/grant", bindIgnErr(auth.GrantApplicationForm{}), user.GrantApplicationOAuth)
m.Post("/authorize", bindIgnErr(auth.AuthorizationForm{}), user.AuthorizeOAuth)
m.Post("/access_token", bindIgnErr(auth.AccessTokenForm{}), reqSignIn, user.AccessTokenOAuth)
}, reqSignIn)

m.Group("/user/settings", func() {
m.Get("", userSetting.Profile)
m.Post("", bindIgnErr(auth.UpdateProfileForm{}), userSetting.ProfilePost)
Expand Down
Loading