RezinaLMS-BackEnd/internal/services/authentication/google.go
n3p-tun3 a81fe3cd19 feat(auth): add learner device sessions with a 2-device limit
- Track learner sessions and revoke them immediately on every request
- Add a device replacement challenge for logins over the limit
- Add learner and admin endpoints to list and remove devices
- Trim excess sessions when enforcement is enabled
- Stop logging refresh tokens and authorization headers

Enforcement is off by default through DEVICE_LIMIT_ENFORCED.
2026-11-23 17:38:48 +03:00

229 lines
5.3 KiB
Go

package authentication
import (
"Rezina-Backend/internal/domain"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strings"
"cloud.google.com/go/auth/credentials/idtoken"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
)
var googleOAuthConfig *oauth2.Config
var ErrGoogleOAuthNotInitialized = errors.New("google oauth not initialized")
func (s *Service) InitGoogleOAuth(clientID, clientSecret, redirectURL string) {
if clientID == "" || clientSecret == "" || redirectURL == "" {
return
}
googleOAuthConfig = &oauth2.Config{
ClientID: clientID,
ClientSecret: clientSecret,
RedirectURL: redirectURL,
Scopes: []string{
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/userinfo.profile",
},
Endpoint: google.Endpoint,
}
}
func (s *Service) GenerateGoogleLoginURL(state string) string {
if googleOAuthConfig == nil {
return ""
}
return googleOAuthConfig.AuthCodeURL(state, oauth2.AccessTypeOffline)
}
func (s *Service) ExchangeGoogleCode(
ctx context.Context,
code string,
) (*oauth2.Token, error) {
if googleOAuthConfig == nil {
return nil, ErrGoogleOAuthNotInitialized
}
if code == "" {
return nil, errors.New("missing google auth code")
}
return googleOAuthConfig.Exchange(ctx, code)
}
func (s *Service) FetchGoogleUser(
ctx context.Context,
token *oauth2.Token,
) (*domain.GoogleUser, error) {
if googleOAuthConfig == nil {
return nil, ErrGoogleOAuthNotInitialized
}
if token == nil {
return nil, errors.New("missing google oauth token")
}
client := googleOAuthConfig.Client(ctx, token)
resp, err := client.Get("https://www.googleapis.com/oauth2/v2/userinfo")
if err != nil {
return nil, fmt.Errorf("failed to fetch google user: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("google userinfo failed: status=%d body=%s", resp.StatusCode, string(body))
}
var user domain.GoogleUser
if err := json.NewDecoder(resp.Body).Decode(&user); err != nil {
return nil, fmt.Errorf("failed to decode google user: %w", err)
}
if user.Email == "" {
return nil, errors.New("google account has no email")
}
return &user, nil
}
func PrimaryGoogleClientID(clientIDs string) string {
for _, id := range strings.Split(clientIDs, ",") {
if id = strings.TrimSpace(id); id != "" {
return id
}
}
return strings.TrimSpace(clientIDs)
}
func GoogleClientIDsForValidation(clientIDs ...string) []string {
seen := make(map[string]struct{})
out := make([]string, 0)
for _, group := range clientIDs {
for _, id := range strings.Split(group, ",") {
id = strings.TrimSpace(id)
if id == "" {
continue
}
if _, ok := seen[id]; ok {
continue
}
seen[id] = struct{}{}
out = append(out, id)
}
}
return out
}
func (s *Service) LoginWithGoogleAndroid(
ctx context.Context,
idToken string,
clientID string,
) (domain.LoginSuccess, error) {
return s.LoginWithGoogleIDToken(ctx, idToken, GoogleClientIDsForValidation(clientID))
}
func (s *Service) LoginWithGoogleIDToken(
ctx context.Context,
idToken string,
clientIDs []string,
) (domain.LoginSuccess, error) {
if idToken == "" {
return domain.LoginSuccess{}, errors.New("missing id token")
}
if len(clientIDs) == 0 {
return domain.LoginSuccess{}, errors.New("missing google client id")
}
var (
payload *idtoken.Payload
lastErr error
)
for _, clientID := range clientIDs {
payload, lastErr = idtoken.Validate(ctx, idToken, clientID)
if lastErr == nil {
break
}
}
if payload == nil {
return domain.LoginSuccess{}, fmt.Errorf("invalid google id token: %w", lastErr)
}
email, _ := payload.Claims["email"].(string)
if email == "" {
return domain.LoginSuccess{}, errors.New("google id token missing email")
}
verified := false
switch v := payload.Claims["email_verified"].(type) {
case bool:
verified = v
case string:
verified = (v == "true")
}
givenName, _ := payload.Claims["given_name"].(string)
familyName, _ := payload.Claims["family_name"].(string)
picture, _ := payload.Claims["picture"].(string)
gUser := domain.GoogleUser{
ID: payload.Subject,
Email: email,
VerifiedEmail: verified,
GivenName: givenName,
FamilyName: familyName,
Picture: picture,
}
return s.LoginWithGoogle(ctx, gUser)
}
func (s *Service) LoginWithGoogle(
ctx context.Context,
gUser domain.GoogleUser,
) (domain.LoginSuccess, error) {
user, isNewAccount, err := s.resolveGoogleUser(ctx, gUser)
if err != nil {
return domain.LoginSuccess{}, err
}
if err := domain.ValidateUserCanAuthenticate(user.Status); err != nil {
return domain.LoginSuccess{}, err
}
if user.Role.IsCustomerLearnerRole() {
return domain.LoginSuccess{UserId: user.ID, Role: user.Role, IsNewAccount: isNewAccount}, nil
}
refreshToken, err := s.issueLegacyRefreshToken(ctx, user.ID)
if err != nil {
return domain.LoginSuccess{}, err
}
return domain.LoginSuccess{
UserId: user.ID,
Role: user.Role,
RfToken: refreshToken,
IsNewAccount: isNewAccount,
}, nil
}
func (s *Service) verifyGoogleIDToken(
ctx context.Context,
idToken string,
clientID string,
) (*idtoken.Payload, error) {
payload, err := idtoken.Validate(ctx, idToken, clientID)
if err != nil {
return nil, err
}
return payload, nil
}