summaryrefslogtreecommitdiff
path: root/internal/oauth2/authorization.go
blob: 5854cb8c02ba24b352ae9fc0d8fa0a23f4bedd06 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package oauth2 // import "miniflux.app/v2/internal/oauth2"

import (
	"crypto/sha256"
	"encoding/base64"
	"io"

	"golang.org/x/oauth2"

	"miniflux.app/v2/internal/crypto"
)

type Authorization struct {
	url          string
	state        string
	codeVerifier string
}

func (u *Authorization) RedirectURL() string {
	return u.url
}

func (u *Authorization) State() string {
	return u.state
}

func (u *Authorization) CodeVerifier() string {
	return u.codeVerifier
}

func GenerateAuthorization(config *oauth2.Config) *Authorization {
	codeVerifier := crypto.GenerateRandomStringHex(32)

	sha2 := sha256.New()
	io.WriteString(sha2, codeVerifier)
	codeChallenge := base64.RawURLEncoding.EncodeToString(sha2.Sum(nil))

	state := crypto.GenerateRandomStringHex(24)

	authUrl := config.AuthCodeURL(
		state,
		oauth2.SetAuthURLParam("code_challenge_method", "S256"),
		oauth2.SetAuthURLParam("code_challenge", codeChallenge),
	)

	return &Authorization{
		url:          authUrl,
		state:        state,
		codeVerifier: codeVerifier,
	}
}