File size: 2,411 Bytes
e762600
 
 
 
 
 
7fc7e09
e762600
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7fc7e09
4c78a11
e762600
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
package services

import (
	"context"
	"errors"

	"github.com/google/uuid"
	"godp.abdanhafidz.com/models"
	"godp.abdanhafidz.com/repositories"
	"google.golang.org/api/idtoken"
)

type GoogleAuthService struct {
	Service[models.ExternalAuth, models.AuthenticatedUser]
}

func (s *GoogleAuthService) Authenticate(isAgree bool) {
	GoogleAuth := repositories.GetExternalAccountByOauthId(s.Constructor.OauthID)
	payload, errGoogleAuth := idtoken.Validate(context.Background(), s.Constructor.OauthID, "")
	s.Error = errGoogleAuth
	if errGoogleAuth != nil {
		s.Exception.Unauthorized = true
		s.Exception.Message = "Oauth Provider Failed Login (Google Authentication)"
		return
	}
	email := payload.Claims["email"]
	checkRegisteredEmail := repositories.GetAccountbyEmail(email.(string))
	if !checkRegisteredEmail.NoRecord {
		token, _ := GenerateToken(&checkRegisteredEmail.Result)
		checkRegisteredEmail.Result.Password = "SECRET"
		s.Result = models.AuthenticatedUser{
			Account: checkRegisteredEmail.Result,
			Token:   token,
		}
		return
	}
	if GoogleAuth.NoRecord {
		if !isAgree {
			s.Exception.BadRequest = true
			s.Exception.Message = "Please agree to the terms and conditions to create an account"
			return
		}
		s.Constructor.OauthProvider = "Google"

		createAccount := repositories.CreateAccount(models.Account{
			Id:              uuid.New(),
			Username:        payload.Claims["name"].(string),
			Email:           email.(string),
			IsEmailVerified: true,
		})

		s.Constructor.AccountId = createAccount.Result.Id
		createGoogleAuth := repositories.CreateExternalAuth(s.Constructor)

		GoogleAuth.Result.AccountId = createGoogleAuth.Result.AccountId
		userProfile := UserProfileService{}
		userProfile.Constructor.AccountId = GoogleAuth.Result.AccountId
		userProfile.Create()
		if userProfile.Error != nil {
			s.Error = userProfile.Error
			return
		}
		s.Error = createGoogleAuth.RowsError
		s.Error = errors.Join(s.Error, createAccount.RowsError)
	}

	accountData := repositories.GetAccountById(GoogleAuth.Result.AccountId)
	token, err_tok := GenerateToken(&accountData.Result)

	if err_tok != nil {
		s.Error = errors.Join(s.Error, err_tok)
	}

	accountData.Result.Password = "SECRET"
	s.Result = models.AuthenticatedUser{
		Account: accountData.Result,
		Token:   token,
	}
	s.Error = accountData.RowsError

}