mirror of
https://github.com/go-gitea/gitea.git
synced 2024-12-22 22:48:12 +08:00
7b297808ce
Signed-off-by: Lauris Bukšis-Haberkorns <lauris@nix.lv>
64 lines
1.6 KiB
Go
64 lines
1.6 KiB
Go
package openidConnect
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"github.com/markbates/goth"
|
|
"golang.org/x/oauth2"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
// Session stores data during the auth process with the OpenID Connect provider.
|
|
type Session struct {
|
|
AuthURL string
|
|
AccessToken string
|
|
RefreshToken string
|
|
ExpiresAt time.Time
|
|
IDToken string
|
|
}
|
|
|
|
// GetAuthURL will return the URL set by calling the `BeginAuth` function on the OpenID Connect provider.
|
|
func (s Session) GetAuthURL() (string, error) {
|
|
if s.AuthURL == "" {
|
|
return "", errors.New("an AuthURL has not be set")
|
|
}
|
|
return s.AuthURL, nil
|
|
}
|
|
|
|
// Authorize the session with the OpenID Connect provider and return the access token to be stored for future use.
|
|
func (s *Session) Authorize(provider goth.Provider, params goth.Params) (string, error) {
|
|
p := provider.(*Provider)
|
|
token, err := p.config.Exchange(oauth2.NoContext, params.Get("code"))
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
if !token.Valid() {
|
|
return "", errors.New("Invalid token received from provider")
|
|
}
|
|
|
|
s.AccessToken = token.AccessToken
|
|
s.RefreshToken = token.RefreshToken
|
|
s.ExpiresAt = token.Expiry
|
|
s.IDToken = token.Extra("id_token").(string)
|
|
return token.AccessToken, err
|
|
}
|
|
|
|
// Marshal the session into a string
|
|
func (s Session) Marshal() string {
|
|
b, _ := json.Marshal(s)
|
|
return string(b)
|
|
}
|
|
|
|
func (s Session) String() string {
|
|
return s.Marshal()
|
|
}
|
|
|
|
// UnmarshalSession will unmarshal a JSON string into a session.
|
|
func (p *Provider) UnmarshalSession(data string) (goth.Session, error) {
|
|
sess := &Session{}
|
|
err := json.NewDecoder(strings.NewReader(data)).Decode(sess)
|
|
return sess, err
|
|
}
|