/
authentication.go
112 lines (93 loc) · 2.46 KB
/
authentication.go
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package services
import (
"context"
"errors"
"net/http"
"github.com/fapiko/john-hancock-platform/app/contracts"
"github.com/fapiko/john-hancock-platform/app/repositories"
"github.com/fapiko/john-hancock-platform/app/repositories/daos"
"github.com/fapiko/john-hancock-platform/app/utils"
"google.golang.org/api/idtoken"
)
var _ AuthService = (*AuthServiceImpl)(nil)
type OAuthClaims struct {
Email string
FirstName string
LastName string
}
type AuthService interface {
GetUserForRequest(ctx context.Context, r *http.Request) (*daos.User, error)
ValidateOAuthToken(
ctx context.Context,
provider string,
accessToken string,
) (*daos.User, error)
}
type AuthServiceImpl struct {
userRepository repositories.UserRepository
}
func (s *AuthServiceImpl) GetUserForRequest(ctx context.Context, r *http.Request) (
*daos.User,
error,
) {
sessionID := r.Header.Get("Authorization")
if sessionID == "" {
return nil, ErrUnauthorized
}
user, err := s.userRepository.GetUserBySessionID(ctx, sessionID)
if err != nil {
if err == repositories.ErrNoRecord {
return nil, ErrUnauthorized
}
return nil, err
}
return user, nil
}
func NewAuthService(userRepository repositories.UserRepository) AuthService {
return &AuthServiceImpl{
userRepository: userRepository,
}
}
func (s *AuthServiceImpl) ValidateOAuthToken(
ctx context.Context,
provider string,
accessToken string,
) (*daos.User, error) {
// TODO: CONFIGURE THIS
const aud = "834953141481-an55r41f085lol5fknij3rp5g9e8ho19.apps.googleusercontent.com"
payload, err := idtoken.Validate(ctx, accessToken, aud)
if err != nil {
return nil, err
}
claims := parseOAuthClaims(payload.Claims)
// See if user exists
user, err := s.userRepository.GetUserByEmail(ctx, payload.Claims["email"].(string))
if err != nil && errors.Is(err, repositories.ErrNoRecord) {
password, err := utils.GenerateRandomString(32)
if err != nil {
return nil, err
}
// Create user
user, err = s.userRepository.CreateUser(
ctx, &contracts.CreateUserRequest{
FirstName: claims.FirstName,
LastName: claims.LastName,
Email: claims.Email,
Password: password,
},
)
if err != nil {
return nil, err
}
} else if err != nil {
return nil, err
}
return user, nil
}
func parseOAuthClaims(claims map[string]interface{}) *OAuthClaims {
return &OAuthClaims{
Email: claims["email"].(string),
FirstName: claims["given_name"].(string),
LastName: claims["family_name"].(string),
}
}