2021-07-24 05:16:34 -05:00
|
|
|
// Copyright 2021 The Gitea Authors. All rights reserved.
|
2022-11-27 13:20:29 -05:00
|
|
|
// SPDX-License-Identifier: MIT
|
2021-07-24 05:16:34 -05:00
|
|
|
|
|
|
|
package oauth2
|
|
|
|
|
|
|
|
import (
|
2021-11-02 19:33:54 -05:00
|
|
|
"encoding/gob"
|
2021-07-24 05:16:34 -05:00
|
|
|
"net/http"
|
2021-07-29 12:53:18 -05:00
|
|
|
"sync"
|
2021-07-24 05:16:34 -05:00
|
|
|
|
2022-01-02 08:12:35 -05:00
|
|
|
"code.gitea.io/gitea/models/auth"
|
2021-07-24 05:16:34 -05:00
|
|
|
"code.gitea.io/gitea/modules/log"
|
|
|
|
"code.gitea.io/gitea/modules/setting"
|
|
|
|
|
|
|
|
"github.com/google/uuid"
|
2021-11-02 19:33:54 -05:00
|
|
|
"github.com/gorilla/sessions"
|
2021-07-24 05:16:34 -05:00
|
|
|
"github.com/markbates/goth/gothic"
|
|
|
|
)
|
|
|
|
|
2021-07-29 12:53:18 -05:00
|
|
|
var gothRWMutex = sync.RWMutex{}
|
|
|
|
|
2021-07-24 05:16:34 -05:00
|
|
|
// 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 12:53:18 -05:00
|
|
|
// Lock our mutex
|
|
|
|
gothRWMutex.Lock()
|
|
|
|
|
2021-11-02 19:33:54 -05:00
|
|
|
gob.Register(&sessions.Session{})
|
|
|
|
|
|
|
|
gothic.Store = &SessionsStore{
|
|
|
|
maxLength: int64(setting.OAuth2.MaxTokenLength),
|
|
|
|
}
|
2021-07-24 05:16:34 -05:00
|
|
|
|
|
|
|
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 12:53:18 -05:00
|
|
|
// Unlock our mutex
|
|
|
|
gothRWMutex.Unlock()
|
|
|
|
|
2022-01-02 08:12:35 -05:00
|
|
|
return initOAuth2Sources()
|
2021-07-24 05:16:34 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
// ResetOAuth2 clears existing OAuth2 providers and loads them from DB
|
|
|
|
func ResetOAuth2() error {
|
|
|
|
ClearProviders()
|
2022-01-02 08:12:35 -05:00
|
|
|
return initOAuth2Sources()
|
2021-07-24 05:16:34 -05:00
|
|
|
}
|
|
|
|
|
2022-01-02 08:12:35 -05:00
|
|
|
// initOAuth2Sources is used to load and register all active OAuth2 providers
|
|
|
|
func initOAuth2Sources() error {
|
|
|
|
authSources, _ := auth.GetActiveOAuth2ProviderSources()
|
|
|
|
for _, source := range authSources {
|
2021-07-24 05:16:34 -05:00
|
|
|
oauth2Source, ok := source.Cfg.(*Source)
|
|
|
|
if !ok {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
err := oauth2Source.RegisterSource()
|
|
|
|
if err != nil {
|
2021-07-29 12:53:18 -05:00
|
|
|
log.Critical("Unable to register source: %s due to Error: %v.", source.Name, err)
|
2021-07-24 05:16:34 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|