2021-07-24 15:46:34 +05:30
|
|
|
// Copyright 2021 The Gitea Authors. All rights reserved.
|
|
|
|
// Use of this source code is governed by a MIT-style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
|
|
|
package oauth2
|
|
|
|
|
|
|
|
import (
|
2021-11-03 06:03:54 +05:30
|
|
|
"encoding/gob"
|
2021-07-24 15:46:34 +05:30
|
|
|
"net/http"
|
2021-07-29 23:23:18 +05:30
|
|
|
"sync"
|
2021-07-24 15:46:34 +05:30
|
|
|
|
2021-09-24 17:02:56 +05:30
|
|
|
"code.gitea.io/gitea/models/login"
|
2021-07-24 15:46:34 +05:30
|
|
|
"code.gitea.io/gitea/modules/log"
|
|
|
|
"code.gitea.io/gitea/modules/setting"
|
|
|
|
|
|
|
|
"github.com/google/uuid"
|
2021-11-03 06:03:54 +05:30
|
|
|
"github.com/gorilla/sessions"
|
2021-07-24 15:46:34 +05:30
|
|
|
"github.com/markbates/goth/gothic"
|
|
|
|
)
|
|
|
|
|
2021-07-29 23:23:18 +05:30
|
|
|
var gothRWMutex = sync.RWMutex{}
|
|
|
|
|
2021-07-24 15:46:34 +05:30
|
|
|
// UsersStoreKey is the key for the store
|
|
|
|
const UsersStoreKey = "gitea-oauth2-sessions"
|
|
|
|
|
|
|
|
// ProviderHeaderKey is the HTTP header key
|
|
|
|
const ProviderHeaderKey = "gitea-oauth2-provider"
|
|
|
|
|
|
|
|
// Init initializes the oauth source
|
|
|
|
func Init() error {
|
|
|
|
if err := InitSigningKey(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2021-07-29 23:23:18 +05:30
|
|
|
// Lock our mutex
|
|
|
|
gothRWMutex.Lock()
|
|
|
|
|
2021-11-03 06:03:54 +05:30
|
|
|
gob.Register(&sessions.Session{})
|
|
|
|
|
|
|
|
gothic.Store = &SessionsStore{
|
|
|
|
maxLength: int64(setting.OAuth2.MaxTokenLength),
|
|
|
|
}
|
2021-07-24 15:46:34 +05:30
|
|
|
|
|
|
|
gothic.SetState = func(req *http.Request) string {
|
|
|
|
return uuid.New().String()
|
|
|
|
}
|
|
|
|
|
|
|
|
gothic.GetProviderName = func(req *http.Request) (string, error) {
|
|
|
|
return req.Header.Get(ProviderHeaderKey), nil
|
|
|
|
}
|
|
|
|
|
2021-07-29 23:23:18 +05:30
|
|
|
// Unlock our mutex
|
|
|
|
gothRWMutex.Unlock()
|
|
|
|
|
2021-07-24 15:46:34 +05:30
|
|
|
return initOAuth2LoginSources()
|
|
|
|
}
|
|
|
|
|
|
|
|
// ResetOAuth2 clears existing OAuth2 providers and loads them from DB
|
|
|
|
func ResetOAuth2() error {
|
|
|
|
ClearProviders()
|
|
|
|
return initOAuth2LoginSources()
|
|
|
|
}
|
|
|
|
|
|
|
|
// initOAuth2LoginSources is used to load and register all active OAuth2 providers
|
|
|
|
func initOAuth2LoginSources() error {
|
2021-09-24 17:02:56 +05:30
|
|
|
loginSources, _ := login.GetActiveOAuth2ProviderLoginSources()
|
2021-07-24 15:46:34 +05:30
|
|
|
for _, source := range loginSources {
|
|
|
|
oauth2Source, ok := source.Cfg.(*Source)
|
|
|
|
if !ok {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
err := oauth2Source.RegisterSource()
|
|
|
|
if err != nil {
|
2021-07-29 23:23:18 +05:30
|
|
|
log.Critical("Unable to register source: %s due to Error: %v.", source.Name, err)
|
2021-07-24 15:46:34 +05:30
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|