aboutsummaryrefslogtreecommitdiff
path: root/internal/auth/service.go
blob: 99972647aad4d5ee8e3a2099ae5cc9fe4523b68f (plain)
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package auth

import (
	"errors"
	"log"
	"time"

	"golang.org/x/oauth2"

	"github.com/gbrlsnchs/jwt/v3"
)

var (
	singingSecret = jwt.NewHS512([]byte("the wolf says moo"))
	// ErrInvalidToken error for token
	ErrInvalidToken = errors.New("Invalid token provided")
	// ErrInvalidJWT error for jwt
	ErrInvalidJWT = errors.New("Invalid JWT")
	// ErrUnauthorized error for unauthorized access
	ErrUnauthorized = errors.New("Unauthorized")
)

// Servicer access to auth functionality
type Servicer interface {
	LoginOrRegisterSessionID(t *oauth2.Token, gp *GoogleAuthProfile) (string, bool, error)
	GenerateStateToken() (string, error)
	ValidateStateToken(token string, sessionToken string) (bool, error)
}

// Service a container for auth deps
type Service struct {
	repo Repo
}

// NewService create auth service
func NewService(repo Repo) *Service {
	return &Service{
		repo,
	}
}

// GenerateStateToken create a random token for oauth exchange
func (a *Service) GenerateStateToken() (string, error) {
	now := time.Now()
	pl := jwt.Payload{
		Issuer:   "iserv-state",
		Subject:  "state param",
		IssuedAt: jwt.NumericDate(now),
	}
	tokenBytes, err := jwt.Sign(pl, singingSecret)
	if err != nil {
		return "", err
	}
	return string(tokenBytes[:]), err
}

// ValidateStateToken validate provided token
func (a *Service) ValidateStateToken(token string, sessionToken string) (bool, error) {
	if token == sessionToken {
		p := jwt.Payload{}
		_, err := jwt.Verify([]byte(token), singingSecret, &p)
		if err != nil {
			return false, ErrInvalidJWT
		}
		return true, nil
	}
	return false, ErrInvalidToken
}

// LoginOrRegisterSessionID create a login
func (a *Service) LoginOrRegisterSessionID(t *oauth2.Token, gp *GoogleAuthProfile) (string, bool, error) {
	isAuthorized, err := a.repo.IsAuthorized(gp)
	newRegistration := false
	if err != nil {
		return "", newRegistration, err
	}
	if isAuthorized != true {
		return "", newRegistration, ErrUnauthorized
	}
	profileID, err := a.repo.LookUpAuthProfileID(gp)
	if err != nil {
		return "", newRegistration, err
	}
	if profileID == "" {
		// create profile
		log.Printf("creating new profile")
		profile := NewAuthProfile(t, gp)
		profileID = profile.ID
		log.Printf("new profile %+v", profile)
		err = a.repo.SaveAuthProfile(profile)
		if err != nil {
			return "", newRegistration, err
		}
		newRegistration = true
	}
	return profileID, newRegistration, nil
}